title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Left Leaning Red Black Tree (Insertion)
09 Jul, 2022 Prerequisites : Red – Black Trees.A left leaning Red Black Tree or (LLRB), is a variant of red black tree, which is a lot easier to implement than Red black tree itself and guarantees all the search, delete and insert operations in O(logn) time. Which nodes are RED and Which are Black ? Nodes which have double incoming edge are RED in color. Nodes which have single incoming edge are BLACK in color. Characteristics of LLRB 1. Root node is Always BLACK in color. 2. Every new Node inserted is always RED in color. 3. Every NULL child of a node is considered as BLACK in color. Eg : only 40 is present in tree. root | 40 <-- as 40 is the root so it / \ is also Black in color. NULL NULL <-- Black in color. 4. There should not be a node which has RIGHT RED child and LEFT BLACK child(or NULL child as all NULLS are BLACK) if present , left rotate the node, and swap the colors of current node and its LEFT child so as to maintain consistency for rule 2 i.e., new node must be RED in color. CASE 1. root root | || 40 LeftRotate(40) 50 / \\ ---> / \ NULL 50 40 NULL root | ColorSwap(50, 40) 50 ---> // \ 40 NULL 5. There should not be a node which has LEFT RED child and LEFT RED grandchild, if present Right Rotate the node and swap the colors between node and it’s RIGHT child to follow rule 2. CASE 2. root root | || 40 RightRotate(40) 20 // \ ---> // \ 20 50 10 40 // \ 10 50 root | ColorSwap(20, 40) 20 ---> // \\ 10 40 \ 50 6. There should not be a node which has LEFT RED child and RIGHT RED child, if present Invert the colors of all nodes i. e., current_node, LEFT child, and RIGHT child. CASE 3. root root | !color(20, 10, 30) || 20 ---> 20 // \\ / \ 10 30 10 30 root As the root is always black | ---> 20 / \ 10 30 Why are we following the above mentioned rules? Because by following above characteristics/rules we are able to simulate all the red-black tree’s properties without caring about the complex implementation of it. Example: Insert the following data into LEFT LEANING RED-BLACK TREE and display the inorder traversal of tree. Input : 10 20 30 40 50 25 Output : 10 20 30 40 50 25 root | 40 // \ 20 50 / \ 10 30 // 25 Approach : Insertions in the LLRB is exactly like inserting into a Binary search tree . The difference is that After we insert the node into the tree we will retrace our steps back to root and try to enforce the above rules for LLRB. While doing the above rotations and swapping of color it may happen that our root becomes RED in color so we also. We have to make sure that our root remains always BLACK in color. C++ C Java C# Javascript // C++ program to implement insert operation// in Red Black Tree.#include <bits/stdc++.h>using namespace std; typedef struct node{ struct node *left, *right; int data; // red ==> true, black ==> false bool color; }node; // Utility function to create a node.node* createNode(int data, bool color){ node *myNode = new node(); myNode -> left = myNode -> right = NULL; myNode -> data = data; // New Node which is created is // always red in color. myNode -> color = true; return myNode;} // Utility function to rotate node anticlockwise.node* rotateLeft(node* myNode){ cout << "left rotation!!\n"; node *child = myNode -> right; node *childLeft = child -> left; child -> left = myNode; myNode -> right = childLeft; return child;} // Utility function to rotate node clockwise.node* rotateRight(node* myNode){ cout << "right rotation\n"; node *child = myNode -> left; node *childRight = child -> right; child -> right = myNode; myNode -> left = childRight; return child;} // Utility function to check whether// node is red in color or not.int isRed(node *myNode){ if (myNode == NULL) return 0; return (myNode -> color == true);} // Utility function to swap color of two// nodes.void swapColors(node *node1, node *node2){ bool temp = node1 -> color; node1 -> color = node2 -> color; node2 -> color = temp;} // Insertion into Left Leaning Red Black Tree.node* insert(node* myNode, int data){ // Normal insertion code for any Binary // Search tree. if (myNode == NULL) return createNode(data, false); if (data < myNode -> data) myNode -> left = insert(myNode -> left, data); else if (data > myNode -> data) myNode -> right = insert(myNode -> right, data); else return myNode; // case 1. // when right child is Red but left child is // Black or doesn't exist. if (isRed(myNode -> right) && !isRed(myNode -> left)) { // Left rotate the node to make it into // valid structure. myNode = rotateLeft(myNode); // Swap the colors as the child node // should always be red swapColors(myNode, myNode -> left); } // case 2 // when left child as well as left grand // child in Red if (isRed(myNode -> left) && isRed(myNode -> left -> left)) { // Right rotate the current node to make // it into a valid structure. myNode = rotateRight(myNode); swapColors(myNode, myNode -> right); } // case 3 // when both left and right child are Red in color. if (isRed(myNode -> left) && isRed(myNode -> right)) { // Invert the color of node as well // it's left and right child. myNode -> color = !myNode -> color; // Change the color to black. myNode -> left -> color = false; myNode -> right -> color = false; } return myNode;} // Inorder traversalvoid inorder(node *node){ if (node) { inorder(node -> left); cout<< node -> data << " "; inorder(node -> right); }} // Driver codeint main(){ node *root = NULL; /* LLRB tree made after all insertions are made. 1. Nodes which have double INCOMING edge means that they are RED in color. 2. Nodes which have single INCOMING edge means that they are BLACK in color. root | 40 // \ 20 50 / \ 10 30 // 25 */ root = insert(root, 10); // To make sure that root remains // black is color root -> color = false; root = insert(root, 20); root -> color = false; root = insert(root, 30); root -> color = false; root = insert(root, 40); root -> color = false; root = insert(root, 50); root -> color = false; root = insert(root, 25); root -> color = false; // Display the tree through inorder traversal. inorder(root); return 0;} // This code is contributed by rutvik_56 // C program to implement insert operation// in Red Black Tree.#include <stdio.h>#include <stdlib.h>#include <stdbool.h> typedef struct node{ struct node *left, *right; int data; // red ==> true, black ==> false bool color;} node; // utility function to create a node.node* createNode(int data, bool color){ node *myNode = (node *) malloc(sizeof(node)); myNode -> left = myNode -> right = NULL; myNode -> data = data; // New Node which is created is // always red in color. myNode -> color = true; return myNode;} // utility function to rotate node anticlockwise.node* rotateLeft(node* myNode){ printf("left rotation!!\n"); node *child = myNode -> right; node *childLeft = child -> left; child -> left = myNode; myNode -> right = childLeft; return child;} // utility function to rotate node clockwise.node* rotateRight(node* myNode){ printf("right rotation\n"); node *child = myNode -> left; node *childRight = child -> right; child -> right = myNode; myNode -> left = childRight; return child;} // utility function to check whether// node is red in color or not.int isRed(node *myNode){ if (myNode == NULL) return 0; return (myNode -> color == true);} // utility function to swap color of two// nodes.void swapColors(node *node1, node *node2){ bool temp = node1 -> color; node1 -> color = node2 -> color; node2 -> color = temp;} // insertion into Left Leaning Red Black Tree.node* insert(node* myNode, int data){ // Normal insertion code for any Binary // Search tree. if (myNode == NULL) return createNode(data, false); if (data < myNode -> data) myNode -> left = insert(myNode -> left, data); else if (data > myNode -> data) myNode -> right = insert(myNode -> right, data); else return myNode; // case 1. // when right child is Red but left child is // Black or doesn't exist. if (isRed(myNode -> right) && !isRed(myNode -> left)) { // left rotate the node to make it into // valid structure. myNode = rotateLeft(myNode); // swap the colors as the child node // should always be red swapColors(myNode, myNode -> left); } // case 2 // when left child as well as left grand child in Red if (isRed(myNode -> left) && isRed(myNode -> left -> left)) { // right rotate the current node to make // it into a valid structure. myNode = rotateRight(myNode); swapColors(myNode, myNode -> right); } // case 3 // when both left and right child are Red in color. if (isRed(myNode -> left) && isRed(myNode -> right)) { // invert the color of node as well // it's left and right child. myNode -> color = !myNode -> color; // change the color to black. myNode -> left -> color = false; myNode -> right -> color = false; } return myNode;} // Inorder traversalvoid inorder(node *node){ if (node) { inorder(node -> left); printf("%d ", node -> data); inorder(node -> right); }} // Driver functionint main(){ node *root = NULL; /* LLRB tree made after all insertions are made. 1. Nodes which have double INCOMING edge means that they are RED in color. 2. Nodes which have single INCOMING edge means that they are BLACK in color. root | 40 // \ 20 50 / \ 10 30 // 25 */ root = insert(root, 10); // to make sure that root remains // black is color root -> color = false; root = insert(root, 20); root -> color = false; root = insert(root, 30); root -> color = false; root = insert(root, 40); root -> color = false; root = insert(root, 50); root -> color = false; root = insert(root, 25); root -> color = false; // display the tree through inorder traversal. inorder(root); return 0;} // Java program to implement insert operation// in Red Black Tree. class node{ node left, right; int data; // red ==> true, black ==> false boolean color; node(int data) { this.data = data; left = null; right = null; // New Node which is created is // always red in color. color = true; }} public class LLRBTREE { private static node root = null; // utility function to rotate node anticlockwise. node rotateLeft(node myNode) { System.out.printf("left rotation!!\n"); node child = myNode.right; node childLeft = child.left; child.left = myNode; myNode.right = childLeft; return child; } // utility function to rotate node clockwise. node rotateRight(node myNode) { System.out.printf("right rotation\n"); node child = myNode.left; node childRight = child.right; child.right = myNode; myNode.left = childRight; return child; } // utility function to check whether // node is red in color or not. boolean isRed(node myNode) { if (myNode == null) return false; return (myNode.color == true); } // utility function to swap color of two // nodes. void swapColors(node node1, node node2) { boolean temp = node1.color; node1.color = node2.color; node2.color = temp; } // insertion into Left Leaning Red Black Tree. node insert(node myNode, int data) { // Normal insertion code for any Binary // Search tree. if (myNode == null) return new node(data); if (data < myNode.data) myNode.left = insert(myNode.left, data); else if (data > myNode.data) myNode.right = insert(myNode.right, data); else return myNode; // case 1. // when right child is Red but left child is // Black or doesn't exist. if (isRed(myNode.right) && !isRed(myNode.left)) { // left rotate the node to make it into // valid structure. myNode = rotateLeft(myNode); // swap the colors as the child node // should always be red swapColors(myNode, myNode.left); } // case 2 // when left child as well as left grand child in Red if (isRed(myNode.left) && isRed(myNode.left.left)) { // right rotate the current node to make // it into a valid structure. myNode = rotateRight(myNode); swapColors(myNode, myNode.right); } // case 3 // when both left and right child are Red in color. if (isRed(myNode.left) && isRed(myNode.right)) { // invert the color of node as well // it's left and right child. myNode.color = !myNode.color; // change the color to black. myNode.left.color = false; myNode.right.color = false; } return myNode; } // Inorder traversal void inorder(node node) { if (node != null) { inorder(node.left); System.out.print(node.data + " "); inorder(node.right); } } public static void main(String[] args) { /* LLRB tree made after all insertions are made. 1. Nodes which have double INCOMING edge means that they are RED in color. 2. Nodes which have single INCOMING edge means that they are BLACK in color. root | 40 // \ 20 50 / \ 10 30 // 25 */ LLRBTREE node = new LLRBTREE(); root = node.insert(root, 10); // to make sure that root remains // black is color root.color = false; root = node.insert(root, 20); root.color = false; root = node.insert(root, 30); root.color = false; root = node.insert(root, 40); root.color = false; root = node.insert(root, 50); root.color = false; root = node.insert(root, 25); root.color = false; // display the tree through inorder traversal. node.inorder(root); } } // This code is contributed by ARSHPREET_SINGH // C# program to implement insert// operation in Red Black Tree.using System; class node{ public node left, right; public int data; // red ==> true, black ==> false public Boolean color; public node(int data) { this.data = data; left = null; right = null; // New Node which is created // is always red in color. color = true; }} public class LLRBTREE{ private static node root = null; // utility function to rotate// node anticlockwise.node rotateLeft(node myNode){ Console.Write("left rotation!!\n"); node child = myNode.right; node childLeft = child.left; child.left = myNode; myNode.right = childLeft; return child;} // utility function to rotate// node clockwise.node rotateRight(node myNode){ Console.Write("right rotation\n"); node child = myNode.left; node childRight = child.right; child.right = myNode; myNode.left = childRight; return child;} // utility function to check whether// node is red in color or not.Boolean isRed(node myNode){ if (myNode == null) return false; return (myNode.color == true);} // utility function to swap// color of two nodes.void swapColors(node node1, node node2){ Boolean temp = node1.color; node1.color = node2.color; node2.color = temp;} // insertion into Left// Leaning Red Black Tree.node insert(node myNode, int data){ // Normal insertion code for // any Binary Search tree. if (myNode == null) return new node(data); if (data < myNode.data) myNode.left = insert(myNode.left, data); else if (data > myNode.data) myNode.right = insert(myNode.right, data); else return myNode; // case 1. // when right child is Red // but left child is // Black or doesn't exist. if (isRed(myNode.right) && !isRed(myNode.left)) { // left rotate the node to make // it into valid structure. myNode = rotateLeft(myNode); // swap the colors as the child // node should always be red swapColors(myNode, myNode.left); } // case 2 // when left child as well as // left grand child in Red if (isRed(myNode.left) && isRed(myNode.left.left)) { // right rotate the current node // to make it into a valid structure. myNode = rotateRight(myNode); swapColors(myNode, myNode.right); } // case 3 // when both left and right // child are Red in color. if (isRed(myNode.left) && isRed(myNode.right)) { // invert the color of node as well // it's left and right child. myNode.color = !myNode.color; // change the color to black. myNode.left.color = false; myNode.right.color = false; } return myNode;} // Inorder traversalvoid inorder(node node){ if (node != null) { inorder(node.left); Console.Write(node.data + " "); inorder(node.right); }} // Driver Codestatic public void Main(String []args){/* LLRB tree made after all insertions are made. 1. Nodes which have double INCOMING edge means that they are RED in color.2. Nodes which have single INCOMING edge means that they are BLACK in color. root | 40 // \ 20 50 / \ 10 30 // 25*/ LLRBTREE node = new LLRBTREE(); root = node.insert(root, 10); // to make sure that root // remains black is colorroot.color = false; root = node.insert(root, 20);root.color = false; root = node.insert(root, 30);root.color = false; root = node.insert(root, 40);root.color = false; root = node.insert(root, 50);root.color = false; root = node.insert(root, 25);root.color = false; // display the tree through// inorder traversal.node.inorder(root);}} // This code is contributed// by Arnab Kundu <script>// Javascript program to implement insert operation// in Red Black Tree. class node{ constructor(data) { this.data = data; this.left = null; this.right = null; // New Node which is created is // always red in color. this.color = true; }} let root = null; // utility function to rotate node anticlockwise.function rotateLeft(myNode){ document.write("left rotation!!<br>"); let child = myNode.right; let childLeft = child.left; child.left = myNode; myNode.right = childLeft; return child;} // utility function to rotate node clockwise.function rotateRight(myNode){ document.write("right rotation<br>"); let child = myNode.left; let childRight = child.right; child.right = myNode; myNode.left = childRight; return child;} // utility function to check whether // node is red in color or not.function isRed(myNode){ if (myNode == null) return false; return (myNode.color == true);} // utility function to swap color of two // nodes.function swapColors(node1,node2){ let temp = node1.color; node1.color = node2.color; node2.color = temp;} // insertion into Left Leaning Red Black Tree.function insert(myNode,data){ // Normal insertion code for any Binary // Search tree. if (myNode == null) return new node(data); if (data < myNode.data) myNode.left = insert(myNode.left, data); else if (data > myNode.data) myNode.right = insert(myNode.right, data); else return myNode; // case 1. // when right child is Red but left child is // Black or doesn't exist. if (isRed(myNode.right) && !isRed(myNode.left)) { // left rotate the node to make it into // valid structure. myNode = rotateLeft(myNode); // swap the colors as the child node // should always be red swapColors(myNode, myNode.left); } // case 2 // when left child as well as left grand child in Red if (isRed(myNode.left) && isRed(myNode.left.left)) { // right rotate the current node to make // it into a valid structure. myNode = rotateRight(myNode); swapColors(myNode, myNode.right); } // case 3 // when both left and right child are Red in color. if (isRed(myNode.left) && isRed(myNode.right)) { // invert the color of node as well // it's left and right child. myNode.color = !myNode.color; // change the color to black. myNode.left.color = false; myNode.right.color = false; } return myNode;} // Inorder traversalfunction inorder(node){ if (node != null) { inorder(node.left); document.write(node.data + " "); inorder(node.right); }} /* LLRB tree made after all insertions are made. 1. Nodes which have double INCOMING edge means that they are RED in color. 2. Nodes which have single INCOMING edge means that they are BLACK in color. root | 40 // \ 20 50 / \ 10 30 // 25 */ root = insert(root, 10);// to make sure that root remains// black is colorroot.color = false; root = insert(root, 20);root.color = false; root = insert(root, 30);root.color = false; root = insert(root, 40);root.color = false; root = insert(root, 50);root.color = false; root = insert(root, 25);root.color = false; // display the tree through inorder traversal.inorder(root); // This code is contributed by avanitrachhadiya2155</script> Output: left rotation!! left rotation!! left rotation!! 10 20 25 30 40 50 Time Complexity: O(log n)References Left Leaning Red Black Trees This article is contributed by Arshpreet Soodan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. andrew1234 Akanksha_Rai rutvik_56 avanitrachhadiya2155 sagartomar9927 rishabhmathur612 Red Black Tree Self-Balancing-BST Advanced Computer Subject Binary Search Tree Binary Search Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n09 Jul, 2022" }, { "code": null, "e": 298, "s": 52, "text": "Prerequisites : Red – Black Trees.A left leaning Red Black Tree or (LLRB), is a variant of red black tree, which is a lot easier to implement than Red black tree itself and guarantees all the search, delete and insert operations in O(logn) time." }, { "code": null, "e": 454, "s": 298, "text": "Which nodes are RED and Which are Black ? Nodes which have double incoming edge are RED in color. Nodes which have single incoming edge are BLACK in color." }, { "code": null, "e": 665, "s": 454, "text": "Characteristics of LLRB 1. Root node is Always BLACK in color. 2. Every new Node inserted is always RED in color. 3. Every NULL child of a node is considered as BLACK in color. Eg : only 40 is present in tree. " }, { "code": null, "e": 799, "s": 665, "text": " \n root\n |\n 40 <-- as 40 is the root so it \n / \\ is also Black in color. \n NULL NULL <-- Black in color." }, { "code": null, "e": 1083, "s": 799, "text": "4. There should not be a node which has RIGHT RED child and LEFT BLACK child(or NULL child as all NULLS are BLACK) if present , left rotate the node, and swap the colors of current node and its LEFT child so as to maintain consistency for rule 2 i.e., new node must be RED in color. " }, { "code": null, "e": 1542, "s": 1083, "text": " CASE 1.\n root root \n | || \n 40 LeftRotate(40) 50 \n / \\\\ ---> / \\ \n NULL 50 40 NULL \n\n root \n | \n ColorSwap(50, 40) 50 \n ---> // \\ \n 40 NULL " }, { "code": null, "e": 1728, "s": 1542, "text": "5. There should not be a node which has LEFT RED child and LEFT RED grandchild, if present Right Rotate the node and swap the colors between node and it’s RIGHT child to follow rule 2. " }, { "code": null, "e": 2276, "s": 1728, "text": " CASE 2.\n root root \n | || \n 40 RightRotate(40) 20 \n // \\ ---> // \\ \n 20 50 10 40 \n // \\ \n10 50\n\n root\n |\n ColorSwap(20, 40) 20\n ---> // \\\\\n 10 40\n \\\n 50\n " }, { "code": null, "e": 2445, "s": 2276, "text": "6. There should not be a node which has LEFT RED child and RIGHT RED child, if present Invert the colors of all nodes i. e., current_node, LEFT child, and RIGHT child. " }, { "code": null, "e": 2919, "s": 2445, "text": " CASE 3.\n root root \n | !color(20, 10, 30) || \n 20 ---> 20 \n // \\\\ / \\ \n 10 30 10 30 \n\n root\n As the root is always black | \n ---> 20 \n / \\\n 10 30 " }, { "code": null, "e": 3132, "s": 2919, "text": "Why are we following the above mentioned rules? Because by following above characteristics/rules we are able to simulate all the red-black tree’s properties without caring about the complex implementation of it. " }, { "code": null, "e": 3142, "s": 3132, "text": "Example: " }, { "code": null, "e": 3405, "s": 3142, "text": "Insert the following data into LEFT LEANING RED-BLACK\nTREE and display the inorder traversal of tree.\nInput : 10 20 30 40 50 25\nOutput : 10 20 30 40 50 25\n root\n |\n 40\n // \\\n 20 50\n / \\\n 10 30\n //\n 25 " }, { "code": null, "e": 3822, "s": 3405, "text": "Approach : Insertions in the LLRB is exactly like inserting into a Binary search tree . The difference is that After we insert the node into the tree we will retrace our steps back to root and try to enforce the above rules for LLRB. While doing the above rotations and swapping of color it may happen that our root becomes RED in color so we also. We have to make sure that our root remains always BLACK in color. " }, { "code": null, "e": 3826, "s": 3822, "text": "C++" }, { "code": null, "e": 3828, "s": 3826, "text": "C" }, { "code": null, "e": 3833, "s": 3828, "text": "Java" }, { "code": null, "e": 3836, "s": 3833, "text": "C#" }, { "code": null, "e": 3847, "s": 3836, "text": "Javascript" }, { "code": "// C++ program to implement insert operation// in Red Black Tree.#include <bits/stdc++.h>using namespace std; typedef struct node{ struct node *left, *right; int data; // red ==> true, black ==> false bool color; }node; // Utility function to create a node.node* createNode(int data, bool color){ node *myNode = new node(); myNode -> left = myNode -> right = NULL; myNode -> data = data; // New Node which is created is // always red in color. myNode -> color = true; return myNode;} // Utility function to rotate node anticlockwise.node* rotateLeft(node* myNode){ cout << \"left rotation!!\\n\"; node *child = myNode -> right; node *childLeft = child -> left; child -> left = myNode; myNode -> right = childLeft; return child;} // Utility function to rotate node clockwise.node* rotateRight(node* myNode){ cout << \"right rotation\\n\"; node *child = myNode -> left; node *childRight = child -> right; child -> right = myNode; myNode -> left = childRight; return child;} // Utility function to check whether// node is red in color or not.int isRed(node *myNode){ if (myNode == NULL) return 0; return (myNode -> color == true);} // Utility function to swap color of two// nodes.void swapColors(node *node1, node *node2){ bool temp = node1 -> color; node1 -> color = node2 -> color; node2 -> color = temp;} // Insertion into Left Leaning Red Black Tree.node* insert(node* myNode, int data){ // Normal insertion code for any Binary // Search tree. if (myNode == NULL) return createNode(data, false); if (data < myNode -> data) myNode -> left = insert(myNode -> left, data); else if (data > myNode -> data) myNode -> right = insert(myNode -> right, data); else return myNode; // case 1. // when right child is Red but left child is // Black or doesn't exist. if (isRed(myNode -> right) && !isRed(myNode -> left)) { // Left rotate the node to make it into // valid structure. myNode = rotateLeft(myNode); // Swap the colors as the child node // should always be red swapColors(myNode, myNode -> left); } // case 2 // when left child as well as left grand // child in Red if (isRed(myNode -> left) && isRed(myNode -> left -> left)) { // Right rotate the current node to make // it into a valid structure. myNode = rotateRight(myNode); swapColors(myNode, myNode -> right); } // case 3 // when both left and right child are Red in color. if (isRed(myNode -> left) && isRed(myNode -> right)) { // Invert the color of node as well // it's left and right child. myNode -> color = !myNode -> color; // Change the color to black. myNode -> left -> color = false; myNode -> right -> color = false; } return myNode;} // Inorder traversalvoid inorder(node *node){ if (node) { inorder(node -> left); cout<< node -> data << \" \"; inorder(node -> right); }} // Driver codeint main(){ node *root = NULL; /* LLRB tree made after all insertions are made. 1. Nodes which have double INCOMING edge means that they are RED in color. 2. Nodes which have single INCOMING edge means that they are BLACK in color. root | 40 // \\ 20 50 / \\ 10 30 // 25 */ root = insert(root, 10); // To make sure that root remains // black is color root -> color = false; root = insert(root, 20); root -> color = false; root = insert(root, 30); root -> color = false; root = insert(root, 40); root -> color = false; root = insert(root, 50); root -> color = false; root = insert(root, 25); root -> color = false; // Display the tree through inorder traversal. inorder(root); return 0;} // This code is contributed by rutvik_56", "e": 7969, "s": 3847, "text": null }, { "code": "// C program to implement insert operation// in Red Black Tree.#include <stdio.h>#include <stdlib.h>#include <stdbool.h> typedef struct node{ struct node *left, *right; int data; // red ==> true, black ==> false bool color;} node; // utility function to create a node.node* createNode(int data, bool color){ node *myNode = (node *) malloc(sizeof(node)); myNode -> left = myNode -> right = NULL; myNode -> data = data; // New Node which is created is // always red in color. myNode -> color = true; return myNode;} // utility function to rotate node anticlockwise.node* rotateLeft(node* myNode){ printf(\"left rotation!!\\n\"); node *child = myNode -> right; node *childLeft = child -> left; child -> left = myNode; myNode -> right = childLeft; return child;} // utility function to rotate node clockwise.node* rotateRight(node* myNode){ printf(\"right rotation\\n\"); node *child = myNode -> left; node *childRight = child -> right; child -> right = myNode; myNode -> left = childRight; return child;} // utility function to check whether// node is red in color or not.int isRed(node *myNode){ if (myNode == NULL) return 0; return (myNode -> color == true);} // utility function to swap color of two// nodes.void swapColors(node *node1, node *node2){ bool temp = node1 -> color; node1 -> color = node2 -> color; node2 -> color = temp;} // insertion into Left Leaning Red Black Tree.node* insert(node* myNode, int data){ // Normal insertion code for any Binary // Search tree. if (myNode == NULL) return createNode(data, false); if (data < myNode -> data) myNode -> left = insert(myNode -> left, data); else if (data > myNode -> data) myNode -> right = insert(myNode -> right, data); else return myNode; // case 1. // when right child is Red but left child is // Black or doesn't exist. if (isRed(myNode -> right) && !isRed(myNode -> left)) { // left rotate the node to make it into // valid structure. myNode = rotateLeft(myNode); // swap the colors as the child node // should always be red swapColors(myNode, myNode -> left); } // case 2 // when left child as well as left grand child in Red if (isRed(myNode -> left) && isRed(myNode -> left -> left)) { // right rotate the current node to make // it into a valid structure. myNode = rotateRight(myNode); swapColors(myNode, myNode -> right); } // case 3 // when both left and right child are Red in color. if (isRed(myNode -> left) && isRed(myNode -> right)) { // invert the color of node as well // it's left and right child. myNode -> color = !myNode -> color; // change the color to black. myNode -> left -> color = false; myNode -> right -> color = false; } return myNode;} // Inorder traversalvoid inorder(node *node){ if (node) { inorder(node -> left); printf(\"%d \", node -> data); inorder(node -> right); }} // Driver functionint main(){ node *root = NULL; /* LLRB tree made after all insertions are made. 1. Nodes which have double INCOMING edge means that they are RED in color. 2. Nodes which have single INCOMING edge means that they are BLACK in color. root | 40 // \\ 20 50 / \\ 10 30 // 25 */ root = insert(root, 10); // to make sure that root remains // black is color root -> color = false; root = insert(root, 20); root -> color = false; root = insert(root, 30); root -> color = false; root = insert(root, 40); root -> color = false; root = insert(root, 50); root -> color = false; root = insert(root, 25); root -> color = false; // display the tree through inorder traversal. inorder(root); return 0;}", "e": 12007, "s": 7969, "text": null }, { "code": "// Java program to implement insert operation// in Red Black Tree. class node{ node left, right; int data; // red ==> true, black ==> false boolean color; node(int data) { this.data = data; left = null; right = null; // New Node which is created is // always red in color. color = true; }} public class LLRBTREE { private static node root = null; // utility function to rotate node anticlockwise. node rotateLeft(node myNode) { System.out.printf(\"left rotation!!\\n\"); node child = myNode.right; node childLeft = child.left; child.left = myNode; myNode.right = childLeft; return child; } // utility function to rotate node clockwise. node rotateRight(node myNode) { System.out.printf(\"right rotation\\n\"); node child = myNode.left; node childRight = child.right; child.right = myNode; myNode.left = childRight; return child; } // utility function to check whether // node is red in color or not. boolean isRed(node myNode) { if (myNode == null) return false; return (myNode.color == true); } // utility function to swap color of two // nodes. void swapColors(node node1, node node2) { boolean temp = node1.color; node1.color = node2.color; node2.color = temp; } // insertion into Left Leaning Red Black Tree. node insert(node myNode, int data) { // Normal insertion code for any Binary // Search tree. if (myNode == null) return new node(data); if (data < myNode.data) myNode.left = insert(myNode.left, data); else if (data > myNode.data) myNode.right = insert(myNode.right, data); else return myNode; // case 1. // when right child is Red but left child is // Black or doesn't exist. if (isRed(myNode.right) && !isRed(myNode.left)) { // left rotate the node to make it into // valid structure. myNode = rotateLeft(myNode); // swap the colors as the child node // should always be red swapColors(myNode, myNode.left); } // case 2 // when left child as well as left grand child in Red if (isRed(myNode.left) && isRed(myNode.left.left)) { // right rotate the current node to make // it into a valid structure. myNode = rotateRight(myNode); swapColors(myNode, myNode.right); } // case 3 // when both left and right child are Red in color. if (isRed(myNode.left) && isRed(myNode.right)) { // invert the color of node as well // it's left and right child. myNode.color = !myNode.color; // change the color to black. myNode.left.color = false; myNode.right.color = false; } return myNode; } // Inorder traversal void inorder(node node) { if (node != null) { inorder(node.left); System.out.print(node.data + \" \"); inorder(node.right); } } public static void main(String[] args) { /* LLRB tree made after all insertions are made. 1. Nodes which have double INCOMING edge means that they are RED in color. 2. Nodes which have single INCOMING edge means that they are BLACK in color. root | 40 // \\ 20 50 / \\ 10 30 // 25 */ LLRBTREE node = new LLRBTREE(); root = node.insert(root, 10); // to make sure that root remains // black is color root.color = false; root = node.insert(root, 20); root.color = false; root = node.insert(root, 30); root.color = false; root = node.insert(root, 40); root.color = false; root = node.insert(root, 50); root.color = false; root = node.insert(root, 25); root.color = false; // display the tree through inorder traversal. node.inorder(root); } } // This code is contributed by ARSHPREET_SINGH", "e": 16280, "s": 12007, "text": null }, { "code": "// C# program to implement insert// operation in Red Black Tree.using System; class node{ public node left, right; public int data; // red ==> true, black ==> false public Boolean color; public node(int data) { this.data = data; left = null; right = null; // New Node which is created // is always red in color. color = true; }} public class LLRBTREE{ private static node root = null; // utility function to rotate// node anticlockwise.node rotateLeft(node myNode){ Console.Write(\"left rotation!!\\n\"); node child = myNode.right; node childLeft = child.left; child.left = myNode; myNode.right = childLeft; return child;} // utility function to rotate// node clockwise.node rotateRight(node myNode){ Console.Write(\"right rotation\\n\"); node child = myNode.left; node childRight = child.right; child.right = myNode; myNode.left = childRight; return child;} // utility function to check whether// node is red in color or not.Boolean isRed(node myNode){ if (myNode == null) return false; return (myNode.color == true);} // utility function to swap// color of two nodes.void swapColors(node node1, node node2){ Boolean temp = node1.color; node1.color = node2.color; node2.color = temp;} // insertion into Left// Leaning Red Black Tree.node insert(node myNode, int data){ // Normal insertion code for // any Binary Search tree. if (myNode == null) return new node(data); if (data < myNode.data) myNode.left = insert(myNode.left, data); else if (data > myNode.data) myNode.right = insert(myNode.right, data); else return myNode; // case 1. // when right child is Red // but left child is // Black or doesn't exist. if (isRed(myNode.right) && !isRed(myNode.left)) { // left rotate the node to make // it into valid structure. myNode = rotateLeft(myNode); // swap the colors as the child // node should always be red swapColors(myNode, myNode.left); } // case 2 // when left child as well as // left grand child in Red if (isRed(myNode.left) && isRed(myNode.left.left)) { // right rotate the current node // to make it into a valid structure. myNode = rotateRight(myNode); swapColors(myNode, myNode.right); } // case 3 // when both left and right // child are Red in color. if (isRed(myNode.left) && isRed(myNode.right)) { // invert the color of node as well // it's left and right child. myNode.color = !myNode.color; // change the color to black. myNode.left.color = false; myNode.right.color = false; } return myNode;} // Inorder traversalvoid inorder(node node){ if (node != null) { inorder(node.left); Console.Write(node.data + \" \"); inorder(node.right); }} // Driver Codestatic public void Main(String []args){/* LLRB tree made after all insertions are made. 1. Nodes which have double INCOMING edge means that they are RED in color.2. Nodes which have single INCOMING edge means that they are BLACK in color. root | 40 // \\ 20 50 / \\ 10 30 // 25*/ LLRBTREE node = new LLRBTREE(); root = node.insert(root, 10); // to make sure that root // remains black is colorroot.color = false; root = node.insert(root, 20);root.color = false; root = node.insert(root, 30);root.color = false; root = node.insert(root, 40);root.color = false; root = node.insert(root, 50);root.color = false; root = node.insert(root, 25);root.color = false; // display the tree through// inorder traversal.node.inorder(root);}} // This code is contributed// by Arnab Kundu", "e": 20162, "s": 16280, "text": null }, { "code": "<script>// Javascript program to implement insert operation// in Red Black Tree. class node{ constructor(data) { this.data = data; this.left = null; this.right = null; // New Node which is created is // always red in color. this.color = true; }} let root = null; // utility function to rotate node anticlockwise.function rotateLeft(myNode){ document.write(\"left rotation!!<br>\"); let child = myNode.right; let childLeft = child.left; child.left = myNode; myNode.right = childLeft; return child;} // utility function to rotate node clockwise.function rotateRight(myNode){ document.write(\"right rotation<br>\"); let child = myNode.left; let childRight = child.right; child.right = myNode; myNode.left = childRight; return child;} // utility function to check whether // node is red in color or not.function isRed(myNode){ if (myNode == null) return false; return (myNode.color == true);} // utility function to swap color of two // nodes.function swapColors(node1,node2){ let temp = node1.color; node1.color = node2.color; node2.color = temp;} // insertion into Left Leaning Red Black Tree.function insert(myNode,data){ // Normal insertion code for any Binary // Search tree. if (myNode == null) return new node(data); if (data < myNode.data) myNode.left = insert(myNode.left, data); else if (data > myNode.data) myNode.right = insert(myNode.right, data); else return myNode; // case 1. // when right child is Red but left child is // Black or doesn't exist. if (isRed(myNode.right) && !isRed(myNode.left)) { // left rotate the node to make it into // valid structure. myNode = rotateLeft(myNode); // swap the colors as the child node // should always be red swapColors(myNode, myNode.left); } // case 2 // when left child as well as left grand child in Red if (isRed(myNode.left) && isRed(myNode.left.left)) { // right rotate the current node to make // it into a valid structure. myNode = rotateRight(myNode); swapColors(myNode, myNode.right); } // case 3 // when both left and right child are Red in color. if (isRed(myNode.left) && isRed(myNode.right)) { // invert the color of node as well // it's left and right child. myNode.color = !myNode.color; // change the color to black. myNode.left.color = false; myNode.right.color = false; } return myNode;} // Inorder traversalfunction inorder(node){ if (node != null) { inorder(node.left); document.write(node.data + \" \"); inorder(node.right); }} /* LLRB tree made after all insertions are made. 1. Nodes which have double INCOMING edge means that they are RED in color. 2. Nodes which have single INCOMING edge means that they are BLACK in color. root | 40 // \\ 20 50 / \\ 10 30 // 25 */ root = insert(root, 10);// to make sure that root remains// black is colorroot.color = false; root = insert(root, 20);root.color = false; root = insert(root, 30);root.color = false; root = insert(root, 40);root.color = false; root = insert(root, 50);root.color = false; root = insert(root, 25);root.color = false; // display the tree through inorder traversal.inorder(root); // This code is contributed by avanitrachhadiya2155</script>", "e": 23957, "s": 20162, "text": null }, { "code": null, "e": 23966, "s": 23957, "text": "Output: " }, { "code": null, "e": 24033, "s": 23966, "text": "left rotation!!\nleft rotation!!\nleft rotation!!\n10 20 25 30 40 50 " }, { "code": null, "e": 24523, "s": 24033, "text": "Time Complexity: O(log n)References Left Leaning Red Black Trees This article is contributed by Arshpreet Soodan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 24534, "s": 24523, "text": "andrew1234" }, { "code": null, "e": 24547, "s": 24534, "text": "Akanksha_Rai" }, { "code": null, "e": 24557, "s": 24547, "text": "rutvik_56" }, { "code": null, "e": 24578, "s": 24557, "text": "avanitrachhadiya2155" }, { "code": null, "e": 24593, "s": 24578, "text": "sagartomar9927" }, { "code": null, "e": 24610, "s": 24593, "text": "rishabhmathur612" }, { "code": null, "e": 24625, "s": 24610, "text": "Red Black Tree" }, { "code": null, "e": 24644, "s": 24625, "text": "Self-Balancing-BST" }, { "code": null, "e": 24670, "s": 24644, "text": "Advanced Computer Subject" }, { "code": null, "e": 24689, "s": 24670, "text": "Binary Search Tree" }, { "code": null, "e": 24708, "s": 24689, "text": "Binary Search Tree" } ]
foreach() loop vs Stream foreach() vs Parallel Stream foreach()
29 May, 2021 Lambda operator is not used: foreach loop in Java doesn’t use any lambda operations and thus operations can be applied on any value outside the list that we are using for iteration in the foreach loop. The foreach loop is concerned over iterating the collection or array by storing each element of the list on a local variable and doing any functionality that we want. Java public class GFG { public static void main(String[] args) { String[] arr = { "1", "2", "3" }; int count = 0; String[] arr1 = { "Geeks", "For", "Geeks" }; for (String str : arr) { System.out.print(arr1[count++]); } }} GeeksForGeeks Here operations on count are possible even being a variable outside the loop because it is in the scope of the foreach loop. It can be used for all collections and arrays: It can be used to iterate all collections and arrays in Java. Java public class GFG { public static void main(String[] args) throws Exception { String[] arr = { "1", "2", "3" }; int count = 0; String[] arr1 = { "Geeks", "For", "Geeks" }; for (String str : arr) { System.out.print(arr1[count++]); } }} GeeksForGeeks The return statements work within the loop: The function can return the value at any point of time within the loop. For example, if we want to print only the first 2 values of any collection or array and then we want to return any value, it can be done in foreach loop in Java. The code below is for printing the 2nd element of an array. Java public class GFG { public static String frechlop(String[] geek) { int count = 0; for (String var : geek) { if (count == 1) return var; count++; } return ""; } public static void main(String[] args) throws Exception { String[] arr1 = { "Geeks", "For", "Geeks" }; String secelt = frechlop(arr1); System.out.println(secelt); }} For Lambda operator is used: In stream().forEach(), lambdas are used and thus operations on variables outside the loop are not allowed. Only the operations on concerned collections are possible. In this, we can perform operations on Collections by single line code that makes it easy and simple to code. Java import Java.util.*;public class GFG { public static void main(String[] args) throws Exception { List<String> arr1 = new ArrayList<String>(); int count = 0; arr1.add("Geeks"); arr1.add("For"); arr1.add("Geeks"); arr1.stream().forEach(s -> { // this will cause an error count++; // print all elements System.out.print(s); }); }} Note: The operation “count++” will cause an error because lambda operations do not allow any external variable operation within themselves. Only used to iterate collections: The stream().forEach() is only used for accessing the collections like set and list. It can also be used for accessing arrays. Java import java.util.*;public class GFG { public static void main(String[] args) throws Exception { String[] arr1 = { "Geeks", "for", "Geeks" }; // The next line will throw error // as there is no such method as stream() arr1.stream().forEach( s -> { System.out.print(s); }); }} Return statements don’t work within this loop, but the function calls are very easy to call: The return statement within the loop doesn’t work. The same functionality of getting the 2nd element cannot be done in the same forEach() method. Java import Java.util.*; public class GFG { static String second(List<String> list) { list.stream().forEach( s -> { // The next line will throw error // as no return allowed // if(s=="For")return s; }); return "null"; } public static void main(String[] args) throws Exception { List<String> arr1 = new ArrayList<String>(); arr1.add("Geeks"); arr1.add("For"); arr1.add("Geeks"); String f = second(arr1); System.out.println(f); }} null Works on multithreading concept: The only difference between stream().forEach() and parallel foreach() is the multithreading feature given in the parallel forEach(). This is way faster that foreach() and stream.forEach(). Like stream().forEach() it also uses lambda symbol to perform functions. The example providing its multithreading nature which is given as follows.It’s clearly implied that the output will never be in the same order for printing the strings due to parallelStream’s multithreaded nature. the ForGeeksGeeks aratan koushalgoyal67 varshagumber28 Picked Difference Between Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Differences between JDK, JRE and JVM Differences between IPv4 and IPv6 Difference between MANET and VANET Object Oriented Programming (OOPs) Concept in Java Reverse a string in Java Arrays.sort() in Java with examples How to iterate any Map in Java Interfaces in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n29 May, 2021" }, { "code": null, "e": 423, "s": 54, "text": "Lambda operator is not used: foreach loop in Java doesn’t use any lambda operations and thus operations can be applied on any value outside the list that we are using for iteration in the foreach loop. The foreach loop is concerned over iterating the collection or array by storing each element of the list on a local variable and doing any functionality that we want." }, { "code": null, "e": 428, "s": 423, "text": "Java" }, { "code": "public class GFG { public static void main(String[] args) { String[] arr = { \"1\", \"2\", \"3\" }; int count = 0; String[] arr1 = { \"Geeks\", \"For\", \"Geeks\" }; for (String str : arr) { System.out.print(arr1[count++]); } }}", "e": 703, "s": 428, "text": null }, { "code": null, "e": 717, "s": 703, "text": "GeeksForGeeks" }, { "code": null, "e": 843, "s": 717, "text": "Here operations on count are possible even being a variable outside the loop because it is in the scope of the foreach loop. " }, { "code": null, "e": 952, "s": 843, "text": "It can be used for all collections and arrays: It can be used to iterate all collections and arrays in Java." }, { "code": null, "e": 957, "s": 952, "text": "Java" }, { "code": "public class GFG { public static void main(String[] args) throws Exception { String[] arr = { \"1\", \"2\", \"3\" }; int count = 0; String[] arr1 = { \"Geeks\", \"For\", \"Geeks\" }; for (String str : arr) { System.out.print(arr1[count++]); } }}", "e": 1250, "s": 957, "text": null }, { "code": null, "e": 1264, "s": 1250, "text": "GeeksForGeeks" }, { "code": null, "e": 1602, "s": 1264, "text": "The return statements work within the loop: The function can return the value at any point of time within the loop. For example, if we want to print only the first 2 values of any collection or array and then we want to return any value, it can be done in foreach loop in Java. The code below is for printing the 2nd element of an array." }, { "code": null, "e": 1607, "s": 1602, "text": "Java" }, { "code": "public class GFG { public static String frechlop(String[] geek) { int count = 0; for (String var : geek) { if (count == 1) return var; count++; } return \"\"; } public static void main(String[] args) throws Exception { String[] arr1 = { \"Geeks\", \"For\", \"Geeks\" }; String secelt = frechlop(arr1); System.out.println(secelt); }}", "e": 2046, "s": 1607, "text": null }, { "code": null, "e": 2050, "s": 2046, "text": "For" }, { "code": null, "e": 2350, "s": 2050, "text": "Lambda operator is used: In stream().forEach(), lambdas are used and thus operations on variables outside the loop are not allowed. Only the operations on concerned collections are possible. In this, we can perform operations on Collections by single line code that makes it easy and simple to code." }, { "code": null, "e": 2355, "s": 2350, "text": "Java" }, { "code": "import Java.util.*;public class GFG { public static void main(String[] args) throws Exception { List<String> arr1 = new ArrayList<String>(); int count = 0; arr1.add(\"Geeks\"); arr1.add(\"For\"); arr1.add(\"Geeks\"); arr1.stream().forEach(s -> { // this will cause an error count++; // print all elements System.out.print(s); }); }}", "e": 2787, "s": 2355, "text": null }, { "code": null, "e": 2929, "s": 2787, "text": "Note: The operation “count++” will cause an error because lambda operations do not allow any external variable operation within themselves. " }, { "code": null, "e": 3090, "s": 2929, "text": "Only used to iterate collections: The stream().forEach() is only used for accessing the collections like set and list. It can also be used for accessing arrays." }, { "code": null, "e": 3095, "s": 3090, "text": "Java" }, { "code": "import java.util.*;public class GFG { public static void main(String[] args) throws Exception { String[] arr1 = { \"Geeks\", \"for\", \"Geeks\" }; // The next line will throw error // as there is no such method as stream() arr1.stream().forEach( s -> { System.out.print(s); }); }}", "e": 3421, "s": 3095, "text": null }, { "code": null, "e": 3660, "s": 3421, "text": "Return statements don’t work within this loop, but the function calls are very easy to call: The return statement within the loop doesn’t work. The same functionality of getting the 2nd element cannot be done in the same forEach() method." }, { "code": null, "e": 3665, "s": 3660, "text": "Java" }, { "code": "import Java.util.*; public class GFG { static String second(List<String> list) { list.stream().forEach( s -> { // The next line will throw error // as no return allowed // if(s==\"For\")return s; }); return \"null\"; } public static void main(String[] args) throws Exception { List<String> arr1 = new ArrayList<String>(); arr1.add(\"Geeks\"); arr1.add(\"For\"); arr1.add(\"Geeks\"); String f = second(arr1); System.out.println(f); }}", "e": 4246, "s": 3665, "text": null }, { "code": null, "e": 4251, "s": 4246, "text": "null" }, { "code": null, "e": 4760, "s": 4251, "text": "Works on multithreading concept: The only difference between stream().forEach() and parallel foreach() is the multithreading feature given in the parallel forEach(). This is way faster that foreach() and stream.forEach(). Like stream().forEach() it also uses lambda symbol to perform functions. The example providing its multithreading nature which is given as follows.It’s clearly implied that the output will never be in the same order for printing the strings due to parallelStream’s multithreaded nature." }, { "code": null, "e": 4765, "s": 4760, "text": "the " }, { "code": null, "e": 4779, "s": 4765, "text": "ForGeeksGeeks" }, { "code": null, "e": 4788, "s": 4781, "text": "aratan" }, { "code": null, "e": 4803, "s": 4788, "text": "koushalgoyal67" }, { "code": null, "e": 4818, "s": 4803, "text": "varshagumber28" }, { "code": null, "e": 4825, "s": 4818, "text": "Picked" }, { "code": null, "e": 4844, "s": 4825, "text": "Difference Between" }, { "code": null, "e": 4849, "s": 4844, "text": "Java" }, { "code": null, "e": 4854, "s": 4849, "text": "Java" }, { "code": null, "e": 4952, "s": 4854, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5013, "s": 4952, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5081, "s": 5013, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 5118, "s": 5081, "text": "Differences between JDK, JRE and JVM" }, { "code": null, "e": 5152, "s": 5118, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 5187, "s": 5152, "text": "Difference between MANET and VANET" }, { "code": null, "e": 5238, "s": 5187, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 5263, "s": 5238, "text": "Reverse a string in Java" }, { "code": null, "e": 5299, "s": 5263, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 5330, "s": 5299, "text": "How to iterate any Map in Java" } ]
GATE | GATE CS 2011 | Question 65
28 Jun, 2021 Let the page fault service time be 10ms in a computer with average memory access time being 20ns. If one page fault is generated for every 10^6 memory accesses, what is the effective access time for the memory?(A) 21ns(B) 30ns(C) 23ns(D) 35nsAnswer: (B)Explanation: Let P be the page fault rate Effective Memory Access Time = p * (page fault service time) + (1 - p) * (Memory access time) = ( 1/(10^6) )* 10 * (10^6) ns + (1 - 1/(10^6)) * 20 ns = 30 ns (approx) Quiz of this Question GATE-CS-2011 GATE-GATE CS 2011 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Jun, 2021" }, { "code": null, "e": 318, "s": 52, "text": "Let the page fault service time be 10ms in a computer with average memory access time being 20ns. If one page fault is generated for every 10^6 memory accesses, what is the effective access time for the memory?(A) 21ns(B) 30ns(C) 23ns(D) 35nsAnswer: (B)Explanation:" }, { "code": null, "e": 638, "s": 318, "text": "Let P be the page fault rate\nEffective Memory Access Time = p * (page fault service time) + \n (1 - p) * (Memory access time)\n = ( 1/(10^6) )* 10 * (10^6) ns +\n (1 - 1/(10^6)) * 20 ns\n = 30 ns (approx) " }, { "code": null, "e": 660, "s": 638, "text": "Quiz of this Question" }, { "code": null, "e": 673, "s": 660, "text": "GATE-CS-2011" }, { "code": null, "e": 691, "s": 673, "text": "GATE-GATE CS 2011" }, { "code": null, "e": 696, "s": 691, "text": "GATE" } ]
How to set the matplotlib figure default size in ipython notebook?
To set the matplotlib figure default size in iPython, use the following steps − To check the default figure size, use plt.rcParams["figure.figsize"] over the ipython shell. To check the default figure size, use plt.rcParams["figure.figsize"] over the ipython shell. Now to set the figure size, override the plt.rcParams["figure.figsize"] variable with a tuple i.e., (20, 10). Now to set the figure size, override the plt.rcParams["figure.figsize"] variable with a tuple i.e., (20, 10). After overriding the plt.rcParams["figure.figsize"] variable, you can use it to get changed figure size. After overriding the plt.rcParams["figure.figsize"] variable, you can use it to get changed figure size. import matplotlib.pyplot as plt print("Before, figure default size is: ", plt.rcParams["figure.figsize"]) plt.rcParams["figure.figsize"] = (20, 10) print("After, figure default size is: ", plt.rcParams["figure.figsize"]) Before, figure default size is: [6.4, 4.8] After, figure default size is: [20.0, 10.0]
[ { "code": null, "e": 1142, "s": 1062, "text": "To set the matplotlib figure default size in iPython, use the following steps −" }, { "code": null, "e": 1235, "s": 1142, "text": "To check the default figure size, use plt.rcParams[\"figure.figsize\"] over the ipython\nshell." }, { "code": null, "e": 1328, "s": 1235, "text": "To check the default figure size, use plt.rcParams[\"figure.figsize\"] over the ipython\nshell." }, { "code": null, "e": 1438, "s": 1328, "text": "Now to set the figure size, override the plt.rcParams[\"figure.figsize\"] variable with a tuple i.e., (20, 10)." }, { "code": null, "e": 1548, "s": 1438, "text": "Now to set the figure size, override the plt.rcParams[\"figure.figsize\"] variable with a tuple i.e., (20, 10)." }, { "code": null, "e": 1653, "s": 1548, "text": "After overriding the plt.rcParams[\"figure.figsize\"] variable, you can use it to get changed figure size." }, { "code": null, "e": 1758, "s": 1653, "text": "After overriding the plt.rcParams[\"figure.figsize\"] variable, you can use it to get changed figure size." }, { "code": null, "e": 1980, "s": 1758, "text": "import matplotlib.pyplot as plt\n\nprint(\"Before, figure default size is: \", plt.rcParams[\"figure.figsize\"])\nplt.rcParams[\"figure.figsize\"] = (20, 10)\nprint(\"After, figure default size is: \", plt.rcParams[\"figure.figsize\"])" }, { "code": null, "e": 2067, "s": 1980, "text": "Before, figure default size is: [6.4, 4.8]\nAfter, figure default size is: [20.0, 10.0]" } ]
Python regex to find sequences of one upper case letter followed by lower case letters
When it is required to find sequences of an upper case letter followed by lower case using regular expression, a method named ‘match_string’ is defined that uses the ‘search’ method to match a regular expression. Outside the method, the string is defined, and the method is called on it by passing the string. Below is a demonstration of the same import re def match_string(my_string): pattern = '[A-Z]+[a-z]+$' if re.search(pattern, my_string): return('The string meets the required condition \n') else: return('The string doesnot meet the required condition \n') print("The string is :") string_1 = "Python" print(string_1) print(match_string(string_1)) print("The string is :") string_2 = "python" print(string_2) print(match_string(string_2)) print("The string is :") string_3 = "PythonInterpreter" print(string_3) print(match_string(string_3)) The string is : Python The string meets the required condition The string is : python The string doesn’t meet the required condition The string is : PythonInterpreter The string meets the required condition The required packages are imported. The required packages are imported. A method named ‘match_string’ is defined, that takes a string as a parameter. A method named ‘match_string’ is defined, that takes a string as a parameter. It uses the ‘search’ method to check if the specific regular expression was found in the string or not. It uses the ‘search’ method to check if the specific regular expression was found in the string or not. Outside the method, a string is defined, and is displayed on the console. Outside the method, a string is defined, and is displayed on the console. The method is called by passing this string as a parameter. The method is called by passing this string as a parameter. The output is displayed on the console. The output is displayed on the console.
[ { "code": null, "e": 1372, "s": 1062, "text": "When it is required to find sequences of an upper case letter followed by lower case using regular expression, a method named ‘match_string’ is defined that uses the ‘search’ method to match a regular expression. Outside the method, the string is defined, and the method is called on it by passing the string." }, { "code": null, "e": 1409, "s": 1372, "text": "Below is a demonstration of the same" }, { "code": null, "e": 1938, "s": 1409, "text": "import re\n\ndef match_string(my_string):\n\n pattern = '[A-Z]+[a-z]+$'\n\n if re.search(pattern, my_string):\n return('The string meets the required condition \\n')\n else:\n return('The string doesnot meet the required condition \\n')\n\nprint(\"The string is :\")\nstring_1 = \"Python\"\nprint(string_1)\nprint(match_string(string_1))\n\nprint(\"The string is :\")\nstring_2 = \"python\"\nprint(string_2)\nprint(match_string(string_2))\n\nprint(\"The string is :\")\nstring_3 = \"PythonInterpreter\"\nprint(string_3)\nprint(match_string(string_3))" }, { "code": null, "e": 2145, "s": 1938, "text": "The string is :\nPython\nThe string meets the required condition\nThe string is :\npython\nThe string doesn’t meet the required condition\nThe string is :\nPythonInterpreter\nThe string meets the required condition" }, { "code": null, "e": 2181, "s": 2145, "text": "The required packages are imported." }, { "code": null, "e": 2217, "s": 2181, "text": "The required packages are imported." }, { "code": null, "e": 2295, "s": 2217, "text": "A method named ‘match_string’ is defined, that takes a string as a parameter." }, { "code": null, "e": 2373, "s": 2295, "text": "A method named ‘match_string’ is defined, that takes a string as a parameter." }, { "code": null, "e": 2477, "s": 2373, "text": "It uses the ‘search’ method to check if the specific regular expression was found in the string or not." }, { "code": null, "e": 2581, "s": 2477, "text": "It uses the ‘search’ method to check if the specific regular expression was found in the string or not." }, { "code": null, "e": 2655, "s": 2581, "text": "Outside the method, a string is defined, and is displayed on the console." }, { "code": null, "e": 2729, "s": 2655, "text": "Outside the method, a string is defined, and is displayed on the console." }, { "code": null, "e": 2789, "s": 2729, "text": "The method is called by passing this string as a parameter." }, { "code": null, "e": 2849, "s": 2789, "text": "The method is called by passing this string as a parameter." }, { "code": null, "e": 2889, "s": 2849, "text": "The output is displayed on the console." }, { "code": null, "e": 2929, "s": 2889, "text": "The output is displayed on the console." } ]
fabs() in C++
09 Apr, 2018 The fabs() function returns the absolute value of the argument.Mathematically |a|. If a is value given in the argument. Syntax: double fabs(double a); float fabs(float a); int fabs(int a); Parameter: The fabs() function takes a single argument, a whose absolute value has to be returned. Return: The fabs() function returns the absolute value of the argument. Error: It is mandatory to give both the arguments otherwise it will give errorno matching function for call to ‘fabs()’ like this. # CODE 1 // CPP code to illustrate// fabs() function#include <cmath>#include <iostream> using namespace std; int main(){ int a = -10, answer; answer = fabs(a); cout << "fabs of " << a << " is " << answer << endl; return 0;} OUTPUT : fabs of -10 is 10 # CODE 2 // CPP code to illustrate// fabs() function#include <cmath>#include <iostream> using namespace std; int main(){ long int a = -35; double answer; answer = fabs(a); cout << "fabs of " << a << " is " << answer << endl; return 0;} OUTPUT : fabs of -35 is 35 CPP-Library cpp-math C++ 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++ std::string class in C++ Friend class and function in C++ Pair in C++ Standard Template Library (STL) Queue in C++ Standard Template Library (STL) Unordered Sets in C++ Standard Template Library List in C++ Standard Template Library (STL) std::find in C++ Inline Functions in C++
[ { "code": null, "e": 54, "s": 26, "text": "\n09 Apr, 2018" }, { "code": null, "e": 174, "s": 54, "text": "The fabs() function returns the absolute value of the argument.Mathematically |a|. If a is value given in the argument." }, { "code": null, "e": 182, "s": 174, "text": "Syntax:" }, { "code": null, "e": 244, "s": 182, "text": "double fabs(double a);\nfloat fabs(float a);\nint fabs(int a);\n" }, { "code": null, "e": 255, "s": 244, "text": "Parameter:" }, { "code": null, "e": 343, "s": 255, "text": "The fabs() function takes a single argument, a whose absolute value has to be returned." }, { "code": null, "e": 351, "s": 343, "text": "Return:" }, { "code": null, "e": 415, "s": 351, "text": "The fabs() function returns the absolute value of the argument." }, { "code": null, "e": 422, "s": 415, "text": "Error:" }, { "code": null, "e": 546, "s": 422, "text": "It is mandatory to give both the arguments otherwise it will give errorno matching function for call to ‘fabs()’ like this." }, { "code": null, "e": 555, "s": 546, "text": "# CODE 1" }, { "code": "// CPP code to illustrate// fabs() function#include <cmath>#include <iostream> using namespace std; int main(){ int a = -10, answer; answer = fabs(a); cout << \"fabs of \" << a << \" is \" << answer << endl; return 0;}", "e": 797, "s": 555, "text": null }, { "code": null, "e": 806, "s": 797, "text": "OUTPUT :" }, { "code": null, "e": 825, "s": 806, "text": "fabs of -10 is 10\n" }, { "code": null, "e": 834, "s": 825, "text": "# CODE 2" }, { "code": "// CPP code to illustrate// fabs() function#include <cmath>#include <iostream> using namespace std; int main(){ long int a = -35; double answer; answer = fabs(a); cout << \"fabs of \" << a << \" is \" << answer << endl; return 0;}", "e": 1091, "s": 834, "text": null }, { "code": null, "e": 1100, "s": 1091, "text": "OUTPUT :" }, { "code": null, "e": 1119, "s": 1100, "text": "fabs of -35 is 35\n" }, { "code": null, "e": 1131, "s": 1119, "text": "CPP-Library" }, { "code": null, "e": 1140, "s": 1131, "text": "cpp-math" }, { "code": null, "e": 1144, "s": 1140, "text": "C++" }, { "code": null, "e": 1148, "s": 1144, "text": "CPP" }, { "code": null, "e": 1246, "s": 1148, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1270, "s": 1246, "text": "Sorting a vector in C++" }, { "code": null, "e": 1290, "s": 1270, "text": "Polymorphism in C++" }, { "code": null, "e": 1315, "s": 1290, "text": "std::string class in C++" }, { "code": null, "e": 1348, "s": 1315, "text": "Friend class and function in C++" }, { "code": null, "e": 1392, "s": 1348, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 1437, "s": 1392, "text": "Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 1485, "s": 1437, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 1529, "s": 1485, "text": "List in C++ Standard Template Library (STL)" }, { "code": null, "e": 1546, "s": 1529, "text": "std::find in C++" } ]
Variants of Binary Search
05 Jan, 2021 Binary search is very easy right? Well, binary search can become complex when element duplication occurs in the sorted list of values. It’s not always the “contains or not” we search using Binary Search, but there are 5 variants such as below:1) Contains (True or False) 2) Index of first occurrence of a key 3) Index of last occurrence of a key 4) Index of least element greater than key 5) Index of greatest element less than key Each of these searches, while the base logic remains same, have a minor variation in implementation and competitive coders should be aware of them. You might have seen other approaches such as this for finding first and last occurrence, where you compare adjacent element also for checking of first/last element is reached. From a complexity perspective, it may look like an O(log n) algorithm, but it doesn’t work when the comparisons itself are expensive. A problem to prove this point is linked at the end of this post, feel free to try it out.Variant 1: Contains key (True or False) Input : 2 3 3 5 5 5 6 6 Function : Contains(4) Returns : False Function : Contains(5) Returns : True Variant 2: First occurrence of key (index of array). This is similar to C++ std::lower_bound(...) Input : 2 3 3 5 5 5 6 6 Function : first(3) Returns : 1 Function : first(5) Returns : 3 Function : first(4) Returns : -1 Variant 3: Last occurrence of key (index of array) Input : 2 3 3 5 5 5 6 6 Function : last(3) Returns : 2 Function : last(5) Returns : 5 Function : last(4) Returns : -1 Variant 4: index(first occurrence) of least integer greater than key. This is similar to C++ std::upper_bound(...) Input : 2 3 3 5 5 5 6 6 Function : leastGreater(2) Returns : 1 Function : leastGreater(5) Returns : 6 Variant 5: index(last occurrence) of greatest integer lesser than key Input : 2 3 3 5 5 5 6 6 Function : greatestLesser(2) Returns : -1 Function : greatestLesser(5) Returns : 2 As you will see below, if you observe the clear difference between the implementations you will see that the same logic is used to find different variants of binary search. C++ Java C# // C++ program to variants of Binary Search#include <bits/stdc++.h> using namespace std; int n = 8; // array sizeint a[] = { 2, 3, 3, 5, 5, 5, 6, 6 }; // Sorted array /* Find if key is in array * Returns: True if key belongs to array, * False if key doesn't belong to array */bool contains(int low, int high, int key){ bool ans = false; while (low <= high) { int mid = low + (high - low) / 2; int midVal = a[mid]; if (midVal < key) { // if mid is less than key, all elements // in range [low, mid] are also less // so we now search in [mid + 1, high] low = mid + 1; } else if (midVal > key) { // if mid is greater than key, all elements // in range [mid + 1, high] are also greater // so we now search in [low, mid - 1] high = mid - 1; } else if (midVal == key) { // comparison added just for the sake // of clarity if mid is equal to key, we // have found that key exists in array ans = true; break; } } return ans;} /* Find first occurrence index of key in array * Returns: an index in range [0, n-1] if key belongs * to array, -1 if key doesn't belong to array */int first(int low, int high, int key){ int ans = -1; while (low <= high) { int mid = low + (high - low + 1) / 2; int midVal = a[mid]; if (midVal < key) { // if mid is less than key, all elements // in range [low, mid] are also less // so we now search in [mid + 1, high] low = mid + 1; } else if (midVal > key) { // if mid is greater than key, all elements // in range [mid + 1, high] are also greater // so we now search in [low, mid - 1] high = mid - 1; } else if (midVal == key) { // if mid is equal to key, we note down // the last found index then we search // for more in left side of mid // so we now search in [low, mid - 1] ans = mid; high = mid - 1; } } return ans;} /* Find last occurrence index of key in array * Returns: an index in range [0, n-1] if key belongs to array, * -1 if key doesn't belong to array */int last(int low, int high, int key){ int ans = -1; while (low <= high) { int mid = low + (high - low + 1) / 2; int midVal = a[mid]; if (midVal < key) { // if mid is less than key, then all elements // in range [low, mid - 1] are also less // so we now search in [mid + 1, high] low = mid + 1; } else if (midVal > key) { // if mid is greater than key, then all // elements in range [mid + 1, high] are // also greater so we now search in // [low, mid - 1] high = mid - 1; } else if (midVal == key) { // if mid is equal to key, we note down // the last found index then we search // for more in right side of mid // so we now search in [mid + 1, high] ans = mid; low = mid + 1; } } return ans;} /* Find index of first occurrence of least element greater than key in array * Returns: an index in range [0, n-1] if key is not the greatest element in array, * -1 if key is the greatest element in array */int leastgreater(int low, int high, int key){ int ans = -1; while (low <= high) { int mid = low + (high - low + 1) / 2; int midVal = a[mid]; if (midVal < key) { // if mid is less than key, all elements // in range [low, mid - 1] are <= key // then we search in right side of mid // so we now search in [mid + 1, high] low = mid + 1; } else if (midVal > key) { // if mid is greater than key, all elements // in range [mid + 1, high] are >= key // we note down the last found index, then // we search in left side of mid // so we now search in [low, mid - 1] ans = mid; high = mid - 1; } else if (midVal == key) { // if mid is equal to key, all elements in // range [low, mid] are <= key // so we now search in [mid + 1, high] low = mid + 1; } } return ans;} /* Find index of last occurrence of greatest element less than key in array * Returns: an index in range [0, n-1] if key is not the least element in array, * -1 if key is the least element in array */int greatestlesser(int low, int high, int key){ int ans = -1; while (low <= high) { int mid = low + (high - low + 1) / 2; int midVal = a[mid]; if (midVal < key) { // if mid is less than key, all elements // in range [low, mid - 1] are < key // we note down the last found index, then // we search in right side of mid // so we now search in [mid + 1, high] ans = mid; low = mid + 1; } else if (midVal > key) { // if mid is greater than key, all elements // in range [mid + 1, high] are > key // then we search in left side of mid // so we now search in [low, mid - 1] high = mid - 1; } else if (midVal == key) { // if mid is equal to key, all elements // in range [mid + 1, high] are >= key // then we search in left side of mid // so we now search in [low, mid - 1] high = mid - 1; } } return ans;} int main(){ printf("Contains\n"); for (int i = 0; i < 10; i++) printf("%d %d\n", i, contains(0, n - 1, i)); printf("First occurrence of key\n"); for (int i = 0; i < 10; i++) printf("%d %d\n", i, first(0, n - 1, i)); printf("Last occurrence of key\n"); for (int i = 0; i < 10; i++) printf("%d %d\n", i, last(0, n - 1, i)); printf("Least integer greater than key\n"); for (int i = 0; i < 10; i++) printf("%d %d\n", i, leastgreater(0, n - 1, i)); printf("Greatest integer lesser than key\n"); for (int i = 0; i < 10; i++) printf("%d %d\n", i, greatestlesser(0, n - 1, i)); return 0;} // Java program to variants of Binary Searchimport java.util.*; class GFG{ // Array size static int n = 8; // Sorted arraystatic int a[] = { 2, 3, 3, 5, 5, 5, 6, 6 }; /* Find if key is in array * Returns: True if key belongs to array, * False if key doesn't belong to array */static int contains(int low, int high, int key){ int ans = 0; while (low <= high) { int mid = low + (high - low) / 2; int midVal = a[mid]; if (midVal < key) { // If mid is less than key, all elements // in range [low, mid] are also less // so we now search in [mid + 1, high] low = mid + 1; } else if (midVal > key) { // If mid is greater than key, all elements // in range [mid + 1, high] are also greater // so we now search in [low, mid - 1] high = mid - 1; } else if (midVal == key) { // Comparison added just for the sake // of clarity if mid is equal to key, we // have found that key exists in array ans = 1; break; } } return ans;} /* Find first occurrence index of key in array * Returns: an index in range [0, n-1] if key belongs * to array, -1 if key doesn't belong to array */static int first(int low, int high, int key){ int ans = -1; while (low <= high) { int mid = low + (high - low + 1) / 2; int midVal = a[mid]; if (midVal < key) { // If mid is less than key, all elements // in range [low, mid] are also less // so we now search in [mid + 1, high] low = mid + 1; } else if (midVal > key) { // If mid is greater than key, all elements // in range [mid + 1, high] are also greater // so we now search in [low, mid - 1] high = mid - 1; } else if (midVal == key) { // If mid is equal to key, we note down // the last found index then we search // for more in left side of mid // so we now search in [low, mid - 1] ans = mid; high = mid - 1; } } return ans;} /* Find last occurrence index of key in array * Returns: an index in range [0, n-1] if key belongs to array, -1 if key doesn't belong to array */static int last(int low, int high, int key){ int ans = -1; while (low <= high) { int mid = low + (high - low + 1) / 2; int midVal = a[mid]; if (midVal < key) { // If mid is less than key, then all elements // in range [low, mid - 1] are also less // so we now search in [mid + 1, high] low = mid + 1; } else if (midVal > key) { // If mid is greater than key, then all // elements in range [mid + 1, high] are // also greater so we now search in // [low, mid - 1] high = mid - 1; } else if (midVal == key) { // If mid is equal to key, we note down // the last found index then we search // for more in right side of mid // so we now search in [mid + 1, high] ans = mid; low = mid + 1; } } return ans;} /* Find index of first occurrence of least element greater than key in array * Returns: an index in range [0, n-1] if key is not the greatest element in array, -1 if key * is the greatest element in array */static int leastgreater(int low, int high, int key){ int ans = -1; while (low <= high) { int mid = low + (high - low + 1) / 2; int midVal = a[mid]; if (midVal < key) { // If mid is less than key, all elements // in range [low, mid - 1] are <= key // then we search in right side of mid // so we now search in [mid + 1, high] low = mid + 1; } else if (midVal > key) { // If mid is greater than key, all elements // in range [mid + 1, high] are >= key // we note down the last found index, then // we search in left side of mid // so we now search in [low, mid - 1] ans = mid; high = mid - 1; } else if (midVal == key) { // If mid is equal to key, all elements in // range [low, mid] are <= key // so we now search in [mid + 1, high] low = mid + 1; } } return ans;} /* Find index of last occurrence of greatest element less than key in array * Returns: an index in range [0, n-1] if key is not the least element in array, -1 if * key is the least element in array */static int greatestlesser(int low, int high, int key){ int ans = -1; while (low <= high) { int mid = low + (high - low + 1) / 2; int midVal = a[mid]; if (midVal < key) { // If mid is less than key, all elements // in range [low, mid - 1] are < key // we note down the last found index, then // we search in right side of mid // so we now search in [mid + 1, high] ans = mid; low = mid + 1; } else if (midVal > key) { // If mid is greater than key, all elements // in range [mid + 1, high] are > key // then we search in left side of mid // so we now search in [low, mid - 1] high = mid - 1; } else if (midVal == key) { // If mid is equal to key, all elements // in range [mid + 1, high] are >= key // then we search in left side of mid // so we now search in [low, mid - 1] high = mid - 1; } } return ans;} // Driver Codepublic static void main(String[] args){ System.out.println("Contains"); for(int i = 0; i < 10; i++) System.out.println(i + " " + contains(0, n - 1, i)); System.out.println("First occurrence of key"); for(int i = 0; i < 10; i++) System.out.println(i + " " + first(0, n - 1, i)); System.out.println("Last occurrence of key"); for(int i = 0; i < 10; i++) System.out.println(i + " " + last(0, n - 1, i)); System.out.println("Least integer greater than key"); for(int i = 0; i < 10; i++) System.out.println(i + " " + leastgreater(0, n - 1, i)); System.out.println("Greatest integer lesser than key"); for(int i = 0; i < 10; i++) System.out.println(i + " " + greatestlesser(0, n - 1, i));}} // This code is contributed by divyeshrabadiya07 // C# program to variants of Binary Searchusing System; class GFG{ // Array size static int n = 8; // Sorted arraystatic int[] a = { 2, 3, 3, 5, 5, 5, 6, 6 }; /* Find if key is in array * Returns: True if key belongs to array, * False if key doesn't belong to array */static int contains(int low, int high, int key){ int ans = 0; while (low <= high) { int mid = low + (high - low) / 2; int midVal = a[mid]; if (midVal < key) { // If mid is less than key, all elements // in range [low, mid] are also less // so we now search in [mid + 1, high] low = mid + 1; } else if (midVal > key) { // If mid is greater than key, all elements // in range [mid + 1, high] are also greater // so we now search in [low, mid - 1] high = mid - 1; } else if (midVal == key) { // Comparison added just for the sake // of clarity if mid is equal to key, we // have found that key exists in array ans = 1; break; } } return ans;} /* Find first occurrence index of key in array * Returns: an index in range [0, n-1] if key belongs * to array, -1 if key doesn't belong to array */static int first(int low, int high, int key){ int ans = -1; while (low <= high) { int mid = low + (high - low + 1) / 2; int midVal = a[mid]; if (midVal < key) { // If mid is less than key, all elements // in range [low, mid] are also less // so we now search in [mid + 1, high] low = mid + 1; } else if (midVal > key) { // If mid is greater than key, all elements // in range [mid + 1, high] are also greater // so we now search in [low, mid - 1] high = mid - 1; } else if (midVal == key) { // If mid is equal to key, we note down // the last found index then we search // for more in left side of mid // so we now search in [low, mid - 1] ans = mid; high = mid - 1; } } return ans;} /* Find last occurrence index of key in array * Returns: an index in range [0, n-1] if key belongs to array, -1 if key doesn't belong to array */static int last(int low, int high, int key){ int ans = -1; while (low <= high) { int mid = low + (high - low + 1) / 2; int midVal = a[mid]; if (midVal < key) { // If mid is less than key, then all elements // in range [low, mid - 1] are also less // so we now search in [mid + 1, high] low = mid + 1; } else if (midVal > key) { // If mid is greater than key, then all // elements in range [mid + 1, high] are // also greater so we now search in // [low, mid - 1] high = mid - 1; } else if (midVal == key) { // If mid is equal to key, we note down // the last found index then we search // for more in right side of mid // so we now search in [mid + 1, high] ans = mid; low = mid + 1; } } return ans;} /* Find index of first occurrence of least element greater than key in array * Returns: an index in range [0, n-1] if key is not the greatest element in array, * -1 if key is the greatest element in array */static int leastgreater(int low, int high, int key){ int ans = -1; while (low <= high) { int mid = low + (high - low + 1) / 2; int midVal = a[mid]; if (midVal < key) { // If mid is less than key, all elements // in range [low, mid - 1] are <= key // then we search in right side of mid // so we now search in [mid + 1, high] low = mid + 1; } else if (midVal > key) { // If mid is greater than key, all elements // in range [mid + 1, high] are >= key // we note down the last found index, then // we search in left side of mid // so we now search in [low, mid - 1] ans = mid; high = mid - 1; } else if (midVal == key) { // If mid is equal to key, all elements in // range [low, mid] are <= key // so we now search in [mid + 1, high] low = mid + 1; } } return ans;} /* Find index of last occurrence of greatest element less than key in array * Returns: an index in range [0, n-1] if key is not the least element in array, * -1 if key is the least element in array */static int greatestlesser(int low, int high, int key){ int ans = -1; while (low <= high) { int mid = low + (high - low + 1) / 2; int midVal = a[mid]; if (midVal < key) { // If mid is less than key, all elements // in range [low, mid - 1] are < key // we note down the last found index, then // we search in right side of mid // so we now search in [mid + 1, high] ans = mid; low = mid + 1; } else if (midVal > key) { // If mid is greater than key, all elements // in range [mid + 1, high] are > key // then we search in left side of mid // so we now search in [low, mid - 1] high = mid - 1; } else if (midVal == key) { // If mid is equal to key, all elements // in range [mid + 1, high] are >= key // then we search in left side of mid // so we now search in [low, mid - 1] high = mid - 1; } } return ans;} // Driver Codestatic void Main(){ Console.WriteLine("Contains"); for(int i = 0; i < 10; i++) Console.WriteLine(i + " " + contains(0, n - 1, i)); Console.WriteLine("First occurrence of key"); for(int i = 0; i < 10; i++) Console.WriteLine(i + " " + first(0, n - 1, i)); Console.WriteLine("Last occurrence of key"); for(int i = 0; i < 10; i++) Console.WriteLine(i + " " + last(0, n - 1, i)); Console.WriteLine("Least integer greater than key"); for(int i = 0; i < 10; i++) Console.WriteLine(i + " " + leastgreater(0, n - 1, i)); Console.WriteLine("Greatest integer lesser than key"); for(int i = 0; i < 10; i++) Console.WriteLine(i + " " + greatestlesser(0, n - 1, i));}} // This code is contributed by divyesh072019 Contains 0 0 1 0 2 1 3 1 4 0 5 1 6 1 7 0 8 0 9 0 First occurrence of key 0 -1 1 -1 2 0 3 1 4 -1 5 3 6 6 7 -1 8 -1 9 -1 Last occurrence of key 0 -1 1 -1 2 0 3 2 4 -1 5 5 6 7 7 -1 8 -1 9 -1 Least integer greater than key 0 0 1 0 2 1 3 3 4 3 5 6 6 -1 7 -1 8 -1 9 -1 Greatest integer lesser than key 0 -1 1 -1 2 -1 3 0 4 2 5 2 6 5 7 7 8 7 9 7 Here is the problem I have mentioned at the beginning of the post: KCOMPRES problem in Codechef. Do try it out and feel free post your queries here.More Binary Search Practice Problems harrypotter0 nidhi_biet coder_nero divyesh072019 divyeshrabadiya07 Binary Search Searching Searching Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n05 Jan, 2021" }, { "code": null, "e": 484, "s": 52, "text": "Binary search is very easy right? Well, binary search can become complex when element duplication occurs in the sorted list of values. It’s not always the “contains or not” we search using Binary Search, but there are 5 variants such as below:1) Contains (True or False) 2) Index of first occurrence of a key 3) Index of last occurrence of a key 4) Index of least element greater than key 5) Index of greatest element less than key" }, { "code": null, "e": 809, "s": 484, "text": "Each of these searches, while the base logic remains same, have a minor variation in implementation and competitive coders should be aware of them. You might have seen other approaches such as this for finding first and last occurrence, where you compare adjacent element also for checking of first/last element is reached. " }, { "code": null, "e": 1073, "s": 809, "text": "From a complexity perspective, it may look like an O(log n) algorithm, but it doesn’t work when the comparisons itself are expensive. A problem to prove this point is linked at the end of this post, feel free to try it out.Variant 1: Contains key (True or False) " }, { "code": null, "e": 1175, "s": 1073, "text": "Input : 2 3 3 5 5 5 6 6\nFunction : Contains(4)\nReturns : False\n\nFunction : Contains(5)\nReturns : True" }, { "code": null, "e": 1248, "s": 1175, "text": "Variant 2: First occurrence of key (index of array). This is similar to " }, { "code": null, "e": 1252, "s": 1248, "text": "C++" }, { "code": "std::lower_bound(...)", "e": 1274, "s": 1252, "text": null }, { "code": null, "e": 1397, "s": 1274, "text": "Input : 2 3 3 5 5 5 6 6\nFunction : first(3)\nReturns : 1\n\nFunction : first(5)\nReturns : 3\n\nFunction : first(4)\nReturns : -1" }, { "code": null, "e": 1449, "s": 1397, "text": "Variant 3: Last occurrence of key (index of array) " }, { "code": null, "e": 1569, "s": 1449, "text": "Input : 2 3 3 5 5 5 6 6\nFunction : last(3)\nReturns : 2\n\nFunction : last(5)\nReturns : 5\n\nFunction : last(4)\nReturns : -1" }, { "code": null, "e": 1659, "s": 1569, "text": "Variant 4: index(first occurrence) of least integer greater than key. This is similar to " }, { "code": null, "e": 1663, "s": 1659, "text": "C++" }, { "code": "std::upper_bound(...)", "e": 1685, "s": 1663, "text": null }, { "code": null, "e": 1788, "s": 1685, "text": "Input : 2 3 3 5 5 5 6 6\nFunction : leastGreater(2)\nReturns : 1\n\nFunction : leastGreater(5)\nReturns : 6" }, { "code": null, "e": 1859, "s": 1788, "text": "Variant 5: index(last occurrence) of greatest integer lesser than key " }, { "code": null, "e": 1967, "s": 1859, "text": "Input : 2 3 3 5 5 5 6 6\nFunction : greatestLesser(2)\nReturns : -1\n\nFunction : greatestLesser(5)\nReturns : 2" }, { "code": null, "e": 2140, "s": 1967, "text": "As you will see below, if you observe the clear difference between the implementations you will see that the same logic is used to find different variants of binary search." }, { "code": null, "e": 2144, "s": 2140, "text": "C++" }, { "code": null, "e": 2149, "s": 2144, "text": "Java" }, { "code": null, "e": 2152, "s": 2149, "text": "C#" }, { "code": "// C++ program to variants of Binary Search#include <bits/stdc++.h> using namespace std; int n = 8; // array sizeint a[] = { 2, 3, 3, 5, 5, 5, 6, 6 }; // Sorted array /* Find if key is in array * Returns: True if key belongs to array, * False if key doesn't belong to array */bool contains(int low, int high, int key){ bool ans = false; while (low <= high) { int mid = low + (high - low) / 2; int midVal = a[mid]; if (midVal < key) { // if mid is less than key, all elements // in range [low, mid] are also less // so we now search in [mid + 1, high] low = mid + 1; } else if (midVal > key) { // if mid is greater than key, all elements // in range [mid + 1, high] are also greater // so we now search in [low, mid - 1] high = mid - 1; } else if (midVal == key) { // comparison added just for the sake // of clarity if mid is equal to key, we // have found that key exists in array ans = true; break; } } return ans;} /* Find first occurrence index of key in array * Returns: an index in range [0, n-1] if key belongs * to array, -1 if key doesn't belong to array */int first(int low, int high, int key){ int ans = -1; while (low <= high) { int mid = low + (high - low + 1) / 2; int midVal = a[mid]; if (midVal < key) { // if mid is less than key, all elements // in range [low, mid] are also less // so we now search in [mid + 1, high] low = mid + 1; } else if (midVal > key) { // if mid is greater than key, all elements // in range [mid + 1, high] are also greater // so we now search in [low, mid - 1] high = mid - 1; } else if (midVal == key) { // if mid is equal to key, we note down // the last found index then we search // for more in left side of mid // so we now search in [low, mid - 1] ans = mid; high = mid - 1; } } return ans;} /* Find last occurrence index of key in array * Returns: an index in range [0, n-1] if key belongs to array, * -1 if key doesn't belong to array */int last(int low, int high, int key){ int ans = -1; while (low <= high) { int mid = low + (high - low + 1) / 2; int midVal = a[mid]; if (midVal < key) { // if mid is less than key, then all elements // in range [low, mid - 1] are also less // so we now search in [mid + 1, high] low = mid + 1; } else if (midVal > key) { // if mid is greater than key, then all // elements in range [mid + 1, high] are // also greater so we now search in // [low, mid - 1] high = mid - 1; } else if (midVal == key) { // if mid is equal to key, we note down // the last found index then we search // for more in right side of mid // so we now search in [mid + 1, high] ans = mid; low = mid + 1; } } return ans;} /* Find index of first occurrence of least element greater than key in array * Returns: an index in range [0, n-1] if key is not the greatest element in array, * -1 if key is the greatest element in array */int leastgreater(int low, int high, int key){ int ans = -1; while (low <= high) { int mid = low + (high - low + 1) / 2; int midVal = a[mid]; if (midVal < key) { // if mid is less than key, all elements // in range [low, mid - 1] are <= key // then we search in right side of mid // so we now search in [mid + 1, high] low = mid + 1; } else if (midVal > key) { // if mid is greater than key, all elements // in range [mid + 1, high] are >= key // we note down the last found index, then // we search in left side of mid // so we now search in [low, mid - 1] ans = mid; high = mid - 1; } else if (midVal == key) { // if mid is equal to key, all elements in // range [low, mid] are <= key // so we now search in [mid + 1, high] low = mid + 1; } } return ans;} /* Find index of last occurrence of greatest element less than key in array * Returns: an index in range [0, n-1] if key is not the least element in array, * -1 if key is the least element in array */int greatestlesser(int low, int high, int key){ int ans = -1; while (low <= high) { int mid = low + (high - low + 1) / 2; int midVal = a[mid]; if (midVal < key) { // if mid is less than key, all elements // in range [low, mid - 1] are < key // we note down the last found index, then // we search in right side of mid // so we now search in [mid + 1, high] ans = mid; low = mid + 1; } else if (midVal > key) { // if mid is greater than key, all elements // in range [mid + 1, high] are > key // then we search in left side of mid // so we now search in [low, mid - 1] high = mid - 1; } else if (midVal == key) { // if mid is equal to key, all elements // in range [mid + 1, high] are >= key // then we search in left side of mid // so we now search in [low, mid - 1] high = mid - 1; } } return ans;} int main(){ printf(\"Contains\\n\"); for (int i = 0; i < 10; i++) printf(\"%d %d\\n\", i, contains(0, n - 1, i)); printf(\"First occurrence of key\\n\"); for (int i = 0; i < 10; i++) printf(\"%d %d\\n\", i, first(0, n - 1, i)); printf(\"Last occurrence of key\\n\"); for (int i = 0; i < 10; i++) printf(\"%d %d\\n\", i, last(0, n - 1, i)); printf(\"Least integer greater than key\\n\"); for (int i = 0; i < 10; i++) printf(\"%d %d\\n\", i, leastgreater(0, n - 1, i)); printf(\"Greatest integer lesser than key\\n\"); for (int i = 0; i < 10; i++) printf(\"%d %d\\n\", i, greatestlesser(0, n - 1, i)); return 0;}", "e": 8634, "s": 2152, "text": null }, { "code": "// Java program to variants of Binary Searchimport java.util.*; class GFG{ // Array size static int n = 8; // Sorted arraystatic int a[] = { 2, 3, 3, 5, 5, 5, 6, 6 }; /* Find if key is in array * Returns: True if key belongs to array, * False if key doesn't belong to array */static int contains(int low, int high, int key){ int ans = 0; while (low <= high) { int mid = low + (high - low) / 2; int midVal = a[mid]; if (midVal < key) { // If mid is less than key, all elements // in range [low, mid] are also less // so we now search in [mid + 1, high] low = mid + 1; } else if (midVal > key) { // If mid is greater than key, all elements // in range [mid + 1, high] are also greater // so we now search in [low, mid - 1] high = mid - 1; } else if (midVal == key) { // Comparison added just for the sake // of clarity if mid is equal to key, we // have found that key exists in array ans = 1; break; } } return ans;} /* Find first occurrence index of key in array * Returns: an index in range [0, n-1] if key belongs * to array, -1 if key doesn't belong to array */static int first(int low, int high, int key){ int ans = -1; while (low <= high) { int mid = low + (high - low + 1) / 2; int midVal = a[mid]; if (midVal < key) { // If mid is less than key, all elements // in range [low, mid] are also less // so we now search in [mid + 1, high] low = mid + 1; } else if (midVal > key) { // If mid is greater than key, all elements // in range [mid + 1, high] are also greater // so we now search in [low, mid - 1] high = mid - 1; } else if (midVal == key) { // If mid is equal to key, we note down // the last found index then we search // for more in left side of mid // so we now search in [low, mid - 1] ans = mid; high = mid - 1; } } return ans;} /* Find last occurrence index of key in array * Returns: an index in range [0, n-1] if key belongs to array, -1 if key doesn't belong to array */static int last(int low, int high, int key){ int ans = -1; while (low <= high) { int mid = low + (high - low + 1) / 2; int midVal = a[mid]; if (midVal < key) { // If mid is less than key, then all elements // in range [low, mid - 1] are also less // so we now search in [mid + 1, high] low = mid + 1; } else if (midVal > key) { // If mid is greater than key, then all // elements in range [mid + 1, high] are // also greater so we now search in // [low, mid - 1] high = mid - 1; } else if (midVal == key) { // If mid is equal to key, we note down // the last found index then we search // for more in right side of mid // so we now search in [mid + 1, high] ans = mid; low = mid + 1; } } return ans;} /* Find index of first occurrence of least element greater than key in array * Returns: an index in range [0, n-1] if key is not the greatest element in array, -1 if key * is the greatest element in array */static int leastgreater(int low, int high, int key){ int ans = -1; while (low <= high) { int mid = low + (high - low + 1) / 2; int midVal = a[mid]; if (midVal < key) { // If mid is less than key, all elements // in range [low, mid - 1] are <= key // then we search in right side of mid // so we now search in [mid + 1, high] low = mid + 1; } else if (midVal > key) { // If mid is greater than key, all elements // in range [mid + 1, high] are >= key // we note down the last found index, then // we search in left side of mid // so we now search in [low, mid - 1] ans = mid; high = mid - 1; } else if (midVal == key) { // If mid is equal to key, all elements in // range [low, mid] are <= key // so we now search in [mid + 1, high] low = mid + 1; } } return ans;} /* Find index of last occurrence of greatest element less than key in array * Returns: an index in range [0, n-1] if key is not the least element in array, -1 if * key is the least element in array */static int greatestlesser(int low, int high, int key){ int ans = -1; while (low <= high) { int mid = low + (high - low + 1) / 2; int midVal = a[mid]; if (midVal < key) { // If mid is less than key, all elements // in range [low, mid - 1] are < key // we note down the last found index, then // we search in right side of mid // so we now search in [mid + 1, high] ans = mid; low = mid + 1; } else if (midVal > key) { // If mid is greater than key, all elements // in range [mid + 1, high] are > key // then we search in left side of mid // so we now search in [low, mid - 1] high = mid - 1; } else if (midVal == key) { // If mid is equal to key, all elements // in range [mid + 1, high] are >= key // then we search in left side of mid // so we now search in [low, mid - 1] high = mid - 1; } } return ans;} // Driver Codepublic static void main(String[] args){ System.out.println(\"Contains\"); for(int i = 0; i < 10; i++) System.out.println(i + \" \" + contains(0, n - 1, i)); System.out.println(\"First occurrence of key\"); for(int i = 0; i < 10; i++) System.out.println(i + \" \" + first(0, n - 1, i)); System.out.println(\"Last occurrence of key\"); for(int i = 0; i < 10; i++) System.out.println(i + \" \" + last(0, n - 1, i)); System.out.println(\"Least integer greater than key\"); for(int i = 0; i < 10; i++) System.out.println(i + \" \" + leastgreater(0, n - 1, i)); System.out.println(\"Greatest integer lesser than key\"); for(int i = 0; i < 10; i++) System.out.println(i + \" \" + greatestlesser(0, n - 1, i));}} // This code is contributed by divyeshrabadiya07", "e": 15715, "s": 8634, "text": null }, { "code": "// C# program to variants of Binary Searchusing System; class GFG{ // Array size static int n = 8; // Sorted arraystatic int[] a = { 2, 3, 3, 5, 5, 5, 6, 6 }; /* Find if key is in array * Returns: True if key belongs to array, * False if key doesn't belong to array */static int contains(int low, int high, int key){ int ans = 0; while (low <= high) { int mid = low + (high - low) / 2; int midVal = a[mid]; if (midVal < key) { // If mid is less than key, all elements // in range [low, mid] are also less // so we now search in [mid + 1, high] low = mid + 1; } else if (midVal > key) { // If mid is greater than key, all elements // in range [mid + 1, high] are also greater // so we now search in [low, mid - 1] high = mid - 1; } else if (midVal == key) { // Comparison added just for the sake // of clarity if mid is equal to key, we // have found that key exists in array ans = 1; break; } } return ans;} /* Find first occurrence index of key in array * Returns: an index in range [0, n-1] if key belongs * to array, -1 if key doesn't belong to array */static int first(int low, int high, int key){ int ans = -1; while (low <= high) { int mid = low + (high - low + 1) / 2; int midVal = a[mid]; if (midVal < key) { // If mid is less than key, all elements // in range [low, mid] are also less // so we now search in [mid + 1, high] low = mid + 1; } else if (midVal > key) { // If mid is greater than key, all elements // in range [mid + 1, high] are also greater // so we now search in [low, mid - 1] high = mid - 1; } else if (midVal == key) { // If mid is equal to key, we note down // the last found index then we search // for more in left side of mid // so we now search in [low, mid - 1] ans = mid; high = mid - 1; } } return ans;} /* Find last occurrence index of key in array * Returns: an index in range [0, n-1] if key belongs to array, -1 if key doesn't belong to array */static int last(int low, int high, int key){ int ans = -1; while (low <= high) { int mid = low + (high - low + 1) / 2; int midVal = a[mid]; if (midVal < key) { // If mid is less than key, then all elements // in range [low, mid - 1] are also less // so we now search in [mid + 1, high] low = mid + 1; } else if (midVal > key) { // If mid is greater than key, then all // elements in range [mid + 1, high] are // also greater so we now search in // [low, mid - 1] high = mid - 1; } else if (midVal == key) { // If mid is equal to key, we note down // the last found index then we search // for more in right side of mid // so we now search in [mid + 1, high] ans = mid; low = mid + 1; } } return ans;} /* Find index of first occurrence of least element greater than key in array * Returns: an index in range [0, n-1] if key is not the greatest element in array, * -1 if key is the greatest element in array */static int leastgreater(int low, int high, int key){ int ans = -1; while (low <= high) { int mid = low + (high - low + 1) / 2; int midVal = a[mid]; if (midVal < key) { // If mid is less than key, all elements // in range [low, mid - 1] are <= key // then we search in right side of mid // so we now search in [mid + 1, high] low = mid + 1; } else if (midVal > key) { // If mid is greater than key, all elements // in range [mid + 1, high] are >= key // we note down the last found index, then // we search in left side of mid // so we now search in [low, mid - 1] ans = mid; high = mid - 1; } else if (midVal == key) { // If mid is equal to key, all elements in // range [low, mid] are <= key // so we now search in [mid + 1, high] low = mid + 1; } } return ans;} /* Find index of last occurrence of greatest element less than key in array * Returns: an index in range [0, n-1] if key is not the least element in array, * -1 if key is the least element in array */static int greatestlesser(int low, int high, int key){ int ans = -1; while (low <= high) { int mid = low + (high - low + 1) / 2; int midVal = a[mid]; if (midVal < key) { // If mid is less than key, all elements // in range [low, mid - 1] are < key // we note down the last found index, then // we search in right side of mid // so we now search in [mid + 1, high] ans = mid; low = mid + 1; } else if (midVal > key) { // If mid is greater than key, all elements // in range [mid + 1, high] are > key // then we search in left side of mid // so we now search in [low, mid - 1] high = mid - 1; } else if (midVal == key) { // If mid is equal to key, all elements // in range [mid + 1, high] are >= key // then we search in left side of mid // so we now search in [low, mid - 1] high = mid - 1; } } return ans;} // Driver Codestatic void Main(){ Console.WriteLine(\"Contains\"); for(int i = 0; i < 10; i++) Console.WriteLine(i + \" \" + contains(0, n - 1, i)); Console.WriteLine(\"First occurrence of key\"); for(int i = 0; i < 10; i++) Console.WriteLine(i + \" \" + first(0, n - 1, i)); Console.WriteLine(\"Last occurrence of key\"); for(int i = 0; i < 10; i++) Console.WriteLine(i + \" \" + last(0, n - 1, i)); Console.WriteLine(\"Least integer greater than key\"); for(int i = 0; i < 10; i++) Console.WriteLine(i + \" \" + leastgreater(0, n - 1, i)); Console.WriteLine(\"Greatest integer lesser than key\"); for(int i = 0; i < 10; i++) Console.WriteLine(i + \" \" + greatestlesser(0, n - 1, i));}} // This code is contributed by divyesh072019", "e": 22719, "s": 15715, "text": null }, { "code": null, "e": 23058, "s": 22719, "text": "Contains\n0 0\n1 0\n2 1\n3 1\n4 0\n5 1\n6 1\n7 0\n8 0\n9 0\nFirst occurrence of key\n0 -1\n1 -1\n2 0\n3 1\n4 -1\n5 3\n6 6\n7 -1\n8 -1\n9 -1\nLast occurrence of key\n0 -1\n1 -1\n2 0\n3 2\n4 -1\n5 5\n6 7\n7 -1\n8 -1\n9 -1\nLeast integer greater than key\n0 0\n1 0\n2 1\n3 3\n4 3\n5 6\n6 -1\n7 -1\n8 -1\n9 -1\nGreatest integer lesser than key\n0 -1\n1 -1\n2 -1\n3 0\n4 2\n5 2\n6 5\n7 7\n8 7\n9 7" }, { "code": null, "e": 23246, "s": 23060, "text": "Here is the problem I have mentioned at the beginning of the post: KCOMPRES problem in Codechef. Do try it out and feel free post your queries here.More Binary Search Practice Problems " }, { "code": null, "e": 23261, "s": 23248, "text": "harrypotter0" }, { "code": null, "e": 23272, "s": 23261, "text": "nidhi_biet" }, { "code": null, "e": 23283, "s": 23272, "text": "coder_nero" }, { "code": null, "e": 23297, "s": 23283, "text": "divyesh072019" }, { "code": null, "e": 23315, "s": 23297, "text": "divyeshrabadiya07" }, { "code": null, "e": 23329, "s": 23315, "text": "Binary Search" }, { "code": null, "e": 23339, "s": 23329, "text": "Searching" }, { "code": null, "e": 23349, "s": 23339, "text": "Searching" }, { "code": null, "e": 23363, "s": 23349, "text": "Binary Search" } ]
Exposing ML/DL Models as REST APIs
17 Jan, 2019 In this article, we will learn how to expose ML/DL model as flask APIs. Frameworks we’ll be using:Keras is a Deep Learning library, built on top of backends such as Tensorflow, Theano or CNTK. It provides abstraction and allows rapid development of ML/DL models. Flask is a micro web framework in Python, which is used to quickly spin up servers to serve pages. Refer Introduction to Flask. Since the focus of the article is to serve a ML/DL model using an API, we wouldn’t get deeper into the making of the Convolutional model. We will be using the ResNet50 Convolutional Neural Network. Install Tensorflow and Keras Examples: Creating the REST API : # keras_server.py # Python program to expose a ML model as flask REST API # import the necessary modulesfrom keras.applications import ResNet50 # pre-built CNN Modelfrom keras.preprocessing.image import img_to_array from keras.applications import imagenet_utilsimport tensorflow as tffrom PIL import Imageimport numpy as npimport flaskimport io # Create Flask application and initialize Keras modelapp = flask.Flask(__name__)model = None # Function to Load the model def load_model(): # global variables, to be used in another function global model model = ResNet50(weights ="imagenet") global graph graph = tf.get_default_graph() # Every ML/DL model has a specific format# of taking input. Before we can predict on# the input image, we first need to preprocess it.def prepare_image(image, target): if image.mode != "RGB": image = image.convert("RGB") # Resize the image to the target dimensions image = image.resize(target) # PIL Image to Numpy array image = img_to_array(image) # Expand the shape of an array, # as required by the Model image = np.expand_dims(image, axis = 0) # preprocess_input function is meant to # adequate your image to the format the model requires image = imagenet_utils.preprocess_input(image) # return the processed image return image # Now, we can predict the [email protected]("/predict", methods =["POST"])def predict(): data = {} # dictionary to store result data["success"] = False # Check if image was properly sent to our endpoint if flask.request.method == "POST": if flask.request.files.get("image"): image = flask.request.files["image"].read() image = Image.open(io.BytesIO(image)) # Resize it to 224x224 pixels # (required input dimensions for ResNet) image = prepare_image(image, target =(224, 224)) # Predict ! global preds, results with graph.as_default(): preds = model.predict(image) results = imagenet_utils.decode_predictions(preds) data["predictions"] = [] for (ID, label, probability) in results[0]: r = {"label": label, "probability": float(probability)} data["predictions"].append(r) data["success"] = True # return JSON response return flask.jsonify(data) if __name__ == "__main__": print(("* Loading Keras model and Flask starting server..." "please wait until server has fully started")) load_model() app.run() Run the flask server python keras_server.py Note #1: For the first time you run it, it takes time to download the weights of the model. In subsequent runs, this won’t be the case.Note #2: Save images in the same directory (ml-api) – dog.jpg, cat.jpg, lion.jpg . Method #1 : use cURL (Download cURL for Windows from here.) $ curl -X POST -F [email protected] "http://localhost:5000/predict" Method #2 : (Suitable if making a Full-stack web app with proper UI)Create a simple HTML form <!-- index.html --><form action = "http://localhost:5000/predict" method = "POST" enctype = "multipart/form-data"> <input type = "file" name = "image" /> <input type = "submit"/></form> Method #3 : Create a simple python script to make HTTP requests to flask server. # simple_request.pyimport requestsimport sys URL = "http://localhost:5000/predict" # provide image name as command line argumentIMAGE_PATH = sys.argv[1] image = open(IMAGE_PATH, "rb").read()payload = {"image": image} # make request to the APIrequest = requests.post(URL, files = payload).json() if request["success"]: # Print formatted Result print("% s % 15s % s"%("Rank", "Label", "Probability")) for (i, result) in enumerate(request["predictions"]): print("% d. % 17s %.4f"%(i + 1, result["label"], result["probability"])) else: print("Request failed") Run it as : python simple_request.py dog.jpg Output: To deactivate after you are done(both Windows and Linux) : > deactivate So the workflow, in general for any model is Build the model and save it. Create a Flask app. Load the Model Define endpoints of API for each type of requests. Preprocess input according to the Model’s architecture and feed it to the model Process the input and send back the output to client. Technical Scripter 2018 Machine Learning Python Technical Scripter Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n17 Jan, 2019" }, { "code": null, "e": 126, "s": 54, "text": "In this article, we will learn how to expose ML/DL model as flask APIs." }, { "code": null, "e": 317, "s": 126, "text": "Frameworks we’ll be using:Keras is a Deep Learning library, built on top of backends such as Tensorflow, Theano or CNTK. It provides abstraction and allows rapid development of ML/DL models." }, { "code": null, "e": 445, "s": 317, "text": "Flask is a micro web framework in Python, which is used to quickly spin up servers to serve pages. Refer Introduction to Flask." }, { "code": null, "e": 643, "s": 445, "text": "Since the focus of the article is to serve a ML/DL model using an API, we wouldn’t get deeper into the making of the Convolutional model. We will be using the ResNet50 Convolutional Neural Network." }, { "code": null, "e": 672, "s": 643, "text": "Install Tensorflow and Keras" }, { "code": null, "e": 682, "s": 672, "text": "Examples:" }, { "code": null, "e": 706, "s": 682, "text": "Creating the REST API :" }, { "code": "# keras_server.py # Python program to expose a ML model as flask REST API # import the necessary modulesfrom keras.applications import ResNet50 # pre-built CNN Modelfrom keras.preprocessing.image import img_to_array from keras.applications import imagenet_utilsimport tensorflow as tffrom PIL import Imageimport numpy as npimport flaskimport io # Create Flask application and initialize Keras modelapp = flask.Flask(__name__)model = None # Function to Load the model def load_model(): # global variables, to be used in another function global model model = ResNet50(weights =\"imagenet\") global graph graph = tf.get_default_graph() # Every ML/DL model has a specific format# of taking input. Before we can predict on# the input image, we first need to preprocess it.def prepare_image(image, target): if image.mode != \"RGB\": image = image.convert(\"RGB\") # Resize the image to the target dimensions image = image.resize(target) # PIL Image to Numpy array image = img_to_array(image) # Expand the shape of an array, # as required by the Model image = np.expand_dims(image, axis = 0) # preprocess_input function is meant to # adequate your image to the format the model requires image = imagenet_utils.preprocess_input(image) # return the processed image return image # Now, we can predict the [email protected](\"/predict\", methods =[\"POST\"])def predict(): data = {} # dictionary to store result data[\"success\"] = False # Check if image was properly sent to our endpoint if flask.request.method == \"POST\": if flask.request.files.get(\"image\"): image = flask.request.files[\"image\"].read() image = Image.open(io.BytesIO(image)) # Resize it to 224x224 pixels # (required input dimensions for ResNet) image = prepare_image(image, target =(224, 224)) # Predict ! global preds, results with graph.as_default(): preds = model.predict(image) results = imagenet_utils.decode_predictions(preds) data[\"predictions\"] = [] for (ID, label, probability) in results[0]: r = {\"label\": label, \"probability\": float(probability)} data[\"predictions\"].append(r) data[\"success\"] = True # return JSON response return flask.jsonify(data) if __name__ == \"__main__\": print((\"* Loading Keras model and Flask starting server...\" \"please wait until server has fully started\")) load_model() app.run()", "e": 3319, "s": 706, "text": null }, { "code": null, "e": 3340, "s": 3319, "text": "Run the flask server" }, { "code": null, "e": 3364, "s": 3340, "text": "python keras_server.py " }, { "code": null, "e": 3583, "s": 3364, "text": " Note #1: For the first time you run it, it takes time to download the weights of the model. In subsequent runs, this won’t be the case.Note #2: Save images in the same directory (ml-api) – dog.jpg, cat.jpg, lion.jpg ." }, { "code": null, "e": 3643, "s": 3583, "text": "Method #1 : use cURL (Download cURL for Windows from here.)" }, { "code": null, "e": 3708, "s": 3643, "text": "$ curl -X POST -F [email protected] \"http://localhost:5000/predict\"" }, { "code": null, "e": 3803, "s": 3708, "text": " Method #2 : (Suitable if making a Full-stack web app with proper UI)Create a simple HTML form" }, { "code": "<!-- index.html --><form action = \"http://localhost:5000/predict\" method = \"POST\" enctype = \"multipart/form-data\"> <input type = \"file\" name = \"image\" /> <input type = \"submit\"/></form>", "e": 4014, "s": 3803, "text": null }, { "code": null, "e": 4096, "s": 4014, "text": " Method #3 : Create a simple python script to make HTTP requests to flask server." }, { "code": "# simple_request.pyimport requestsimport sys URL = \"http://localhost:5000/predict\" # provide image name as command line argumentIMAGE_PATH = sys.argv[1] image = open(IMAGE_PATH, \"rb\").read()payload = {\"image\": image} # make request to the APIrequest = requests.post(URL, files = payload).json() if request[\"success\"]: # Print formatted Result print(\"% s % 15s % s\"%(\"Rank\", \"Label\", \"Probability\")) for (i, result) in enumerate(request[\"predictions\"]): print(\"% d. % 17s %.4f\"%(i + 1, result[\"label\"], result[\"probability\"])) else: print(\"Request failed\")", "e": 4700, "s": 4096, "text": null }, { "code": null, "e": 4712, "s": 4700, "text": "Run it as :" }, { "code": null, "e": 4745, "s": 4712, "text": "python simple_request.py dog.jpg" }, { "code": null, "e": 4753, "s": 4745, "text": "Output:" }, { "code": null, "e": 4812, "s": 4753, "text": "To deactivate after you are done(both Windows and Linux) :" }, { "code": null, "e": 4826, "s": 4812, "text": "> deactivate\n" }, { "code": null, "e": 4871, "s": 4826, "text": "So the workflow, in general for any model is" }, { "code": null, "e": 4900, "s": 4871, "text": "Build the model and save it." }, { "code": null, "e": 4920, "s": 4900, "text": "Create a Flask app." }, { "code": null, "e": 4935, "s": 4920, "text": "Load the Model" }, { "code": null, "e": 4986, "s": 4935, "text": "Define endpoints of API for each type of requests." }, { "code": null, "e": 5066, "s": 4986, "text": "Preprocess input according to the Model’s architecture and feed it to the model" }, { "code": null, "e": 5120, "s": 5066, "text": "Process the input and send back the output to client." }, { "code": null, "e": 5144, "s": 5120, "text": "Technical Scripter 2018" }, { "code": null, "e": 5161, "s": 5144, "text": "Machine Learning" }, { "code": null, "e": 5168, "s": 5161, "text": "Python" }, { "code": null, "e": 5187, "s": 5168, "text": "Technical Scripter" }, { "code": null, "e": 5204, "s": 5187, "text": "Machine Learning" } ]
Print last k digits of a^b (a raised to power b)
13 Jul, 2022 Given positive integers k, a and b we need to print last k digits of a^b ie.. pow(a, b). Input Constraint: k <= 9, a <= 10^6, b<= 10^6 Examples: Input : a = 11, b = 3, k = 2 Output : 31 Explanation : a^b = 11^3 = 1331, hence last two digits are 31 Input : a = 10, b = 10000, k = 5 Output : 00000 Explanation : a^b = 1000..........0 (total zeros = 10000), hence last 5 digits are 00000 First Calculate a^b, then take last k digits by taking modulo with 10^k. Above solution fails when a^b is too large, as we can hold at most 2^64 -1 in C/C++. The efficient way is to keep only k digits after every multiplication. This idea is very similar to discussed in Modular Exponentiation where we discussed a general way to find (a^b)%c, here in this case c is 10^k. Here is the implementation. C++ Java Python3 C# PHP Javascript // C++ code to find last k digits of a^b#include <iostream>using namespace std; /* Iterative Function to calculate (x^y)%p in O(log y) */int power(long long int x, long long int y, long long int p){ long long int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y & 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} // C++ function to calculate// number of digits in xint numberOfDigits(int x){ int i = 0; while (x) { x /= 10; i++; } return i;} // C++ function to print last k digits of a^bvoid printLastKDigits(int a, int b, int k){ cout << "Last " << k; cout << " digits of " << a; cout << "^" << b << " = "; // Generating 10^k int temp = 1; for (int i = 1; i <= k; i++) temp *= 10; // Calling modular exponentiation temp = power(a, b, temp); // Printing leftmost zeros. Since (a^b)%k // can have digits less than k. In that // case we need to print zeros for (int i = 0; i < k - numberOfDigits(temp); i++) cout << 0; // If temp is not zero then print temp // If temp is zero then already printed if (temp) cout << temp;} // Driver program to test above functionsint main(){ int a = 11; int b = 3; int k = 2; printLastKDigits(a, b, k); return 0;} // Java code to find last k digits of a^b public class GFG{ /* Iterative Function to calculate (x^y)%p in O(log y) */ static int power(long x, long y, long p) { long res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return (int) res; } // Method to print last k digits of a^b static void printLastKDigits(int a, int b, int k) { System.out.print("Last " + k + " digits of " + a + "^" + b + " = "); // Generating 10^k int temp = 1; for (int i = 1; i <= k; i++) temp *= 10; // Calling modular exponentiation temp = power(a, b, temp); // Printing leftmost zeros. Since (a^b)%k // can have digits less than k. In that // case we need to print zeros for (int i = 0; i < k - Integer.toString(temp).length() ; i++) System.out.print(0); // If temp is not zero then print temp // If temp is zero then already printed if (temp != 0) System.out.print(temp); } // Driver Method public static void main(String[] args) { int a = 11; int b = 3; int k = 2; printLastKDigits(a, b, k); }} # Python 3 code to find last# k digits of a^b # Iterative Function to calculate# (x^y)%p in O(log y)def power(x, y, p): res = 1 # Initialize result x = x % p # Update x if it is more # than or equal to p while (y > 0) : # If y is odd, multiply # x with result if (y & 1): res = (res * x) % p # y must be even now y = y >> 1 # y = y/2 x = (x * x) % p return res # function to calculate# number of digits in xdef numberOfDigits(x): i = 0 while (x) : x //= 10 i += 1 return i # function to print last k digits of a^bdef printLastKDigits( a, b, k): print("Last " + str( k)+" digits of " + str(a) + "^" + str(b), end = " = ") # Generating 10^k temp = 1 for i in range(1, k + 1): temp *= 10 # Calling modular exponentiation temp = power(a, b, temp) # Printing leftmost zeros. Since (a^b)%k # can have digits less than k. In that # case we need to print zeros for i in range( k - numberOfDigits(temp)): print("0") # If temp is not zero then print temp # If temp is zero then already printed if (temp): print(temp) # Driver Codeif __name__ == "__main__": a = 11 b = 3 k = 2 printLastKDigits(a, b, k) # This code is contributed# by ChitraNayal // C# code to find last k digits of a^busing System; class GFG{ // Iterative Function to calculate// (x^y)%p in O(log y)static int power(long x, long y, long p){ long res = 1; // Initialize result x = x % p; // Update x if it is more // than or equal to p while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return (int) res;} // Method to print last k digits of a^bstatic void printLastKDigits(int a, int b, int k){ Console.Write("Last " + k + " digits of " + a + "^" + b + " = "); // Generating 10^k int temp = 1; for (int i = 1; i <= k; i++) temp *= 10; // Calling modular exponentiation temp = power(a, b, temp); // Printing leftmost zeros. Since (a^b)%k // can have digits less than k. In that // case we need to print zeros for (int i = 0; i < k - temp.ToString().Length; i++) Console.WriteLine(0); // If temp is not zero then print temp // If temp is zero then already printed if (temp != 0) Console.Write(temp);} // Driver Codepublic static void Main(){ int a = 11; int b = 3; int k = 2; printLastKDigits(a, b, k);}} // This code is contributed// by 29AjayKumar <?php// PHP code to find last k digits of a^b /* Iterative Function to calculate (x^y)%p in O(log y) */ function power($x, $y, $p){ $res = 1; // Initialize result $x = $x % $p; // Update x if it is more // than or equal to p while ($y > 0) { // If y is odd, multiply x // with result if ($y & 1) $res = ($res * $x) % $p; // y must be even now $y = $y >> 1; // y = y/2 $x = ($x * $x) % $p; } return $res;} // function to calculate// number of digits in xfunction numberOfDigits($x){ $i = 0; while ($x) { $x = (int)$x / 10; $i++; } return $i;} // function to print last k digits of a^bfunction printLastKDigits( $a, $b, $k){ echo "Last ",$k; echo " digits of " ,$a; echo "^" , $b , " = "; // Generating 10^k $temp = 1; for ($i = 1; $i <= $k; $i++) $temp *= 10; // Calling modular exponentiation $temp = power($a, $b, $temp); // Printing leftmost zeros. Since // (a^b)%k can have digits less // then k. In that case we need // to print zeros for ($i = 0; $i < $k - numberOfDigits($temp); $i++) echo 0; // If temp is not zero then print temp // If temp is zero then already printed if ($temp) echo $temp;} // Driver Code$a = 11;$b = 3;$k = 2;printLastKDigits($a, $b, $k); // This code is contributed by ajit?> <script>// javascript code to find last k digits of a^b /* Iterative Function to calculate (x^y)%p in O(log y) */ function power(x , y , p) { var res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return parseInt( res); } // Method to print last k digits of a^b function printLastKDigits(a , b , k) { document.write("Last " + k + " digits of " + a + "^" + b + " = "); // Generating 10^k var temp = 1; for (i = 1; i <= k; i++) temp *= 10; // Calling modular exponentiation temp = power(a, b, temp); // Printing leftmost zeros. Since (a^b)%k // can have digits less than k. In that // case we need to print zeros for (i = 0; i < k - temp.toString().length; i++) document.write(0); // If temp is not zero then print temp // If temp is zero then already printed if (temp != 0) document.write(temp); } // Driver Method var a = 11; var b = 3; var k = 2; printLastKDigits(a, b, k); // This code contributed by gauravrajput1</script> Output: Last 2 digits of 11^3 = 31 Time Complexity : O(log b) Space Complexity : O(1) This article is contributed by Pratik Chhajer. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. ukasp jit_t 29AjayKumar GauravRajput1 simmytarika5 khushboogoyal499 simranarora5sos mitalibhola94 Modular Arithmetic number-digits Mathematical Mathematical Modular Arithmetic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Jul, 2022" }, { "code": null, "e": 141, "s": 52, "text": "Given positive integers k, a and b we need to print last k digits of a^b ie.. pow(a, b)." }, { "code": null, "e": 187, "s": 141, "text": "Input Constraint:\nk <= 9, a <= 10^6, b<= 10^6" }, { "code": null, "e": 198, "s": 187, "text": "Examples: " }, { "code": null, "e": 441, "s": 198, "text": "Input : a = 11, b = 3, k = 2\nOutput : 31\nExplanation : a^b = 11^3 = 1331, hence \nlast two digits are 31\n\nInput : a = 10, b = 10000, k = 5\nOutput : 00000\nExplanation : a^b = 1000..........0 (total \nzeros = 10000), hence last 5 digits are 00000" }, { "code": null, "e": 599, "s": 441, "text": "First Calculate a^b, then take last k digits by taking modulo with 10^k. Above solution fails when a^b is too large, as we can hold at most 2^64 -1 in C/C++." }, { "code": null, "e": 814, "s": 599, "text": "The efficient way is to keep only k digits after every multiplication. This idea is very similar to discussed in Modular Exponentiation where we discussed a general way to find (a^b)%c, here in this case c is 10^k." }, { "code": null, "e": 842, "s": 814, "text": "Here is the implementation." }, { "code": null, "e": 846, "s": 842, "text": "C++" }, { "code": null, "e": 851, "s": 846, "text": "Java" }, { "code": null, "e": 859, "s": 851, "text": "Python3" }, { "code": null, "e": 862, "s": 859, "text": "C#" }, { "code": null, "e": 866, "s": 862, "text": "PHP" }, { "code": null, "e": 877, "s": 866, "text": "Javascript" }, { "code": "// C++ code to find last k digits of a^b#include <iostream>using namespace std; /* Iterative Function to calculate (x^y)%p in O(log y) */int power(long long int x, long long int y, long long int p){ long long int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y & 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} // C++ function to calculate// number of digits in xint numberOfDigits(int x){ int i = 0; while (x) { x /= 10; i++; } return i;} // C++ function to print last k digits of a^bvoid printLastKDigits(int a, int b, int k){ cout << \"Last \" << k; cout << \" digits of \" << a; cout << \"^\" << b << \" = \"; // Generating 10^k int temp = 1; for (int i = 1; i <= k; i++) temp *= 10; // Calling modular exponentiation temp = power(a, b, temp); // Printing leftmost zeros. Since (a^b)%k // can have digits less than k. In that // case we need to print zeros for (int i = 0; i < k - numberOfDigits(temp); i++) cout << 0; // If temp is not zero then print temp // If temp is zero then already printed if (temp) cout << temp;} // Driver program to test above functionsint main(){ int a = 11; int b = 3; int k = 2; printLastKDigits(a, b, k); return 0;}", "e": 2359, "s": 877, "text": null }, { "code": "// Java code to find last k digits of a^b public class GFG{ /* Iterative Function to calculate (x^y)%p in O(log y) */ static int power(long x, long y, long p) { long res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return (int) res; } // Method to print last k digits of a^b static void printLastKDigits(int a, int b, int k) { System.out.print(\"Last \" + k + \" digits of \" + a + \"^\" + b + \" = \"); // Generating 10^k int temp = 1; for (int i = 1; i <= k; i++) temp *= 10; // Calling modular exponentiation temp = power(a, b, temp); // Printing leftmost zeros. Since (a^b)%k // can have digits less than k. In that // case we need to print zeros for (int i = 0; i < k - Integer.toString(temp).length() ; i++) System.out.print(0); // If temp is not zero then print temp // If temp is zero then already printed if (temp != 0) System.out.print(temp); } // Driver Method public static void main(String[] args) { int a = 11; int b = 3; int k = 2; printLastKDigits(a, b, k); }}", "e": 3919, "s": 2359, "text": null }, { "code": "# Python 3 code to find last# k digits of a^b # Iterative Function to calculate# (x^y)%p in O(log y)def power(x, y, p): res = 1 # Initialize result x = x % p # Update x if it is more # than or equal to p while (y > 0) : # If y is odd, multiply # x with result if (y & 1): res = (res * x) % p # y must be even now y = y >> 1 # y = y/2 x = (x * x) % p return res # function to calculate# number of digits in xdef numberOfDigits(x): i = 0 while (x) : x //= 10 i += 1 return i # function to print last k digits of a^bdef printLastKDigits( a, b, k): print(\"Last \" + str( k)+\" digits of \" + str(a) + \"^\" + str(b), end = \" = \") # Generating 10^k temp = 1 for i in range(1, k + 1): temp *= 10 # Calling modular exponentiation temp = power(a, b, temp) # Printing leftmost zeros. Since (a^b)%k # can have digits less than k. In that # case we need to print zeros for i in range( k - numberOfDigits(temp)): print(\"0\") # If temp is not zero then print temp # If temp is zero then already printed if (temp): print(temp) # Driver Codeif __name__ == \"__main__\": a = 11 b = 3 k = 2 printLastKDigits(a, b, k) # This code is contributed# by ChitraNayal", "e": 5267, "s": 3919, "text": null }, { "code": "// C# code to find last k digits of a^busing System; class GFG{ // Iterative Function to calculate// (x^y)%p in O(log y)static int power(long x, long y, long p){ long res = 1; // Initialize result x = x % p; // Update x if it is more // than or equal to p while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return (int) res;} // Method to print last k digits of a^bstatic void printLastKDigits(int a, int b, int k){ Console.Write(\"Last \" + k + \" digits of \" + a + \"^\" + b + \" = \"); // Generating 10^k int temp = 1; for (int i = 1; i <= k; i++) temp *= 10; // Calling modular exponentiation temp = power(a, b, temp); // Printing leftmost zeros. Since (a^b)%k // can have digits less than k. In that // case we need to print zeros for (int i = 0; i < k - temp.ToString().Length; i++) Console.WriteLine(0); // If temp is not zero then print temp // If temp is zero then already printed if (temp != 0) Console.Write(temp);} // Driver Codepublic static void Main(){ int a = 11; int b = 3; int k = 2; printLastKDigits(a, b, k);}} // This code is contributed// by 29AjayKumar", "e": 6648, "s": 5267, "text": null }, { "code": "<?php// PHP code to find last k digits of a^b /* Iterative Function to calculate (x^y)%p in O(log y) */ function power($x, $y, $p){ $res = 1; // Initialize result $x = $x % $p; // Update x if it is more // than or equal to p while ($y > 0) { // If y is odd, multiply x // with result if ($y & 1) $res = ($res * $x) % $p; // y must be even now $y = $y >> 1; // y = y/2 $x = ($x * $x) % $p; } return $res;} // function to calculate// number of digits in xfunction numberOfDigits($x){ $i = 0; while ($x) { $x = (int)$x / 10; $i++; } return $i;} // function to print last k digits of a^bfunction printLastKDigits( $a, $b, $k){ echo \"Last \",$k; echo \" digits of \" ,$a; echo \"^\" , $b , \" = \"; // Generating 10^k $temp = 1; for ($i = 1; $i <= $k; $i++) $temp *= 10; // Calling modular exponentiation $temp = power($a, $b, $temp); // Printing leftmost zeros. Since // (a^b)%k can have digits less // then k. In that case we need // to print zeros for ($i = 0; $i < $k - numberOfDigits($temp); $i++) echo 0; // If temp is not zero then print temp // If temp is zero then already printed if ($temp) echo $temp;} // Driver Code$a = 11;$b = 3;$k = 2;printLastKDigits($a, $b, $k); // This code is contributed by ajit?>", "e": 8062, "s": 6648, "text": null }, { "code": "<script>// javascript code to find last k digits of a^b /* Iterative Function to calculate (x^y)%p in O(log y) */ function power(x , y , p) { var res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return parseInt( res); } // Method to print last k digits of a^b function printLastKDigits(a , b , k) { document.write(\"Last \" + k + \" digits of \" + a + \"^\" + b + \" = \"); // Generating 10^k var temp = 1; for (i = 1; i <= k; i++) temp *= 10; // Calling modular exponentiation temp = power(a, b, temp); // Printing leftmost zeros. Since (a^b)%k // can have digits less than k. In that // case we need to print zeros for (i = 0; i < k - temp.toString().length; i++) document.write(0); // If temp is not zero then print temp // If temp is zero then already printed if (temp != 0) document.write(temp); } // Driver Method var a = 11; var b = 3; var k = 2; printLastKDigits(a, b, k); // This code contributed by gauravrajput1</script>", "e": 9485, "s": 8062, "text": null }, { "code": null, "e": 9495, "s": 9485, "text": "Output: " }, { "code": null, "e": 9522, "s": 9495, "text": "Last 2 digits of 11^3 = 31" }, { "code": null, "e": 9996, "s": 9522, "text": "Time Complexity : O(log b) Space Complexity : O(1) This article is contributed by Pratik Chhajer. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 10002, "s": 9996, "text": "ukasp" }, { "code": null, "e": 10008, "s": 10002, "text": "jit_t" }, { "code": null, "e": 10020, "s": 10008, "text": "29AjayKumar" }, { "code": null, "e": 10034, "s": 10020, "text": "GauravRajput1" }, { "code": null, "e": 10047, "s": 10034, "text": "simmytarika5" }, { "code": null, "e": 10064, "s": 10047, "text": "khushboogoyal499" }, { "code": null, "e": 10080, "s": 10064, "text": "simranarora5sos" }, { "code": null, "e": 10094, "s": 10080, "text": "mitalibhola94" }, { "code": null, "e": 10113, "s": 10094, "text": "Modular Arithmetic" }, { "code": null, "e": 10127, "s": 10113, "text": "number-digits" }, { "code": null, "e": 10140, "s": 10127, "text": "Mathematical" }, { "code": null, "e": 10153, "s": 10140, "text": "Mathematical" }, { "code": null, "e": 10172, "s": 10153, "text": "Modular Arithmetic" } ]
Ruby | StringScanner scan function
12 Dec, 2019 StringScanner#scan() : scan() is a StringScanner class method which tries to match with pattern at the current position. Syntax: StringScanner.scan() Parameter: StringScanner values Return: matched string otherwise return false Example #1 : # Ruby code for StringScanner.scan() method # loading StringScannerrequire 'strscan' # declaring StringScanner c = StringScanner.new("Mon Sep 12 2018 14:39") # scan() methodc.scan(/\w+/) puts "String Scanner result of c.scan() form : #{c.pos()}\n\n" # scan() methodc.scan(/\s+/) puts "String Scanner result of c.scan() form : #{c.pos()}\n\n" Output : String Scanner result of c.scan() form : 3 String Scanner result of c.scan() form : 4 Example #2 : # Ruby code for StringScanner.scan() method # loading StringScannerrequire 'strscan' # declaring StringScanner c = StringScanner.new("h ello geeks") # scan() methodc.scan(/\w+/) puts "String Scanner result of c.scan() form : #{c.pos()}\n\n" # scan() methodc.scan(/\s+/) puts "String Scanner result of c.scan() form : #{c.pos()}\n\n" Output : String Scanner result of c.scan() form : 1 String Scanner result of c.scan() form : 2 Ruby String Scanner-class Ruby-Methods Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Make a Custom Array of Hashes in Ruby? Ruby | Array count() operation Ruby | Array slice() function Include v/s Extend in Ruby Global Variable in Ruby Ruby | Array select() function Ruby | Data Types Ruby | Case Statement Ruby | Enumerator each_with_index function Ruby | Hash delete() function
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Dec, 2019" }, { "code": null, "e": 149, "s": 28, "text": "StringScanner#scan() : scan() is a StringScanner class method which tries to match with pattern at the current position." }, { "code": null, "e": 178, "s": 149, "text": "Syntax: StringScanner.scan()" }, { "code": null, "e": 210, "s": 178, "text": "Parameter: StringScanner values" }, { "code": null, "e": 256, "s": 210, "text": "Return: matched string otherwise return false" }, { "code": null, "e": 269, "s": 256, "text": "Example #1 :" }, { "code": "# Ruby code for StringScanner.scan() method # loading StringScannerrequire 'strscan' # declaring StringScanner c = StringScanner.new(\"Mon Sep 12 2018 14:39\") # scan() methodc.scan(/\\w+/) puts \"String Scanner result of c.scan() form : #{c.pos()}\\n\\n\" # scan() methodc.scan(/\\s+/) puts \"String Scanner result of c.scan() form : #{c.pos()}\\n\\n\"", "e": 618, "s": 269, "text": null }, { "code": null, "e": 627, "s": 618, "text": "Output :" }, { "code": null, "e": 716, "s": 627, "text": "String Scanner result of c.scan() form : 3\n\nString Scanner result of c.scan() form : 4\n\n" }, { "code": null, "e": 729, "s": 716, "text": "Example #2 :" }, { "code": "# Ruby code for StringScanner.scan() method # loading StringScannerrequire 'strscan' # declaring StringScanner c = StringScanner.new(\"h ello geeks\") # scan() methodc.scan(/\\w+/) puts \"String Scanner result of c.scan() form : #{c.pos()}\\n\\n\" # scan() methodc.scan(/\\s+/) puts \"String Scanner result of c.scan() form : #{c.pos()}\\n\\n\"", "e": 1069, "s": 729, "text": null }, { "code": null, "e": 1078, "s": 1069, "text": "Output :" }, { "code": null, "e": 1166, "s": 1078, "text": "String Scanner result of c.scan() form : 1\n\nString Scanner result of c.scan() form : 2\n" }, { "code": null, "e": 1192, "s": 1166, "text": "Ruby String Scanner-class" }, { "code": null, "e": 1205, "s": 1192, "text": "Ruby-Methods" }, { "code": null, "e": 1210, "s": 1205, "text": "Ruby" }, { "code": null, "e": 1308, "s": 1210, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1354, "s": 1308, "text": "How to Make a Custom Array of Hashes in Ruby?" }, { "code": null, "e": 1385, "s": 1354, "text": "Ruby | Array count() operation" }, { "code": null, "e": 1415, "s": 1385, "text": "Ruby | Array slice() function" }, { "code": null, "e": 1442, "s": 1415, "text": "Include v/s Extend in Ruby" }, { "code": null, "e": 1466, "s": 1442, "text": "Global Variable in Ruby" }, { "code": null, "e": 1497, "s": 1466, "text": "Ruby | Array select() function" }, { "code": null, "e": 1515, "s": 1497, "text": "Ruby | Data Types" }, { "code": null, "e": 1537, "s": 1515, "text": "Ruby | Case Statement" }, { "code": null, "e": 1580, "s": 1537, "text": "Ruby | Enumerator each_with_index function" } ]
AWT ContainerEvent Class
The Class ContainerEvent represents that a container's contents changed because a component was added or removed. Following is the declaration for java.awt.event.ContainerEvent class: public class ContainerEvent extends ComponentEvent Following are the fields for java.awt.Component class: static int COMPONENT_ADDED -- This event indicates that a component was added to the container. static int COMPONENT_ADDED -- This event indicates that a component was added to the container. static int COMPONENT_REMOVED -- This event indicates that a component was removed from the container. static int COMPONENT_REMOVED -- This event indicates that a component was removed from the container. static int CONTAINER_FIRST -- The first number in the range of ids used for container events. static int CONTAINER_FIRST -- The first number in the range of ids used for container events. static int CONTAINER_LAST -- The last number in the range of ids used for container events. static int CONTAINER_LAST -- The last number in the range of ids used for container events. ContainerEvent(Component source, int id, Component child) Constructs a ContainerEvent object. This class inherits methods from the following classes: java.awt.ComponentEvent java.awt.ComponentEvent java.awt.AWTEvent java.awt.AWTEvent java.util.EventObject java.util.EventObject java.lang.Object java.lang.Object 13 Lectures 2 hours EduOLC Print Add Notes Bookmark this page
[ { "code": null, "e": 1861, "s": 1747, "text": "The Class ContainerEvent represents that a container's contents changed because a component was added or removed." }, { "code": null, "e": 1931, "s": 1861, "text": "Following is the declaration for java.awt.event.ContainerEvent class:" }, { "code": null, "e": 1985, "s": 1931, "text": "public class ContainerEvent\n extends ComponentEvent" }, { "code": null, "e": 2040, "s": 1985, "text": "Following are the fields for java.awt.Component class:" }, { "code": null, "e": 2137, "s": 2040, "text": "static int COMPONENT_ADDED -- This event indicates that a component was added to the container." }, { "code": null, "e": 2234, "s": 2137, "text": "static int COMPONENT_ADDED -- This event indicates that a component was added to the container." }, { "code": null, "e": 2337, "s": 2234, "text": "static int COMPONENT_REMOVED -- This event indicates that a component was removed from the container." }, { "code": null, "e": 2440, "s": 2337, "text": "static int COMPONENT_REMOVED -- This event indicates that a component was removed from the container." }, { "code": null, "e": 2535, "s": 2440, "text": "static int CONTAINER_FIRST -- The first number in the range of ids used for container events." }, { "code": null, "e": 2630, "s": 2535, "text": "static int CONTAINER_FIRST -- The first number in the range of ids used for container events." }, { "code": null, "e": 2723, "s": 2630, "text": "static int CONTAINER_LAST -- The last number in the range of ids used for container events." }, { "code": null, "e": 2816, "s": 2723, "text": "static int CONTAINER_LAST -- The last number in the range of ids used for container events." }, { "code": null, "e": 2875, "s": 2816, "text": "ContainerEvent(Component source, int id, Component child) " }, { "code": null, "e": 2911, "s": 2875, "text": "Constructs a ContainerEvent object." }, { "code": null, "e": 2967, "s": 2911, "text": "This class inherits methods from the following classes:" }, { "code": null, "e": 2991, "s": 2967, "text": "java.awt.ComponentEvent" }, { "code": null, "e": 3015, "s": 2991, "text": "java.awt.ComponentEvent" }, { "code": null, "e": 3033, "s": 3015, "text": "java.awt.AWTEvent" }, { "code": null, "e": 3051, "s": 3033, "text": "java.awt.AWTEvent" }, { "code": null, "e": 3073, "s": 3051, "text": "java.util.EventObject" }, { "code": null, "e": 3095, "s": 3073, "text": "java.util.EventObject" }, { "code": null, "e": 3112, "s": 3095, "text": "java.lang.Object" }, { "code": null, "e": 3129, "s": 3112, "text": "java.lang.Object" }, { "code": null, "e": 3162, "s": 3129, "text": "\n 13 Lectures \n 2 hours \n" }, { "code": null, "e": 3170, "s": 3162, "text": " EduOLC" }, { "code": null, "e": 3177, "s": 3170, "text": " Print" }, { "code": null, "e": 3188, "s": 3177, "text": " Add Notes" } ]
How to take backup of a single table in a MySQL database?
The backup of a table can be made with the help of backup table as well as mysqldump utility. The backup table concept was used in MySQL version 5.0 and its earlier version. Here, I am performing backup with the help of mysqldump. Firstly, we will open cmd with the help of shortcut key. The mysqldump will run at the cmd. Therefore, firstly open cmd with the help of shortcut key − windowskey+R; Here is the snapshot − Now, cmd will open − In this, the MySQL bin folder is present at the following location − C:\Program Files\MySQL\MySQL Server 8.0\bin Type the above path to reach the “bin” folder. Now, we are in “bin” folder. The query to take backup is as follows − C:\Program Files\MySQL\MySQL Server 8.0\bin>mysqldump -u Manish -p business student < E:\student.sql Enter password: *********** The following is the output − -- MySQL dump 10.13 Distrib 8.0.12, for Win64 (x86_64) -- -- Host: localhost Database: business -- ------------------------------------------------------ -- Server version 8.0.12 /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; SET NAMES utf8mb4 ; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `student` -- DROP TABLE IF EXISTS `student`; /*!40101 SET @saved_cs_client = @@character_set_client */; SET character_set_client = utf8mb4 ; CREATE TABLE `student` ( `id` int(11) DEFAULT NULL, `Name` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL, KEY `NameStuIndex` (`Name`), KEY `idIndex` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `student` -- LOCK TABLES `student` WRITE; /*!40000 ALTER TABLE `student` DISABLE KEYS */; INSERT into `student` VALUES (1,'John'),(2,'Bob'); /*!40000 ALTER TABLE `student` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2018-10-03 10:30:58
[ { "code": null, "e": 1236, "s": 1062, "text": "The backup of a table can be made with the help of backup table as well as mysqldump utility.\nThe backup table concept was used in MySQL version 5.0 and its earlier version." }, { "code": null, "e": 1445, "s": 1236, "text": "Here, I am performing backup with the help of mysqldump. Firstly, we will open cmd with the\nhelp of shortcut key. The mysqldump will run at the cmd. Therefore, firstly open cmd with the\nhelp of shortcut key −" }, { "code": null, "e": 1460, "s": 1445, "text": "windowskey+R;\n" }, { "code": null, "e": 1483, "s": 1460, "text": "Here is the snapshot −" }, { "code": null, "e": 1504, "s": 1483, "text": "Now, cmd will open −" }, { "code": null, "e": 1573, "s": 1504, "text": "In this, the MySQL bin folder is present at the following location −" }, { "code": null, "e": 1618, "s": 1573, "text": "C:\\Program Files\\MySQL\\MySQL Server 8.0\\bin\n" }, { "code": null, "e": 1665, "s": 1618, "text": "Type the above path to reach the “bin” folder." }, { "code": null, "e": 1735, "s": 1665, "text": "Now, we are in “bin” folder. The query to take backup is as follows −" }, { "code": null, "e": 1865, "s": 1735, "text": "C:\\Program Files\\MySQL\\MySQL Server 8.0\\bin>mysqldump -u Manish -p business student <\nE:\\student.sql\nEnter password: ***********\n" }, { "code": null, "e": 1895, "s": 1865, "text": "The following is the output −" }, { "code": null, "e": 3840, "s": 1895, "text": "-- MySQL dump 10.13 Distrib 8.0.12, for Win64 (x86_64)\n--\n-- Host: localhost Database: business\n-- ------------------------------------------------------\n-- Server version 8.0.12\n\n/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\n/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;\n/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;\nSET NAMES utf8mb4 ;\n/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;\n/*!40103 SET TIME_ZONE='+00:00' */;\n/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;\n/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS,\nFOREIGN_KEY_CHECKS=0 */;\n/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE,\nSQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;\n/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;\n--\n-- Table structure for table `student`\n--\n\nDROP TABLE IF EXISTS `student`;\n/*!40101 SET @saved_cs_client = @@character_set_client */;\nSET character_set_client = utf8mb4 ;\n\nCREATE TABLE `student` (\n `id` int(11) DEFAULT NULL,\n `Name` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,\n KEY `NameStuIndex` (`Name`),\n KEY `idIndex` (`id`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;\n/*!40101 SET character_set_client = @saved_cs_client */;\n--\n-- Dumping data for table `student`\n--\n\nLOCK TABLES `student` WRITE;\n/*!40000 ALTER TABLE `student` DISABLE KEYS */;\nINSERT into `student` VALUES (1,'John'),(2,'Bob');\n/*!40000 ALTER TABLE `student` ENABLE KEYS */;\nUNLOCK TABLES;\n/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;\n/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;\n/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;\n/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;\n/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;\n/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;\n/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;\n/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;\n-- Dump completed on 2018-10-03 10:30:58" } ]
How to insert into two tables using a single MySQL query?
You can use stored procedure to insert into two tables in a single query. Let us first create a table − mysql> create table DemoTable ( StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, StudentFirstName varchar(20) ); Query OK, 0 rows affected (0.56 sec) Here is the query to create second table − mysql> create table DemoTable2 ( ClientId int NOT NULL AUTO_INCREMENT PRIMARY KEY, ClientName varchar(20), ClientAge int ); Query OK, 0 rows affected (0.76 sec) Following is the query to create stored procedure to insert into two tables created above − mysql> DELIMITER // mysql> CREATE PROCEDURE insert_into_twoTables(name varchar(100),age int) BEGIN INSERT INTO DemoTable(StudentFirstName) VALUES(name); INSERT INTO DemoTable2(ClientName,ClientAge) VALUES(name,age); END // Query OK, 0 rows affected (0.14 sec) mysql> DELIMITER ; Now call the stored procedure with the help of CALL command − mysql> call insert_into_twoTables('Tom',38); Query OK, 1 row affected, 1 warning (0.41 sec) Check the record is inserted into both tables or not. The query to display all records from the first table is as follows − mysql> select * from DemoTable; This will produce the following output − +-----------+------------------+ | StudentId | StudentFirstName | +-----------+------------------+ | 1 | Tom | +-----------+------------------+ 1 row in set (0.00 sec) Following is the query to display all records from the second table − mysql> select * from DemoTable2; This will produce the following output − +----------+------------+-----------+ | ClientId | ClientName | ClientAge | +----------+------------+-----------+ | 1 | Tom | 38 | +----------+------------+-----------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1166, "s": 1062, "text": "You can use stored procedure to insert into two tables in a single query. Let us first create a table −" }, { "code": null, "e": 1324, "s": 1166, "text": "mysql> create table DemoTable\n(\n StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n StudentFirstName varchar(20)\n);\nQuery OK, 0 rows affected (0.56 sec)" }, { "code": null, "e": 1367, "s": 1324, "text": "Here is the query to create second table −" }, { "code": null, "e": 1537, "s": 1367, "text": "mysql> create table DemoTable2\n(\n ClientId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n ClientName varchar(20),\n ClientAge int\n);\nQuery OK, 0 rows affected (0.76 sec)" }, { "code": null, "e": 1629, "s": 1537, "text": "Following is the query to create stored procedure to insert into two tables created above −" }, { "code": null, "e": 1950, "s": 1629, "text": "mysql> DELIMITER //\n mysql> CREATE PROCEDURE insert_into_twoTables(name varchar(100),age int)\n BEGIN\n INSERT INTO DemoTable(StudentFirstName) VALUES(name);\n INSERT INTO DemoTable2(ClientName,ClientAge) VALUES(name,age);\n END\n //\n Query OK, 0 rows affected (0.14 sec)\nmysql> DELIMITER ;" }, { "code": null, "e": 2012, "s": 1950, "text": "Now call the stored procedure with the help of CALL command −" }, { "code": null, "e": 2104, "s": 2012, "text": "mysql> call insert_into_twoTables('Tom',38);\nQuery OK, 1 row affected, 1 warning (0.41 sec)" }, { "code": null, "e": 2158, "s": 2104, "text": "Check the record is inserted into both tables or not." }, { "code": null, "e": 2228, "s": 2158, "text": "The query to display all records from the first table is as follows −" }, { "code": null, "e": 2260, "s": 2228, "text": "mysql> select * from DemoTable;" }, { "code": null, "e": 2301, "s": 2260, "text": "This will produce the following output −" }, { "code": null, "e": 2490, "s": 2301, "text": "+-----------+------------------+\n| StudentId | StudentFirstName |\n+-----------+------------------+\n| 1 | Tom |\n+-----------+------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 2560, "s": 2490, "text": "Following is the query to display all records from the second table −" }, { "code": null, "e": 2593, "s": 2560, "text": "mysql> select * from DemoTable2;" }, { "code": null, "e": 2634, "s": 2593, "text": "This will produce the following output −" }, { "code": null, "e": 2848, "s": 2634, "text": "+----------+------------+-----------+\n| ClientId | ClientName | ClientAge |\n+----------+------------+-----------+\n| 1 | Tom | 38 |\n+----------+------------+-----------+\n1 row in set (0.00 sec)" } ]
How to read a simple text file in Android App?
This example demonstrates how do I read a simple text file in the android app. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Create a new Android Resource directory (raw.xml) and add a text file in the res/raw Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="8dp" tools:context=".MainActivity"> <Button android:id="@+id/button" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="70dp" android:onClick="ReadTextFile" android:text="Read Text File" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:text="Read text File in Android" android:textAlignment="center" android:textSize="18sp" android:textStyle="bold" /> <TextView android:id="@+id/textView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/button" android:layout_marginTop="10dp" android:textSize="20sp" android:textStyle="bold" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; import android.widget.Toast; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class MainActivity extends AppCompatActivity { TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.textView); } public void ReadTextFile(View view) throws IOException { String string = ""; StringBuilder stringBuilder = new StringBuilder(); InputStream is = this.getResources().openRawResource(R.raw.sample); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); while (true) { try { if ((string = reader.readLine()) == null) break; } catch (IOException e) { e.printStackTrace(); } stringBuilder.append(string).append("\n"); textView.setText(stringBuilder); } is.close(); Toast.makeText(getBaseContext(), stringBuilder.toString(), Toast.LENGTH_LONG).show(); } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − Click here to download the project code.
[ { "code": null, "e": 1141, "s": 1062, "text": "This example demonstrates how do I read a simple text file in the android app." }, { "code": null, "e": 1270, "s": 1141, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1355, "s": 1270, "text": "Create a new Android Resource directory (raw.xml) and add a text file in the res/raw" }, { "code": null, "e": 1420, "s": 1355, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2583, "s": 1420, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout\nxmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"8dp\"\n tools:context=\".MainActivity\">\n <Button\n android:id=\"@+id/button\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"70dp\"\n android:onClick=\"ReadTextFile\"\n android:text=\"Read Text File\" />\n <TextView\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_marginTop=\"20dp\"\n android:text=\"Read text File in Android\"\n android:textAlignment=\"center\"\n android:textSize=\"18sp\"\n android:textStyle=\"bold\" />\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@id/button\"\n android:layout_marginTop=\"10dp\"\n android:textSize=\"20sp\"\n android:textStyle=\"bold\" />\n</RelativeLayout>" }, { "code": null, "e": 2640, "s": 2583, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3911, "s": 2640, "text": "import androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.TextView;\nimport android.widget.Toast;\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\npublic class MainActivity extends AppCompatActivity {\n TextView textView;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.textView);\n }\n public void ReadTextFile(View view) throws IOException {\n String string = \"\";\n StringBuilder stringBuilder = new StringBuilder();\n InputStream is = this.getResources().openRawResource(R.raw.sample);\n BufferedReader reader = new BufferedReader(new InputStreamReader(is));\n while (true) {\n try {\n if ((string = reader.readLine()) == null) break;\n }\n catch (IOException e) {\n e.printStackTrace();\n }\n stringBuilder.append(string).append(\"\\n\");\n textView.setText(stringBuilder);\n }\n is.close();\n Toast.makeText(getBaseContext(), stringBuilder.toString(),\n Toast.LENGTH_LONG).show();\n }\n}" }, { "code": null, "e": 3966, "s": 3911, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 4636, "s": 3966, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 4987, "s": 4636, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 5028, "s": 4987, "text": "Click here to download the project code." } ]
HTML - <fieldset> Tag
The HTML <fieldset> tag is used for grouping related form elements. By using the fieldset tag and the legend tag, you can make your forms much easier to understand for your users. <!DOCTYPE html> <html> <head> <title>HTML fieldset Tag</title> </head> <body> <form> <fieldset> <legend>Details</legend> Student Name: <input type = "text"><br /> MCA Subjects:<input type = "text"><br /> Course Link:<input type = "url" name = "websitelink"> </fieldset> </form> </body> </html> This will produce the following result − This tag supports all the global attributes described in HTML Attribute Reference The HTML <fieldset> tag also supports the following additional attributes − This tag supports all the event attributes described in HTML Events Reference 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": 2554, "s": 2374, "text": "The HTML <fieldset> tag is used for grouping related form elements. By using the fieldset tag and the legend tag, you can make your forms much easier to understand for your users." }, { "code": null, "e": 2967, "s": 2554, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML fieldset Tag</title>\n </head>\n\n <body>\n <form>\n \n <fieldset>\n <legend>Details</legend>\n Student Name: <input type = \"text\"><br />\n MCA Subjects:<input type = \"text\"><br />\n Course Link:<input type = \"url\" name = \"websitelink\">\n </fieldset>\n \n </form>\n </body>\n\n</html>" }, { "code": null, "e": 3008, "s": 2967, "text": "This will produce the following result −" }, { "code": null, "e": 3090, "s": 3008, "text": "This tag supports all the global attributes described in HTML Attribute Reference" }, { "code": null, "e": 3167, "s": 3090, "text": "The HTML <fieldset> tag also supports the following additional attributes −" }, { "code": null, "e": 3245, "s": 3167, "text": "This tag supports all the event attributes described in HTML Events Reference" }, { "code": null, "e": 3278, "s": 3245, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 3292, "s": 3278, "text": " Anadi Sharma" }, { "code": null, "e": 3327, "s": 3292, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3341, "s": 3327, "text": " Anadi Sharma" }, { "code": null, "e": 3376, "s": 3341, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3393, "s": 3376, "text": " Frahaan Hussain" }, { "code": null, "e": 3428, "s": 3393, "text": "\n 57 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3459, "s": 3428, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3492, "s": 3459, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 3523, "s": 3492, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3558, "s": 3523, "text": "\n 45 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3589, "s": 3558, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3596, "s": 3589, "text": " Print" }, { "code": null, "e": 3607, "s": 3596, "text": " Add Notes" } ]
DateTime.ToLongDateString() Method in C#
The DateTime.ToLongDateString() method in C# is used to convert the value of the current DateTime object to its equivalent long date string representation. Following is the syntax − public string ToLongDateString (); Let us now see an example to implement the DateTime.ToLongDateString() method − using System; public class Demo { public static void Main() { DateTime d = new DateTime(2019, 10, 11, 9, 10, 45); Console.WriteLine("Date = {0}", d); string str = d.ToLongDateString(); Console.WriteLine("Long date string representation = {0}", str); } } This will produce the following output − Date = 10/11/2019 9:10:45 AM Long date string representation = Friday, October 11, 2019 Let us now see another example to implement the DateTime.ToLongDateString() method − using System; using System.Globalization; public class Demo { public static void Main() { DateTime d = DateTime.Now; Console.WriteLine("Date = {0}", d); Console.WriteLine("Current culture = "+CultureInfo.CurrentCulture.Name); var pattern = CultureInfo.CurrentCulture.DateTimeFormat; string str = d.ToLongDateString(); Console.WriteLine("Long date string = {0}", pattern.LongDatePattern); Console.WriteLine("Long date string representation = {0}", str); } } This will produce the following output − Date = 10/16/2019 8:39:08 AM Current culture = en-US Long date string = dddd, MMMM d, yyyy Long date string representation = Wednesday, October 16, 2019
[ { "code": null, "e": 1218, "s": 1062, "text": "The DateTime.ToLongDateString() method in C# is used to convert the value of the current DateTime object to its equivalent long date string representation." }, { "code": null, "e": 1244, "s": 1218, "text": "Following is the syntax −" }, { "code": null, "e": 1279, "s": 1244, "text": "public string ToLongDateString ();" }, { "code": null, "e": 1359, "s": 1279, "text": "Let us now see an example to implement the DateTime.ToLongDateString() method −" }, { "code": null, "e": 1643, "s": 1359, "text": "using System;\npublic class Demo {\n public static void Main() {\n DateTime d = new DateTime(2019, 10, 11, 9, 10, 45);\n Console.WriteLine(\"Date = {0}\", d);\n string str = d.ToLongDateString();\n Console.WriteLine(\"Long date string representation = {0}\", str);\n }\n}" }, { "code": null, "e": 1684, "s": 1643, "text": "This will produce the following output −" }, { "code": null, "e": 1772, "s": 1684, "text": "Date = 10/11/2019 9:10:45 AM\nLong date string representation = Friday, October 11, 2019" }, { "code": null, "e": 1857, "s": 1772, "text": "Let us now see another example to implement the DateTime.ToLongDateString() method −" }, { "code": null, "e": 2362, "s": 1857, "text": "using System;\nusing System.Globalization;\npublic class Demo {\n public static void Main() {\n DateTime d = DateTime.Now;\n Console.WriteLine(\"Date = {0}\", d);\n Console.WriteLine(\"Current culture = \"+CultureInfo.CurrentCulture.Name);\n var pattern = CultureInfo.CurrentCulture.DateTimeFormat;\n string str = d.ToLongDateString();\n Console.WriteLine(\"Long date string = {0}\", pattern.LongDatePattern);\n Console.WriteLine(\"Long date string representation = {0}\", str);\n }\n}" }, { "code": null, "e": 2403, "s": 2362, "text": "This will produce the following output −" }, { "code": null, "e": 2556, "s": 2403, "text": "Date = 10/16/2019 8:39:08 AM\nCurrent culture = en-US\nLong date string = dddd, MMMM d, yyyy\nLong date string representation = Wednesday, October 16, 2019" } ]
How to setup Tailwind CSS in AngularJS ? - GeeksforGeeks
01 Jul, 2021 What is Tailwind CSS? According to the official documentation, Tailwind CSS is a utility-first CSS framework for rapidly building custom user interfaces. It is a cool way to write inline styling and achieve an awesome interface without writing a single line of your own CSS. What is Angular? Angular is a platform and framework for building single-page client applications using HTML and TypeScript. Angular is written in TypeScript. It implements core and optional functionality as a set of TypeScript libraries that you import into your applications. So lets start with creating a new angular project and setup Tailwind CSS in the angular project. Setting up new Angular Project: Open CMD (Window) or Terminal (Linux) and write command. ng new project-name After running the above command, it asks some question as shown below, related to CSS which is basically the CSS type you want to use in your angular project. Let Select CSS for this project. It also ask for routing let enable it by saying yes. Let them finish the above process. Once process is completed, there is project folder. Get into the folder using change directory command of CMD or Terminal and run following command. ng serve --open It will open the default page of angular in the browser. Angular setup is done let move to install the Tailwind CSS in the angular. Installing Tailwind CSS in the Angular Project: There are 2 ways to add tailwind CSS in the Angular Project. Using CDN Using PostCSS and command line configuration Using CDN: Open the project in your favourite Code Editor. Browse the index.html of angular project. Just paste the below line in the head section. <link href=”https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css” rel=”stylesheet”> It will include all the libraries of the tailwind in the project using the internet. It is an easy way to includes the tailwind. Note: It is require internet. If internet is not available then it will not work. Using PostCSS: Open the project directory in the cmd or terminal and run following command. npm install tailwindcss postcss autoprefixer Above command install require library for tailwind to run. Let’s config the tailwind css and postcss. For that we can create a file with name of tailwind.config.js and postcss.config.js in the project file. tailwind.config.js module.exports = { purge: [], darkMode: false, // or 'media' or 'class' theme: { extend: {}, }, variants: { extend: {}, }, plugins: [], } postcss.config.js module.exports = { plugins: { tailwindcss: {}, autoprefixer: {}, }, }; Now tailwind CSS is ready to use in your Angular project and it is successfully setup into the project. Now you can use tailwind inline CSS and to make more hand dirty you can refer to the tailwind website. Ref: https://tailwindcss.com/ AngularJS-Questions Picked Tailwind CSS AngularJS CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 10 Angular Libraries For Web Developers How to make a Bootstrap Modal Popup in Angular 9/8 ? Angular 10 (blur) Event Angular PrimeNG Dropdown Component How to use <mat-chip-list> and <mat-chip> in Angular Material ? 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? How to update Node.js and NPM to next version ? CSS to put icon inside an input element in a form
[ { "code": null, "e": 25134, "s": 25106, "text": "\n01 Jul, 2021" }, { "code": null, "e": 25156, "s": 25134, "text": "What is Tailwind CSS?" }, { "code": null, "e": 25409, "s": 25156, "text": "According to the official documentation, Tailwind CSS is a utility-first CSS framework for rapidly building custom user interfaces. It is a cool way to write inline styling and achieve an awesome interface without writing a single line of your own CSS." }, { "code": null, "e": 25426, "s": 25409, "text": "What is Angular?" }, { "code": null, "e": 25687, "s": 25426, "text": "Angular is a platform and framework for building single-page client applications using HTML and TypeScript. Angular is written in TypeScript. It implements core and optional functionality as a set of TypeScript libraries that you import into your applications." }, { "code": null, "e": 25784, "s": 25687, "text": "So lets start with creating a new angular project and setup Tailwind CSS in the angular project." }, { "code": null, "e": 25816, "s": 25784, "text": "Setting up new Angular Project:" }, { "code": null, "e": 25873, "s": 25816, "text": "Open CMD (Window) or Terminal (Linux) and write command." }, { "code": null, "e": 25893, "s": 25873, "text": "ng new project-name" }, { "code": null, "e": 26085, "s": 25893, "text": "After running the above command, it asks some question as shown below, related to CSS which is basically the CSS type you want to use in your angular project. Let Select CSS for this project." }, { "code": null, "e": 26138, "s": 26085, "text": "It also ask for routing let enable it by saying yes." }, { "code": null, "e": 26173, "s": 26138, "text": "Let them finish the above process." }, { "code": null, "e": 26322, "s": 26173, "text": "Once process is completed, there is project folder. Get into the folder using change directory command of CMD or Terminal and run following command." }, { "code": null, "e": 26338, "s": 26322, "text": "ng serve --open" }, { "code": null, "e": 26395, "s": 26338, "text": "It will open the default page of angular in the browser." }, { "code": null, "e": 26470, "s": 26395, "text": "Angular setup is done let move to install the Tailwind CSS in the angular." }, { "code": null, "e": 26579, "s": 26470, "text": "Installing Tailwind CSS in the Angular Project: There are 2 ways to add tailwind CSS in the Angular Project." }, { "code": null, "e": 26589, "s": 26579, "text": "Using CDN" }, { "code": null, "e": 26634, "s": 26589, "text": "Using PostCSS and command line configuration" }, { "code": null, "e": 26645, "s": 26634, "text": "Using CDN:" }, { "code": null, "e": 26693, "s": 26645, "text": "Open the project in your favourite Code Editor." }, { "code": null, "e": 26735, "s": 26693, "text": "Browse the index.html of angular project." }, { "code": null, "e": 26782, "s": 26735, "text": "Just paste the below line in the head section." }, { "code": null, "e": 26868, "s": 26782, "text": "<link href=”https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css” rel=”stylesheet”>" }, { "code": null, "e": 26997, "s": 26868, "text": "It will include all the libraries of the tailwind in the project using the internet. It is an easy way to includes the tailwind." }, { "code": null, "e": 27079, "s": 26997, "text": "Note: It is require internet. If internet is not available then it will not work." }, { "code": null, "e": 27094, "s": 27079, "text": "Using PostCSS:" }, { "code": null, "e": 27171, "s": 27094, "text": "Open the project directory in the cmd or terminal and run following command." }, { "code": null, "e": 27216, "s": 27171, "text": "npm install tailwindcss postcss autoprefixer" }, { "code": null, "e": 27423, "s": 27216, "text": "Above command install require library for tailwind to run. Let’s config the tailwind css and postcss. For that we can create a file with name of tailwind.config.js and postcss.config.js in the project file." }, { "code": null, "e": 27442, "s": 27423, "text": "tailwind.config.js" }, { "code": null, "e": 27625, "s": 27442, "text": "module.exports = {\n purge: [],\n darkMode: false, // or 'media' or 'class'\n theme: {\n extend: {},\n },\n variants: {\n extend: {},\n },\n plugins: [],\n}\n" }, { "code": null, "e": 27643, "s": 27625, "text": "postcss.config.js" }, { "code": null, "e": 27739, "s": 27643, "text": "module.exports = {\n plugins: {\n tailwindcss: {},\n autoprefixer: {},\n },\n};\n" }, { "code": null, "e": 27843, "s": 27739, "text": "Now tailwind CSS is ready to use in your Angular project and it is successfully setup into the project." }, { "code": null, "e": 27946, "s": 27843, "text": "Now you can use tailwind inline CSS and to make more hand dirty you can refer to the tailwind website." }, { "code": null, "e": 27977, "s": 27946, "text": "Ref: https://tailwindcss.com/ " }, { "code": null, "e": 27997, "s": 27977, "text": "AngularJS-Questions" }, { "code": null, "e": 28004, "s": 27997, "text": "Picked" }, { "code": null, "e": 28017, "s": 28004, "text": "Tailwind CSS" }, { "code": null, "e": 28027, "s": 28017, "text": "AngularJS" }, { "code": null, "e": 28031, "s": 28027, "text": "CSS" }, { "code": null, "e": 28048, "s": 28031, "text": "Web Technologies" }, { "code": null, "e": 28146, "s": 28048, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28190, "s": 28146, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 28243, "s": 28190, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 28267, "s": 28243, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 28302, "s": 28267, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 28366, "s": 28302, "text": "How to use <mat-chip-list> and <mat-chip> in Angular Material ?" }, { "code": null, "e": 28428, "s": 28366, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28478, "s": 28428, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 28536, "s": 28478, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 28584, "s": 28536, "text": "How to update Node.js and NPM to next version ?" } ]
PostgreSQL - TRUNCATE TABLE Command
The PostgreSQL TRUNCATE TABLE command is used to delete complete data from an existing table. You can also use DROP TABLE command to delete complete table but it would remove complete table structure from the database and you would need to re-create this table once again if you wish to store some data. It has the same effect as DELETE on each table, but since it does not actually scan the tables, it is faster. Furthermore, it reclaims disk space immediately, rather than requiring a subsequent VACUUM operation. This is most useful on large tables. The basic syntax of TRUNCATE TABLE is as follows − TRUNCATE TABLE table_name; Consider the COMPANY table has the following records − id | name | age | address | salary ----+-------+-----+------------+-------- 1 | Paul | 32 | California | 20000 2 | Allen | 25 | Texas | 15000 3 | Teddy | 23 | Norway | 20000 4 | Mark | 25 | Rich-Mond | 65000 5 | David | 27 | Texas | 85000 6 | Kim | 22 | South-Hall | 45000 7 | James | 24 | Houston | 10000 (7 rows) The following is the example to truncate − testdb=# TRUNCATE TABLE COMPANY; Now, COMPANY table is truncated and the following would be the output of SELECT statement − testdb=# SELECT * FROM CUSTOMERS; id | name | age | address | salary ----+------+-----+---------+-------- (0 rows) 23 Lectures 1.5 hours John Elder 49 Lectures 3.5 hours Niyazi Erdogan 126 Lectures 10.5 hours Abhishek And Pukhraj 35 Lectures 5 hours Karthikeya T 5 Lectures 51 mins Vinay Kumar 5 Lectures 52 mins Vinay Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 3129, "s": 2825, "text": "The PostgreSQL TRUNCATE TABLE command is used to delete complete data from an existing table. You can also use DROP TABLE command to delete complete table but it would remove complete table structure from the database and you would need to re-create this table once again if you wish to store some data." }, { "code": null, "e": 3378, "s": 3129, "text": "It has the same effect as DELETE on each table, but since it does not actually scan the tables, it is faster. Furthermore, it reclaims disk space immediately, rather than requiring a subsequent VACUUM operation. This is most useful on large tables." }, { "code": null, "e": 3429, "s": 3378, "text": "The basic syntax of TRUNCATE TABLE is as follows −" }, { "code": null, "e": 3458, "s": 3429, "text": "TRUNCATE TABLE table_name;\n" }, { "code": null, "e": 3513, "s": 3458, "text": "Consider the COMPANY table has the following records −" }, { "code": null, "e": 3883, "s": 3513, "text": " id | name | age | address | salary\n----+-------+-----+------------+--------\n 1 | Paul | 32 | California | 20000\n 2 | Allen | 25 | Texas | 15000\n 3 | Teddy | 23 | Norway | 20000\n 4 | Mark | 25 | Rich-Mond | 65000\n 5 | David | 27 | Texas | 85000\n 6 | Kim | 22 | South-Hall | 45000\n 7 | James | 24 | Houston | 10000\n(7 rows)" }, { "code": null, "e": 3926, "s": 3883, "text": "The following is the example to truncate −" }, { "code": null, "e": 3959, "s": 3926, "text": "testdb=# TRUNCATE TABLE COMPANY;" }, { "code": null, "e": 4051, "s": 3959, "text": "Now, COMPANY table is truncated and the following would be the output of SELECT statement −" }, { "code": null, "e": 4167, "s": 4051, "text": "testdb=# SELECT * FROM CUSTOMERS;\n id | name | age | address | salary\n----+------+-----+---------+--------\n(0 rows)" }, { "code": null, "e": 4202, "s": 4167, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4214, "s": 4202, "text": " John Elder" }, { "code": null, "e": 4249, "s": 4214, "text": "\n 49 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4265, "s": 4249, "text": " Niyazi Erdogan" }, { "code": null, "e": 4302, "s": 4265, "text": "\n 126 Lectures \n 10.5 hours \n" }, { "code": null, "e": 4324, "s": 4302, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 4357, "s": 4324, "text": "\n 35 Lectures \n 5 hours \n" }, { "code": null, "e": 4371, "s": 4357, "text": " Karthikeya T" }, { "code": null, "e": 4402, "s": 4371, "text": "\n 5 Lectures \n 51 mins\n" }, { "code": null, "e": 4415, "s": 4402, "text": " Vinay Kumar" }, { "code": null, "e": 4446, "s": 4415, "text": "\n 5 Lectures \n 52 mins\n" }, { "code": null, "e": 4459, "s": 4446, "text": " Vinay Kumar" }, { "code": null, "e": 4466, "s": 4459, "text": " Print" }, { "code": null, "e": 4477, "s": 4466, "text": " Add Notes" } ]
Applications of tree data structure - GeeksforGeeks
17 Dec, 2021 Why Tree? Unlike Array and Linked List, which are linear data structures, tree is hierarchical (or non-linear) data structure. One reason to use trees might be because you want to store information that naturally forms a hierarchy. For example, the file system on a computer: file system ———– One reason to use trees might be because you want to store information that naturally forms a hierarchy. For example, the file system on a computer: file system ———– file system ———– / <-- root / \ ... home / \ ugrad course / / | \ ... cs101 cs112 cs113 If we organize keys in form of a tree (with some ordering e.g., BST), we can search for a given key in moderate time (quicker than Linked List and slower than arrays). Self-balancing search trees like AVL and Red-Black trees guarantee an upper bound of O(Logn) for search.We can insert/delete keys in moderate time (quicker than Arrays and slower than Unordered Linked Lists). Self-balancing search trees like AVL and Red-Black trees guarantee an upper bound of O(Logn) for insertion/deletion.Like Linked Lists and unlike Arrays, Pointer implementation of trees don’t have an upper limit on number of nodes as nodes are linked using pointers. If we organize keys in form of a tree (with some ordering e.g., BST), we can search for a given key in moderate time (quicker than Linked List and slower than arrays). Self-balancing search trees like AVL and Red-Black trees guarantee an upper bound of O(Logn) for search. We can insert/delete keys in moderate time (quicker than Arrays and slower than Unordered Linked Lists). Self-balancing search trees like AVL and Red-Black trees guarantee an upper bound of O(Logn) for insertion/deletion. Like Linked Lists and unlike Arrays, Pointer implementation of trees don’t have an upper limit on number of nodes as nodes are linked using pointers. Other Applications : Store hierarchical data, like folder structure, organization structure, XML/HTML data.Binary Search Tree is a tree that allows fast search, insert, delete on a sorted data. It also allows finding closest itemHeap is a tree data structure which is implemented using arrays and used to implement priority queues.B-Tree and B+ Tree : They are used to implement indexing in databases.Syntax Tree: Scanning, parsing , generation of code and evaluation of arithmetic expressions in Compiler design.K-D Tree: A space partitioning tree used to organize points in K dimensional space.Trie : Used to implement dictionaries with prefix lookup.Suffix Tree : For quick pattern searching in a fixed text.Spanning Trees and shortest path trees are used in routers and bridges respectively in computer networksAs a workflow for compositing digital images for visual effects.Decision trees.Organization chart of a large organization. Store hierarchical data, like folder structure, organization structure, XML/HTML data. Binary Search Tree is a tree that allows fast search, insert, delete on a sorted data. It also allows finding closest item Heap is a tree data structure which is implemented using arrays and used to implement priority queues. B-Tree and B+ Tree : They are used to implement indexing in databases. Syntax Tree: Scanning, parsing , generation of code and evaluation of arithmetic expressions in Compiler design. K-D Tree: A space partitioning tree used to organize points in K dimensional space. Trie : Used to implement dictionaries with prefix lookup. Suffix Tree : For quick pattern searching in a fixed text. Spanning Trees and shortest path trees are used in routers and bridges respectively in computer networks As a workflow for compositing digital images for visual effects. Decision trees. Organization chart of a large organization. References: http://www.cs.bu.edu/teaching/c/tree/binary/ http://en.wikipedia.org/wiki/Tree_%28data_structure%29#Common_uses Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. itskawal2000 Self-Balancing-BST Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) Level Order Binary Tree Traversal AVL Tree | Set 1 (Insertion) Inorder Tree Traversal without Recursion Write a Program to Find the Maximum Depth or Height of a Tree Binary Tree | Set 3 (Types of Binary Tree) Binary Tree | Set 2 (Properties) Decision Tree A program to check if a binary tree is BST or not
[ { "code": null, "e": 35847, "s": 35819, "text": "\n17 Dec, 2021" }, { "code": null, "e": 35975, "s": 35847, "text": "Why Tree? Unlike Array and Linked List, which are linear data structures, tree is hierarchical (or non-linear) data structure. " }, { "code": null, "e": 36143, "s": 35975, "text": "One reason to use trees might be because you want to store information that naturally forms a hierarchy. For example, the file system on a computer: file system ———– " }, { "code": null, "e": 36311, "s": 36143, "text": "One reason to use trees might be because you want to store information that naturally forms a hierarchy. For example, the file system on a computer: file system ———– " }, { "code": null, "e": 36330, "s": 36311, "text": "file system ———– " }, { "code": null, "e": 36475, "s": 36330, "text": " / <-- root\n / \\\n... home\n / \\\n ugrad course\n / / | \\\n ... cs101 cs112 cs113" }, { "code": null, "e": 37118, "s": 36475, "text": "If we organize keys in form of a tree (with some ordering e.g., BST), we can search for a given key in moderate time (quicker than Linked List and slower than arrays). Self-balancing search trees like AVL and Red-Black trees guarantee an upper bound of O(Logn) for search.We can insert/delete keys in moderate time (quicker than Arrays and slower than Unordered Linked Lists). Self-balancing search trees like AVL and Red-Black trees guarantee an upper bound of O(Logn) for insertion/deletion.Like Linked Lists and unlike Arrays, Pointer implementation of trees don’t have an upper limit on number of nodes as nodes are linked using pointers." }, { "code": null, "e": 37391, "s": 37118, "text": "If we organize keys in form of a tree (with some ordering e.g., BST), we can search for a given key in moderate time (quicker than Linked List and slower than arrays). Self-balancing search trees like AVL and Red-Black trees guarantee an upper bound of O(Logn) for search." }, { "code": null, "e": 37613, "s": 37391, "text": "We can insert/delete keys in moderate time (quicker than Arrays and slower than Unordered Linked Lists). Self-balancing search trees like AVL and Red-Black trees guarantee an upper bound of O(Logn) for insertion/deletion." }, { "code": null, "e": 37763, "s": 37613, "text": "Like Linked Lists and unlike Arrays, Pointer implementation of trees don’t have an upper limit on number of nodes as nodes are linked using pointers." }, { "code": null, "e": 37786, "s": 37763, "text": "Other Applications : " }, { "code": null, "e": 38704, "s": 37786, "text": "Store hierarchical data, like folder structure, organization structure, XML/HTML data.Binary Search Tree is a tree that allows fast search, insert, delete on a sorted data. It also allows finding closest itemHeap is a tree data structure which is implemented using arrays and used to implement priority queues.B-Tree and B+ Tree : They are used to implement indexing in databases.Syntax Tree: Scanning, parsing , generation of code and evaluation of arithmetic expressions in Compiler design.K-D Tree: A space partitioning tree used to organize points in K dimensional space.Trie : Used to implement dictionaries with prefix lookup.Suffix Tree : For quick pattern searching in a fixed text.Spanning Trees and shortest path trees are used in routers and bridges respectively in computer networksAs a workflow for compositing digital images for visual effects.Decision trees.Organization chart of a large organization." }, { "code": null, "e": 38791, "s": 38704, "text": "Store hierarchical data, like folder structure, organization structure, XML/HTML data." }, { "code": null, "e": 38914, "s": 38791, "text": "Binary Search Tree is a tree that allows fast search, insert, delete on a sorted data. It also allows finding closest item" }, { "code": null, "e": 39017, "s": 38914, "text": "Heap is a tree data structure which is implemented using arrays and used to implement priority queues." }, { "code": null, "e": 39088, "s": 39017, "text": "B-Tree and B+ Tree : They are used to implement indexing in databases." }, { "code": null, "e": 39202, "s": 39088, "text": "Syntax Tree: Scanning, parsing , generation of code and evaluation of arithmetic expressions in Compiler design." }, { "code": null, "e": 39286, "s": 39202, "text": "K-D Tree: A space partitioning tree used to organize points in K dimensional space." }, { "code": null, "e": 39344, "s": 39286, "text": "Trie : Used to implement dictionaries with prefix lookup." }, { "code": null, "e": 39403, "s": 39344, "text": "Suffix Tree : For quick pattern searching in a fixed text." }, { "code": null, "e": 39508, "s": 39403, "text": "Spanning Trees and shortest path trees are used in routers and bridges respectively in computer networks" }, { "code": null, "e": 39573, "s": 39508, "text": "As a workflow for compositing digital images for visual effects." }, { "code": null, "e": 39589, "s": 39573, "text": "Decision trees." }, { "code": null, "e": 39633, "s": 39589, "text": "Organization chart of a large organization." }, { "code": null, "e": 39758, "s": 39633, "text": "References: http://www.cs.bu.edu/teaching/c/tree/binary/ http://en.wikipedia.org/wiki/Tree_%28data_structure%29#Common_uses " }, { "code": null, "e": 39884, "s": 39758, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 39899, "s": 39886, "text": "itskawal2000" }, { "code": null, "e": 39918, "s": 39899, "text": "Self-Balancing-BST" }, { "code": null, "e": 39923, "s": 39918, "text": "Tree" }, { "code": null, "e": 39928, "s": 39923, "text": "Tree" }, { "code": null, "e": 40026, "s": 39928, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40076, "s": 40026, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 40111, "s": 40076, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 40145, "s": 40111, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 40174, "s": 40145, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 40215, "s": 40174, "text": "Inorder Tree Traversal without Recursion" }, { "code": null, "e": 40277, "s": 40215, "text": "Write a Program to Find the Maximum Depth or Height of a Tree" }, { "code": null, "e": 40320, "s": 40277, "text": "Binary Tree | Set 3 (Types of Binary Tree)" }, { "code": null, "e": 40353, "s": 40320, "text": "Binary Tree | Set 2 (Properties)" }, { "code": null, "e": 40367, "s": 40353, "text": "Decision Tree" } ]
ANSYS in a Python Web App, Part 1: Post Processing with PyDPF | by Steve Kiefer | Towards Data Science
ANSYS recently announced it is supporting an open source project: PyAnsys. PyAnsys is split into multiple packages: PyMAPDL for interacting with an instance of an Ansys multiphysics simulation and equation solver and PyDPF-Core (& its simplified sibling PyDPF-Post) for post-processing Ansys results files. This is really intriguing to me as a structural analyst that uses ANSYS and Python pretty much daily. I have also used Plotly’s Dash framework to build fairly simple web-apps for post processing data and solving various equations or systems. After playing around with PyANSYS in a Jupyter notebook for a while I decided to see if I could mash together a web-app that uses PyANSYS as a backend for a purpose-built analysis tool that a non-analyst could use and get insight (or at least build something that heads in that direction). PyANSYS is split into several packages. PyMAPDL is focused on communicating with a running MAPDL instance (local or remote) which pulls a license while running. PyDPF-Core and PyDPF-Post are focused on post-processing already-solved files (eg *.rst). These libraries do require Ansys to be installed. In this article I’ll walk through using PyDPF, Dash & Dash-VTK to build a web app that loads and plots results from a few PyDPF examples. You can see the full files (notebook and Dash app) in this GitHub repository. Plotly’s Dash open source framework is described as a framework that can be used to build a fully functioning web-application with only python. I really like it for building applications I expect other users (besides myself) will use. While its grown a lot since its debut, you can read the 2017 announcement essay to get more context to what Dash is all about: medium.com Years ago I built a few VTK-based desktop applications for post-processing FEA results. So when I learned about Dash-VTK I was excited to try and port some of that into a web-app. I put together an example with a writeup you can check out here: towardsdatascience.com With Dash we are able to build an application with a simple and clean user interface and thanks to Dash-VTK view 3D mesh and associated results. If you are using Ansys to solve your analysis problems you would need to export the results from Ansys into some fixed (likely text) format so they could be read in by the web-app. You would have to export the model (mesh) as well as the results from Ansys and handle all the mapping. This could be fragile and would be limited to whatever results you (as the developer) would code for reading. This is where PyDPF comes in to help eliminate that export of model and mesh step and go right from a full results file to data processing and plotting. The DPF in PyDPF stands for Data Processing Framework and (according to the PyAnsys Documentation) is dedicated to post-processing: DPF is a workflow-based framework which allows simple and/or complex evaluations by chaining operators. The data in DPF is defined based on physics agnostic mathematical quantities described in a self-sufficient entity called field. This allows DPF to be a modular and easy to use tool with a large range of capabilities. It’s a product designed to handle large amount of data. The PyAnsys documentation and examples highlight its use in Jupyter notebooks (including plotting). I explored the libraries using VS Code ‘Interactive window’ & ‘Python code files’ which are effectively a Jupyter notebook. Let’s see what it would look like in a notebook: ....and voila! Lots of info about the results file such as results sets, units, and mesh statistics. DPF Model------------------------------DPF Result InfoAnalysis: staticPhysics Type: mecanicUnit system: MKS: m, kg, N, s, V, A, degCAvailable results:U Displacement :nodal displacementsENF Element nodal Forces :element nodal forcesENG_VOL Volume :element volumeENG_SE Energy-stiffness matrix :element energy associated with the stiffness matrixENG_AHO Hourglass Energy :artificial hourglass energyENG_TH thermal dissipation energy :thermal dissipation energyENG_KE Kinetic Energy :kinetic energyENG_CO co-energy :co-energy (magnetics)ENG_INC incremental energy :incremental energy (magnetics)BFE Temperature :element structural nodal temperatures------------------------------DPF Meshed Region:3751 nodes3000 elementsUnit: mWith solid (3D) elements------------------------------DPF Time/Freq Support:Number of sets: 1Cumulative Time (s) LoadStep Substep1 1.000000 1 1 Now we go a little further and plot some results. In the script below we first setup a few variables for selecting the results type, component, and time step (lines 3–7). Then, using the available_results attribute of the model.metadata.result_info object we can get the result info objects for each result type in the results file (eg displacement, stress, etc). The result info object is not where the result data is actually stored. It is only a metadata object, but has all the information to retrieve the actual results using operators. First we create an operator using the operator_name attribute of the metadata object and connect it to the model.metadata.data_sources which associates the generic operator with our model object. We then use the time_scoping input to select the results set by index (converting from typical 0-based to 1-based in this case). If there is only 1 component in this results set then we get the fields container of the selected data set by calling the res_op.outputs.field_container() method. If there are more than 1 component then we create a new operator (component_selector_fc()) and chain it to the results operator by connecting the results operator outputs to the comp_sel operator on line 21 of the gist. We then add another input to select the component number (line 22) and request the fields container object by calling the .outputs.fields_container() method. There should only be 1 field object inside our field_container and we can access it as the first item in a list. finally we pass our filtered field to the plot method on our mesh object. To change result type, component, or time step you just change the index parameters (res_idx, comp_idx, or tf_idx). If you check out the PyDPF examples you will notice there are shortcuts to plotting displacement, but we will use this more generic method later. PyDPF is using VTK objects in the background to plot the results. Under the hood PyDPF converts the mesh object to a VTK unstructured grid and adds the arrays to that grid object before plotting. When we get to Dash_VTK we will also want the grid object so lets try and explicitly use it. Lets put it in a function! In this function we pass in the meshed region (model.metadata.meshed_region) and the filtered down field object we want to plot. We check the location of the field (grids/nodes or elements/cells) and then map the field data order to the order of the nodes/cells in the vtk grid object. This is needed because the raw field data may have a different mapping/order than the order of the nodes/elements (so you cant just assign the field.data array directly to the grid object!). Once we get our grid with the results array assigned we can replace the mesh.plot(f0) line with grid.plot(scalars=name). The main point here is that we are plotting directly with the VTK object (which we will need for Dash_vtk).... And now for the main course.... Ok we have a script that can filter down a results set to a specific field (by result type, time, and component) and we have a function that can extract a vtk grid object and assign that field to it with appropriate scoping. We now want to setup the Dash app so we can select one of the built in examples, and select the result type (by name) and time step (by time) and (if appropriate) select the component of the result. That sounds like 4x dcc.dropdown components. We will also use dash_bootstrap_components to make it look nice and add some callbacks that crawl through the selected ansys.dpf.core.examples example to collect the appropriate options for the dropdowns. we will put the actual plotting behind a “plot” button for stability. Below is an excerpt of the layout with dropdowns and the plot button. I am using a global variable APP_ID mostly out of habit to distinguish id names in the case of a multi-page app. Several dropdowns are missing options as well as value parameters. We will populate these with callbacks. Below are 2 callbacks that populate the result type, time step, and component dropdown options and default values. The first is triggered when the example is selected. This callback crawls through the available_results in the metadata.result_info object and creates the dropdown options using the name of the result type. We also create the timestep options using the float value as the label, but the integer index as the value parameter (remember using the index in the notebook example? We also send back default values (last timestep and first result type). The second callback is fired when a result type is selected. We use the result name to find the appropriate result_info item (using next). Once we have that we determine the number of components and create the options, values, and if the dropdown should be disabled (for the case of 1 component). Now for the callback that return the 3D object for Dash_VTK. This callback is fired when the ‘plot’ button is pressed. We get the model object using the example_dropdown and a global variable (dict) that maps the example names (simple_bar, msup_transient, and static) to their appropriate ansys.dpf.core.examples object. We get the result_info object as in the previous callback but now we get the meshed_region (mesh) object. The next part should look familiar from the notebook example except after we get the grid object with the field assigned, we then convert it to a mesh_state object that the Dash_VTK GeometryRepresentation component is expecting. we also set the colorscale range to the min/max of the field results. Not shown here is a function that creates a plotly figure with only a colorbar. While you can make a few edits to the dash_vtk source and rebuild the javascript (using node.js, and npm)to get a scalrabar to work with Dash_VTK (see here) I found it fairly simple to just create a plotly colorbar with the same background as Dash_VTK. See the full project for details. You can see the full files (notebook and Dash app) in this GitHub repository. I also included a yml file for installing all required libraries via conda. Note: I did notice some instability in the javascript when switching result types that have different quantity of components, eg from displacement (3 components)to stress (6 components) . I tried a few things, but digging into the javascript (react_VTK) is beyond my expertise. If you see an error you can refresh the page and start over. The first plot always works. Good question.... I believe packaging pyAnsys into a web app is most powerful when the intended user is not a simulation expert. Otherwise you could just use the notebook interface, Workbench, or MAPDL. I can think of a couple examples where post-processing could be useful in a web-app: A results file database where results files would be archived with some extra metadata and could be brought up to review very specific results (eg stress)Storing base ‘unit’ analyses that could be scaled / combined using superposition controlled by parameters provided in the web app A results file database where results files would be archived with some extra metadata and could be brought up to review very specific results (eg stress) Storing base ‘unit’ analyses that could be scaled / combined using superposition controlled by parameters provided in the web app Well thanks for making it this far. I hope you found something in here useful. In a future article I will cover integrating the PyAnsys pyMAPDL library into a Dash app which may be more useful as the Dash app can act as a very restricted preprocessor. It will include solving and extracting some results as well.
[ { "code": null, "e": 714, "s": 165, "text": "ANSYS recently announced it is supporting an open source project: PyAnsys. PyAnsys is split into multiple packages: PyMAPDL for interacting with an instance of an Ansys multiphysics simulation and equation solver and PyDPF-Core (& its simplified sibling PyDPF-Post) for post-processing Ansys results files. This is really intriguing to me as a structural analyst that uses ANSYS and Python pretty much daily. I have also used Plotly’s Dash framework to build fairly simple web-apps for post processing data and solving various equations or systems." }, { "code": null, "e": 1305, "s": 714, "text": "After playing around with PyANSYS in a Jupyter notebook for a while I decided to see if I could mash together a web-app that uses PyANSYS as a backend for a purpose-built analysis tool that a non-analyst could use and get insight (or at least build something that heads in that direction). PyANSYS is split into several packages. PyMAPDL is focused on communicating with a running MAPDL instance (local or remote) which pulls a license while running. PyDPF-Core and PyDPF-Post are focused on post-processing already-solved files (eg *.rst). These libraries do require Ansys to be installed." }, { "code": null, "e": 1521, "s": 1305, "text": "In this article I’ll walk through using PyDPF, Dash & Dash-VTK to build a web app that loads and plots results from a few PyDPF examples. You can see the full files (notebook and Dash app) in this GitHub repository." }, { "code": null, "e": 1756, "s": 1521, "text": "Plotly’s Dash open source framework is described as a framework that can be used to build a fully functioning web-application with only python. I really like it for building applications I expect other users (besides myself) will use." }, { "code": null, "e": 1883, "s": 1756, "text": "While its grown a lot since its debut, you can read the 2017 announcement essay to get more context to what Dash is all about:" }, { "code": null, "e": 1894, "s": 1883, "text": "medium.com" }, { "code": null, "e": 2139, "s": 1894, "text": "Years ago I built a few VTK-based desktop applications for post-processing FEA results. So when I learned about Dash-VTK I was excited to try and port some of that into a web-app. I put together an example with a writeup you can check out here:" }, { "code": null, "e": 2162, "s": 2139, "text": "towardsdatascience.com" }, { "code": null, "e": 2855, "s": 2162, "text": "With Dash we are able to build an application with a simple and clean user interface and thanks to Dash-VTK view 3D mesh and associated results. If you are using Ansys to solve your analysis problems you would need to export the results from Ansys into some fixed (likely text) format so they could be read in by the web-app. You would have to export the model (mesh) as well as the results from Ansys and handle all the mapping. This could be fragile and would be limited to whatever results you (as the developer) would code for reading. This is where PyDPF comes in to help eliminate that export of model and mesh step and go right from a full results file to data processing and plotting." }, { "code": null, "e": 2987, "s": 2855, "text": "The DPF in PyDPF stands for Data Processing Framework and (according to the PyAnsys Documentation) is dedicated to post-processing:" }, { "code": null, "e": 3365, "s": 2987, "text": "DPF is a workflow-based framework which allows simple and/or complex evaluations by chaining operators. The data in DPF is defined based on physics agnostic mathematical quantities described in a self-sufficient entity called field. This allows DPF to be a modular and easy to use tool with a large range of capabilities. It’s a product designed to handle large amount of data." }, { "code": null, "e": 3638, "s": 3365, "text": "The PyAnsys documentation and examples highlight its use in Jupyter notebooks (including plotting). I explored the libraries using VS Code ‘Interactive window’ & ‘Python code files’ which are effectively a Jupyter notebook. Let’s see what it would look like in a notebook:" }, { "code": null, "e": 3739, "s": 3638, "text": "....and voila! Lots of info about the results file such as results sets, units, and mesh statistics." }, { "code": null, "e": 4657, "s": 3739, "text": "DPF Model------------------------------DPF Result InfoAnalysis: staticPhysics Type: mecanicUnit system: MKS: m, kg, N, s, V, A, degCAvailable results:U Displacement :nodal displacementsENF Element nodal Forces :element nodal forcesENG_VOL Volume :element volumeENG_SE Energy-stiffness matrix :element energy associated with the stiffness matrixENG_AHO Hourglass Energy :artificial hourglass energyENG_TH thermal dissipation energy :thermal dissipation energyENG_KE Kinetic Energy :kinetic energyENG_CO co-energy :co-energy (magnetics)ENG_INC incremental energy :incremental energy (magnetics)BFE Temperature :element structural nodal temperatures------------------------------DPF Meshed Region:3751 nodes3000 elementsUnit: mWith solid (3D) elements------------------------------DPF Time/Freq Support:Number of sets: 1Cumulative Time (s) LoadStep Substep1 1.000000 1 1" }, { "code": null, "e": 6252, "s": 4657, "text": "Now we go a little further and plot some results. In the script below we first setup a few variables for selecting the results type, component, and time step (lines 3–7). Then, using the available_results attribute of the model.metadata.result_info object we can get the result info objects for each result type in the results file (eg displacement, stress, etc). The result info object is not where the result data is actually stored. It is only a metadata object, but has all the information to retrieve the actual results using operators. First we create an operator using the operator_name attribute of the metadata object and connect it to the model.metadata.data_sources which associates the generic operator with our model object. We then use the time_scoping input to select the results set by index (converting from typical 0-based to 1-based in this case). If there is only 1 component in this results set then we get the fields container of the selected data set by calling the res_op.outputs.field_container() method. If there are more than 1 component then we create a new operator (component_selector_fc()) and chain it to the results operator by connecting the results operator outputs to the comp_sel operator on line 21 of the gist. We then add another input to select the component number (line 22) and request the fields container object by calling the .outputs.fields_container() method. There should only be 1 field object inside our field_container and we can access it as the first item in a list. finally we pass our filtered field to the plot method on our mesh object." }, { "code": null, "e": 6514, "s": 6252, "text": "To change result type, component, or time step you just change the index parameters (res_idx, comp_idx, or tf_idx). If you check out the PyDPF examples you will notice there are shortcuts to plotting displacement, but we will use this more generic method later." }, { "code": null, "e": 6830, "s": 6514, "text": "PyDPF is using VTK objects in the background to plot the results. Under the hood PyDPF converts the mesh object to a VTK unstructured grid and adds the arrays to that grid object before plotting. When we get to Dash_VTK we will also want the grid object so lets try and explicitly use it. Lets put it in a function!" }, { "code": null, "e": 7539, "s": 6830, "text": "In this function we pass in the meshed region (model.metadata.meshed_region) and the filtered down field object we want to plot. We check the location of the field (grids/nodes or elements/cells) and then map the field data order to the order of the nodes/cells in the vtk grid object. This is needed because the raw field data may have a different mapping/order than the order of the nodes/elements (so you cant just assign the field.data array directly to the grid object!). Once we get our grid with the results array assigned we can replace the mesh.plot(f0) line with grid.plot(scalars=name). The main point here is that we are plotting directly with the VTK object (which we will need for Dash_vtk)...." }, { "code": null, "e": 7571, "s": 7539, "text": "And now for the main course...." }, { "code": null, "e": 8315, "s": 7571, "text": "Ok we have a script that can filter down a results set to a specific field (by result type, time, and component) and we have a function that can extract a vtk grid object and assign that field to it with appropriate scoping. We now want to setup the Dash app so we can select one of the built in examples, and select the result type (by name) and time step (by time) and (if appropriate) select the component of the result. That sounds like 4x dcc.dropdown components. We will also use dash_bootstrap_components to make it look nice and add some callbacks that crawl through the selected ansys.dpf.core.examples example to collect the appropriate options for the dropdowns. we will put the actual plotting behind a “plot” button for stability." }, { "code": null, "e": 8604, "s": 8315, "text": "Below is an excerpt of the layout with dropdowns and the plot button. I am using a global variable APP_ID mostly out of habit to distinguish id names in the case of a multi-page app. Several dropdowns are missing options as well as value parameters. We will populate these with callbacks." }, { "code": null, "e": 9166, "s": 8604, "text": "Below are 2 callbacks that populate the result type, time step, and component dropdown options and default values. The first is triggered when the example is selected. This callback crawls through the available_results in the metadata.result_info object and creates the dropdown options using the name of the result type. We also create the timestep options using the float value as the label, but the integer index as the value parameter (remember using the index in the notebook example? We also send back default values (last timestep and first result type)." }, { "code": null, "e": 9463, "s": 9166, "text": "The second callback is fired when a result type is selected. We use the result name to find the appropriate result_info item (using next). Once we have that we determine the number of components and create the options, values, and if the dropdown should be disabled (for the case of 1 component)." }, { "code": null, "e": 10556, "s": 9463, "text": "Now for the callback that return the 3D object for Dash_VTK. This callback is fired when the ‘plot’ button is pressed. We get the model object using the example_dropdown and a global variable (dict) that maps the example names (simple_bar, msup_transient, and static) to their appropriate ansys.dpf.core.examples object. We get the result_info object as in the previous callback but now we get the meshed_region (mesh) object. The next part should look familiar from the notebook example except after we get the grid object with the field assigned, we then convert it to a mesh_state object that the Dash_VTK GeometryRepresentation component is expecting. we also set the colorscale range to the min/max of the field results. Not shown here is a function that creates a plotly figure with only a colorbar. While you can make a few edits to the dash_vtk source and rebuild the javascript (using node.js, and npm)to get a scalrabar to work with Dash_VTK (see here) I found it fairly simple to just create a plotly colorbar with the same background as Dash_VTK. See the full project for details." }, { "code": null, "e": 10710, "s": 10556, "text": "You can see the full files (notebook and Dash app) in this GitHub repository. I also included a yml file for installing all required libraries via conda." }, { "code": null, "e": 11078, "s": 10710, "text": "Note: I did notice some instability in the javascript when switching result types that have different quantity of components, eg from displacement (3 components)to stress (6 components) . I tried a few things, but digging into the javascript (react_VTK) is beyond my expertise. If you see an error you can refresh the page and start over. The first plot always works." }, { "code": null, "e": 11366, "s": 11078, "text": "Good question.... I believe packaging pyAnsys into a web app is most powerful when the intended user is not a simulation expert. Otherwise you could just use the notebook interface, Workbench, or MAPDL. I can think of a couple examples where post-processing could be useful in a web-app:" }, { "code": null, "e": 11650, "s": 11366, "text": "A results file database where results files would be archived with some extra metadata and could be brought up to review very specific results (eg stress)Storing base ‘unit’ analyses that could be scaled / combined using superposition controlled by parameters provided in the web app" }, { "code": null, "e": 11805, "s": 11650, "text": "A results file database where results files would be archived with some extra metadata and could be brought up to review very specific results (eg stress)" }, { "code": null, "e": 11935, "s": 11805, "text": "Storing base ‘unit’ analyses that could be scaled / combined using superposition controlled by parameters provided in the web app" } ]
Recursive program for prime number - GeeksforGeeks
27 Jan, 2022 Given a number n, check whether it’s prime number or not using recursion.Examples: Input : n = 11 Output : Yes Input : n = 15 Output : No The idea is based on school method to check for prime numbers. C++ Java Python3 C# PHP Javascript // CPP Program to find whether a Number // is Prime or Not using Recursion#include <bits/stdc++.h>using namespace std; // Returns true if n is prime, else// return false.// i is current divisor to check.bool isPrime(int n, int i = 2){ // Base cases if (n <= 2) return (n == 2) ? true : false; if (n % i == 0) return false; if (i * i > n) return true; // Check for next divisor return isPrime(n, i + 1);} // Driver Programint main(){ int n = 15; if (isPrime(n)) cout << "Yes"; else cout << "No"; return 0;} // java Program to find whether a Number// is Prime or Not using Recursionimport java.util.*; class GFG { // Returns true if n is prime, else // return false. // i is current divisor to check. static boolean isPrime(int n, int i) { // Base cases if (n <= 2) return (n == 2) ? true : false; if (n % i == 0) return false; if (i * i > n) return true; // Check for next divisor return isPrime(n, i + 1); } // Driver program to test above function public static void main(String[] args) { int n = 15; if (isPrime(n, 2)) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed by Sam007. # Python 3 Program to find whether# a Number is Prime or Not using# Recursion # Returns true if n is prime, else# return false.# i is current divisor to check.def isPrime(n, i = 2): # Base cases if (n <= 2): return True if(n == 2) else False if (n % i == 0): return False if (i * i > n): return True # Check for next divisor return isPrime(n, i + 1) # Driver Programn = 15if (isPrime(n)): print("Yes")else: print("No") # This code is contributed by# Smitha Dinesh Semwal // C# Program to find whether a Number// is Prime or Not using Recursionusing System; class GFG{ // Returns true if n is prime, else // return false. // i is current divisor to check. static bool isPrime(int n, int i) { // Base cases if (n <= 2) return (n == 2) ? true : false; if (n % i == 0) return false; if (i * i > n) return true; // Check for next divisor return isPrime(n, i + 1); } // Driver code static void Main() { int n = 15; if (isPrime(n, 2)) Console.Write("Yes"); else Console.Write("No"); } } // This code is contributed by Sam007 <?php// PHP Program to find whether a Number// is Prime or Not using Recursion // Returns true if n is prime, else// return false.// i is current divisor to check.function isPrime($n, $i = 2){ // Base cases if ($n <= 2) return ($n == 2) ? true : false; if ($n % $i == 0) return false; if ($i * $i > $n) return true; // Check for next divisor return isPrime($n, $i + 1);} // Driver Code$n = 15;if (isPrime($n)) echo("Yes");else echo("No"); // This code is contributed by Ajit.?> <script> // JavaScript program to find whether a Number// is Prime or Not using Recursion // Returns true if n is prime, else // return false. // i is current divisor to check. function isPrime(n, i) { // Base cases if (n <= 2) return (n == 2) ? true : false; if (n % i == 0) return false; if (i * i > n) return true; // Check for next divisor return isPrime(n, i + 1); } // Driver code let n = 15; if (isPrime(n, 2)) document.write("Yes"); else document.write("No"); </script> No Smitha Dinesh Semwal jit_t susmitakundugoaldanga Admired_Olive Prime Number Mathematical Recursion Mathematical Recursion Prime Number Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Program to find sum of elements in a given array Program for factorial of a number Operators in C / C++ Program for Tower of Hanoi Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Recursion Program for Sum of the digits of a given number Backtracking | Introduction
[ { "code": null, "e": 24744, "s": 24716, "text": "\n27 Jan, 2022" }, { "code": null, "e": 24829, "s": 24744, "text": "Given a number n, check whether it’s prime number or not using recursion.Examples: " }, { "code": null, "e": 24885, "s": 24829, "text": "Input : n = 11\nOutput : Yes\n\nInput : n = 15\nOutput : No" }, { "code": null, "e": 24951, "s": 24887, "text": "The idea is based on school method to check for prime numbers. " }, { "code": null, "e": 24955, "s": 24951, "text": "C++" }, { "code": null, "e": 24960, "s": 24955, "text": "Java" }, { "code": null, "e": 24968, "s": 24960, "text": "Python3" }, { "code": null, "e": 24971, "s": 24968, "text": "C#" }, { "code": null, "e": 24975, "s": 24971, "text": "PHP" }, { "code": null, "e": 24986, "s": 24975, "text": "Javascript" }, { "code": "// CPP Program to find whether a Number // is Prime or Not using Recursion#include <bits/stdc++.h>using namespace std; // Returns true if n is prime, else// return false.// i is current divisor to check.bool isPrime(int n, int i = 2){ // Base cases if (n <= 2) return (n == 2) ? true : false; if (n % i == 0) return false; if (i * i > n) return true; // Check for next divisor return isPrime(n, i + 1);} // Driver Programint main(){ int n = 15; if (isPrime(n)) cout << \"Yes\"; else cout << \"No\"; return 0;}", "e": 25560, "s": 24986, "text": null }, { "code": "// java Program to find whether a Number// is Prime or Not using Recursionimport java.util.*; class GFG { // Returns true if n is prime, else // return false. // i is current divisor to check. static boolean isPrime(int n, int i) { // Base cases if (n <= 2) return (n == 2) ? true : false; if (n % i == 0) return false; if (i * i > n) return true; // Check for next divisor return isPrime(n, i + 1); } // Driver program to test above function public static void main(String[] args) { int n = 15; if (isPrime(n, 2)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed by Sam007.", "e": 26338, "s": 25560, "text": null }, { "code": "# Python 3 Program to find whether# a Number is Prime or Not using# Recursion # Returns true if n is prime, else# return false.# i is current divisor to check.def isPrime(n, i = 2): # Base cases if (n <= 2): return True if(n == 2) else False if (n % i == 0): return False if (i * i > n): return True # Check for next divisor return isPrime(n, i + 1) # Driver Programn = 15if (isPrime(n)): print(\"Yes\")else: print(\"No\") # This code is contributed by# Smitha Dinesh Semwal", "e": 26861, "s": 26338, "text": null }, { "code": "// C# Program to find whether a Number// is Prime or Not using Recursionusing System; class GFG{ // Returns true if n is prime, else // return false. // i is current divisor to check. static bool isPrime(int n, int i) { // Base cases if (n <= 2) return (n == 2) ? true : false; if (n % i == 0) return false; if (i * i > n) return true; // Check for next divisor return isPrime(n, i + 1); } // Driver code static void Main() { int n = 15; if (isPrime(n, 2)) Console.Write(\"Yes\"); else Console.Write(\"No\"); } } // This code is contributed by Sam007", "e": 27573, "s": 26861, "text": null }, { "code": "<?php// PHP Program to find whether a Number// is Prime or Not using Recursion // Returns true if n is prime, else// return false.// i is current divisor to check.function isPrime($n, $i = 2){ // Base cases if ($n <= 2) return ($n == 2) ? true : false; if ($n % $i == 0) return false; if ($i * $i > $n) return true; // Check for next divisor return isPrime($n, $i + 1);} // Driver Code$n = 15;if (isPrime($n)) echo(\"Yes\");else echo(\"No\"); // This code is contributed by Ajit.?>", "e": 28097, "s": 27573, "text": null }, { "code": "<script> // JavaScript program to find whether a Number// is Prime or Not using Recursion // Returns true if n is prime, else // return false. // i is current divisor to check. function isPrime(n, i) { // Base cases if (n <= 2) return (n == 2) ? true : false; if (n % i == 0) return false; if (i * i > n) return true; // Check for next divisor return isPrime(n, i + 1); } // Driver code let n = 15; if (isPrime(n, 2)) document.write(\"Yes\"); else document.write(\"No\"); </script>", "e": 28739, "s": 28097, "text": null }, { "code": null, "e": 28742, "s": 28739, "text": "No" }, { "code": null, "e": 28765, "s": 28744, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 28771, "s": 28765, "text": "jit_t" }, { "code": null, "e": 28793, "s": 28771, "text": "susmitakundugoaldanga" }, { "code": null, "e": 28807, "s": 28793, "text": "Admired_Olive" }, { "code": null, "e": 28820, "s": 28807, "text": "Prime Number" }, { "code": null, "e": 28833, "s": 28820, "text": "Mathematical" }, { "code": null, "e": 28843, "s": 28833, "text": "Recursion" }, { "code": null, "e": 28856, "s": 28843, "text": "Mathematical" }, { "code": null, "e": 28866, "s": 28856, "text": "Recursion" }, { "code": null, "e": 28879, "s": 28866, "text": "Prime Number" }, { "code": null, "e": 28977, "s": 28879, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28986, "s": 28977, "text": "Comments" }, { "code": null, "e": 28999, "s": 28986, "text": "Old Comments" }, { "code": null, "e": 29023, "s": 28999, "text": "Merge two sorted arrays" }, { "code": null, "e": 29066, "s": 29023, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 29115, "s": 29066, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 29149, "s": 29115, "text": "Program for factorial of a number" }, { "code": null, "e": 29170, "s": 29149, "text": "Operators in C / C++" }, { "code": null, "e": 29197, "s": 29170, "text": "Program for Tower of Hanoi" }, { "code": null, "e": 29282, "s": 29197, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 29292, "s": 29282, "text": "Recursion" }, { "code": null, "e": 29340, "s": 29292, "text": "Program for Sum of the digits of a given number" } ]
Output of Python programs | Set 8 - GeeksforGeeks
01 Jun, 2021 Prerequisite – Lists in Python Predict the output of the following Python programs. Program 1 Python list = [1, 2, 3, None, (1, 2, 3, 4, 5), ['Geeks', 'for', 'Geeks']]print len(list) Output: 6 Explanation: The beauty of python list datatype is that within a list, a programmer can nest another list, a dictionary or a tuple. Since in the code there are 6 items present in the list the length of the list is 6. Program 2 Python list = ['python', 'learning', '@', 'Geeks', 'for', 'Geeks'] print list[::] print list[0:6:2] print list[ :6: ] print list[ :6:2] print list[ ::3] print list[ ::-2] Output: ['python', 'learning', '@', 'Geeks', 'for', 'Geeks'] ['python', '@', 'for'] ['python', 'learning', '@', 'Geeks', 'for', 'Geeks'] ['python', '@', 'for'] ['python', 'Geeks'] ['Geeks', 'Geeks', 'learning'] Explanation: In python list slicing can also be done by using the syntax listName[x:y:z] where x means the initial index, y-1 defines the final index value and z specifies the step size. If anyone of the values among x, y and z is missing the interpreter takes default value.Note: 1. For x default value is 0 i.e. start of the list. 2. For y default value is length of the list. 3. For z default value is 1 i.e. every element of the list. Program 3 Python d1 = [10, 20, 30, 40, 50]d2 = [1, 2, 3, 4, 5]print d1 - d1 Output: No Output Explanation: Unlike addition or relational operators not all the arithmetic operators can use lists as their operands. Since – minus operator can’t take lists as its operand no output will be produced. Program will produce following error. TypeError: unsupported operand type(s) for -: 'list' and 'list' Program 4 Python list = ['a', 'b', 'c', 'd', 'e']print list[10:] Output: [] Explanation: As one would expect, attempting to access a member of a list using an index that exceeds the number of members (e.g., attempting to access list[10] in the list above) results in an IndexError. However, attempting to access a slice of a list at a starting index that exceeds the number of members in the list will not result in an IndexError and will simply return an empty list. Program 5 Python list = ['a', 'b', 'c']*-3print list Output: [] Explanation: A expression list[listelements]*N where N is a integer appends N copies of list elements in the original list. If N is a negative integer or 0 output will be a empty list else if N is positive list elements will be added N times to the original list. This article is contributed by Avinash Kumar Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Akanksha_Rai arorakashish0911 Python-Output Program Output Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to copy a string in C/C++ Output of Java Program | Set 3 Runtime Errors Output of C++ Program | Set 1 Output of C programs | Set 31 (Pointers) Output of Java Program | Set 7 Output of C Programs | Set 3 Output of Java program | Set 5 Output of Java program | Set 26 Output of C Program | Set 24
[ { "code": null, "e": 24618, "s": 24590, "text": "\n01 Jun, 2021" }, { "code": null, "e": 24703, "s": 24618, "text": "Prerequisite – Lists in Python Predict the output of the following Python programs. " }, { "code": null, "e": 24715, "s": 24703, "text": "Program 1 " }, { "code": null, "e": 24722, "s": 24715, "text": "Python" }, { "code": "list = [1, 2, 3, None, (1, 2, 3, 4, 5), ['Geeks', 'for', 'Geeks']]print len(list)", "e": 24804, "s": 24722, "text": null }, { "code": null, "e": 24814, "s": 24804, "text": "Output: " }, { "code": null, "e": 24816, "s": 24814, "text": "6" }, { "code": null, "e": 25034, "s": 24816, "text": "Explanation: The beauty of python list datatype is that within a list, a programmer can nest another list, a dictionary or a tuple. Since in the code there are 6 items present in the list the length of the list is 6. " }, { "code": null, "e": 25046, "s": 25034, "text": "Program 2 " }, { "code": null, "e": 25053, "s": 25046, "text": "Python" }, { "code": "list = ['python', 'learning', '@', 'Geeks', 'for', 'Geeks'] print list[::] print list[0:6:2] print list[ :6: ] print list[ :6:2] print list[ ::3] print list[ ::-2] ", "e": 25248, "s": 25053, "text": null }, { "code": null, "e": 25258, "s": 25248, "text": "Output: " }, { "code": null, "e": 25461, "s": 25258, "text": "['python', 'learning', '@', 'Geeks', 'for', 'Geeks']\n['python', '@', 'for']\n['python', 'learning', '@', 'Geeks', 'for', 'Geeks']\n['python', '@', 'for']\n['python', 'Geeks']\n['Geeks', 'Geeks', 'learning']" }, { "code": null, "e": 25901, "s": 25461, "text": "Explanation: In python list slicing can also be done by using the syntax listName[x:y:z] where x means the initial index, y-1 defines the final index value and z specifies the step size. If anyone of the values among x, y and z is missing the interpreter takes default value.Note: 1. For x default value is 0 i.e. start of the list. 2. For y default value is length of the list. 3. For z default value is 1 i.e. every element of the list. " }, { "code": null, "e": 25913, "s": 25901, "text": "Program 3 " }, { "code": null, "e": 25920, "s": 25913, "text": "Python" }, { "code": "d1 = [10, 20, 30, 40, 50]d2 = [1, 2, 3, 4, 5]print d1 - d1", "e": 25979, "s": 25920, "text": null }, { "code": null, "e": 25989, "s": 25979, "text": "Output: " }, { "code": null, "e": 25999, "s": 25989, "text": "No Output" }, { "code": null, "e": 26241, "s": 25999, "text": "Explanation: Unlike addition or relational operators not all the arithmetic operators can use lists as their operands. Since – minus operator can’t take lists as its operand no output will be produced. Program will produce following error. " }, { "code": null, "e": 26305, "s": 26241, "text": "TypeError: unsupported operand type(s) for -: 'list' and 'list'" }, { "code": null, "e": 26317, "s": 26307, "text": "Program 4" }, { "code": null, "e": 26324, "s": 26317, "text": "Python" }, { "code": "list = ['a', 'b', 'c', 'd', 'e']print list[10:]", "e": 26372, "s": 26324, "text": null }, { "code": null, "e": 26382, "s": 26372, "text": "Output: " }, { "code": null, "e": 26385, "s": 26382, "text": "[]" }, { "code": null, "e": 26779, "s": 26385, "text": "Explanation: As one would expect, attempting to access a member of a list using an index that exceeds the number of members (e.g., attempting to access list[10] in the list above) results in an IndexError. However, attempting to access a slice of a list at a starting index that exceeds the number of members in the list will not result in an IndexError and will simply return an empty list. " }, { "code": null, "e": 26791, "s": 26779, "text": "Program 5 " }, { "code": null, "e": 26798, "s": 26791, "text": "Python" }, { "code": "list = ['a', 'b', 'c']*-3print list", "e": 26834, "s": 26798, "text": null }, { "code": null, "e": 26844, "s": 26834, "text": "Output: " }, { "code": null, "e": 26847, "s": 26844, "text": "[]" }, { "code": null, "e": 27113, "s": 26847, "text": "Explanation: A expression list[listelements]*N where N is a integer appends N copies of list elements in the original list. If N is a negative integer or 0 output will be a empty list else if N is positive list elements will be added N times to the original list. " }, { "code": null, "e": 27540, "s": 27113, "text": "This article is contributed by Avinash Kumar Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 27553, "s": 27540, "text": "Akanksha_Rai" }, { "code": null, "e": 27570, "s": 27553, "text": "arorakashish0911" }, { "code": null, "e": 27584, "s": 27570, "text": "Python-Output" }, { "code": null, "e": 27599, "s": 27584, "text": "Program Output" }, { "code": null, "e": 27697, "s": 27599, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27738, "s": 27697, "text": "Different ways to copy a string in C/C++" }, { "code": null, "e": 27769, "s": 27738, "text": "Output of Java Program | Set 3" }, { "code": null, "e": 27784, "s": 27769, "text": "Runtime Errors" }, { "code": null, "e": 27814, "s": 27784, "text": "Output of C++ Program | Set 1" }, { "code": null, "e": 27855, "s": 27814, "text": "Output of C programs | Set 31 (Pointers)" }, { "code": null, "e": 27886, "s": 27855, "text": "Output of Java Program | Set 7" }, { "code": null, "e": 27915, "s": 27886, "text": "Output of C Programs | Set 3" }, { "code": null, "e": 27946, "s": 27915, "text": "Output of Java program | Set 5" }, { "code": null, "e": 27978, "s": 27946, "text": "Output of Java program | Set 26" } ]
Painting the Fence | Practice | GeeksforGeeks
Given a fence with n posts and k colors, find out the number of ways of painting the fence so that not more than two consecutive fences have the same colors. Since the answer can be large return it modulo 10^9 + 7. Example 1: Input: N=3, K=2 Output: 6 Explanation: We have following possible combinations: Example 2: Input: N=2, K=4 Output: 16 Your Task: Since, this is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function countWays() that takes n and k as parameters and returns the number of ways in which the fence can be painted.(modulo 109 + 7) Expected Time Complexity: O(N). Expected Auxiliary Space: O(N). Constraints: 1 ≤ N ≤ 5000 1 ≤ K ≤ 100 0 lindan1231 week ago int mod = 1e9 + 7; long long countWays(int n, int k){ long long int dp[n+1]; //because when 1 fence only if(n==1) { return k; } else if(n==2) { return k*k; } dp[1] = k; dp[2] = k*k; for(long long int i=3;i<=n;i++) { dp[i] = ((k-1)*((dp[i-1]%mod)+ (dp[i-2])%mod)%mod)%mod; } return dp[n]%mod; } Time Taken : 0.02 Cpp 0 mukulbansal4213 weeks ago 0 aryanrot2343 weeks ago Idk why my code is not working for other test cases , i'm getting TLE Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1 at Array.main(File.java:53) #My code long countWays(int n,int k) { if(n==1) return k; if(n==0) return 0; if(k==0) return 0; long same = k*1; long diff = k*(k-1); long total = same+diff; for(int i = 3;i<=n;i++){ same = diff*1; diff = total*(k-1); total = same+diff; } return total%1000000007; } +1 jainmuskan5653 weeks ago long long countWays(int n, int k){ /* we will think of this as taking count of 2 types of ways same= in which last 2 fences are of same color diff= last 2 are of different color total= same+diff we iterate over the number of fences and change the value of same, total and diff accordingly for each next iteration the value of same = diff*1 (all the different values and their last element is decided) diff = total *(k-1) (all the values then choose the color not taken already) total= same+diff */ // only 1 fence number of ways would be k if(n==1){ return k; } long long same,diff,total; long long mod= 1e9+7; same= k%mod; diff= (k*(k-1))%mod; total= (same+diff)%mod; for(int i=3;i<=n;i++){ same= (diff)%mod; diff= ((total)%mod *(k-1))%mod; total= ((diff)%mod+(same)%mod)%mod; } return (total)%mod; } 0 khushiaggarwal09021 month ago long long countWays(int n, int k) { long long mod=1e9+7; if(n==0) return 0; if(n==1) return k%mod; long long same=k%mod; long long diff= (k*(k-1))%mod; for(long long i=3;i<=n;i++) { long long prev=diff%mod; diff=((same+prev)*(k-1))%mod; same=prev%mod; } return (same+diff)%mod; } 0 ankitghanghas10721 month ago long long countWays(int n, int k){ // code here int inf = 1e9 + 7; long long dp[n+1]; dp[1] = k; dp[2] = k*k; for(int i = 3; i<=n; i++){ dp[i] = ((k-1)*((dp[i-1] + dp[i-2])%inf))%inf; } return dp[n]; } +4 aloksinghbais022 months ago C++ solution having time complexity as O(N) and space complexity as O(1) is as follows :- Execution Time :- 0.0 / 1.1 sec long long countWays(int n, int k){ if(n == 1) return (k); int mod = (int)1e9 + 7; long long int same = k * 1; long long int diff = (k * (k-1)) % mod; long long int total = (same + diff) % mod; for(int i = 3; i <= n; i++){ same = diff * 1; diff = (total * (k-1)) % mod; total = (same + diff) % mod; } return total; } 0 bhargav_412 months ago Java Solution | TC - O(N) | SC - O(1) class Solution { long countWays(int n,int k) { if(n==1) return k; long last_two_same; long last_two_different; long total; last_two_same = (long)k; last_two_different = (long)k*((long)(k-1)); total = last_two_same + last_two_different; int mod = 1000000007; for(int i=3;i<=n;i++){ last_two_same = last_two_different%mod; last_two_different = ((total%mod)*(long)(k-1))%mod; total = (last_two_different%mod + last_two_same%mod)%mod; } return total%mod; } } 0 gauravkmr01102 months ago long long countWays(int n, int k){ long long dp[n+1]; dp[0]=0; dp[1]=k; dp[2]=k*k; int m = 1e9+7; for(int i =3 ; i<=n ; i++){ dp[i]=((dp[i-2]+dp[i-1])*(k-1))%m; } return dp[n]; } 0 uttarandas5012 months ago long long countWays(int n, int k){ // code here int mod = 1e9+7; long long a = 1, b = k, c; if(n==1){return k;} if(n==2){return b*(k-1);} else{ for(int i=3; i<=n; i++){ c = ((a+b)*(k-1))%mod; a = b; b = c; } } return (b*k)%mod; } 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": 453, "s": 238, "text": "Given a fence with n posts and k colors, find out the number of ways of painting the fence so that not more than two consecutive fences have the same colors. Since the answer can be large return it modulo 10^9 + 7." }, { "code": null, "e": 465, "s": 453, "text": "\nExample 1:" }, { "code": null, "e": 549, "s": 465, "text": "Input:\nN=3, K=2 \nOutput: 6\nExplanation: \nWe have following possible combinations:\n" }, { "code": null, "e": 562, "s": 551, "text": "Example 2:" }, { "code": null, "e": 591, "s": 562, "text": "Input:\nN=2, K=4\nOutput: 16\n" }, { "code": null, "e": 888, "s": 591, "text": "\nYour Task:\nSince, this is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function countWays() that takes n and k as parameters and returns the number of ways in which the fence can be painted.(modulo 109 + 7)" }, { "code": null, "e": 954, "s": 890, "text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(N)." }, { "code": null, "e": 994, "s": 956, "text": "Constraints:\n1 ≤ N ≤ 5000\n1 ≤ K ≤ 100" }, { "code": null, "e": 998, "s": 996, "text": "0" }, { "code": null, "e": 1018, "s": 998, "text": "lindan1231 week ago" }, { "code": null, "e": 1477, "s": 1018, "text": "int mod = 1e9 + 7;\n long long countWays(int n, int k){\n long long int dp[n+1];\n //because when 1 fence only\n if(n==1)\n {\n return k;\n }\n \n else if(n==2)\n {\n return k*k;\n }\n dp[1] = k;\n dp[2] = k*k;\n for(long long int i=3;i<=n;i++)\n {\n dp[i] = ((k-1)*((dp[i-1]%mod)+ (dp[i-2])%mod)%mod)%mod;\n }\n return dp[n]%mod;\n }" }, { "code": null, "e": 1495, "s": 1477, "text": "Time Taken : 0.02" }, { "code": null, "e": 1499, "s": 1495, "text": "Cpp" }, { "code": null, "e": 1501, "s": 1499, "text": "0" }, { "code": null, "e": 1527, "s": 1501, "text": "mukulbansal4213 weeks ago" }, { "code": null, "e": 1529, "s": 1527, "text": "0" }, { "code": null, "e": 1552, "s": 1529, "text": "aryanrot2343 weeks ago" }, { "code": null, "e": 1623, "s": 1552, "text": "Idk why my code is not working for other test cases , i'm getting TLE " }, { "code": null, "e": 1757, "s": 1625, "text": "Exception in thread \"main\" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1 at Array.main(File.java:53)" }, { "code": null, "e": 1768, "s": 1759, "text": "#My code" }, { "code": null, "e": 2160, "s": 1768, "text": " long countWays(int n,int k)\n {\n if(n==1) return k;\n if(n==0) return 0;\n if(k==0) return 0;\n \n long same = k*1;\n long diff = k*(k-1);\n long total = same+diff;\n \n for(int i = 3;i<=n;i++){\n same = diff*1;\n diff = total*(k-1);\n total = same+diff;\n }\n return total%1000000007;\n }" }, { "code": null, "e": 2163, "s": 2160, "text": "+1" }, { "code": null, "e": 2188, "s": 2163, "text": "jainmuskan5653 weeks ago" }, { "code": null, "e": 3213, "s": 2188, "text": " long long countWays(int n, int k){ /* we will think of this as taking count of 2 types of ways same= in which last 2 fences are of same color diff= last 2 are of different color total= same+diff we iterate over the number of fences and change the value of same, total and diff accordingly for each next iteration the value of same = diff*1 (all the different values and their last element is decided) diff = total *(k-1) (all the values then choose the color not taken already) total= same+diff */ // only 1 fence number of ways would be k if(n==1){ return k; } long long same,diff,total; long long mod= 1e9+7; same= k%mod; diff= (k*(k-1))%mod; total= (same+diff)%mod; for(int i=3;i<=n;i++){ same= (diff)%mod; diff= ((total)%mod *(k-1))%mod; total= ((diff)%mod+(same)%mod)%mod; } return (total)%mod; }" }, { "code": null, "e": 3215, "s": 3213, "text": "0" }, { "code": null, "e": 3245, "s": 3215, "text": "khushiaggarwal09021 month ago" }, { "code": null, "e": 3633, "s": 3245, "text": "long long countWays(int n, int k) { long long mod=1e9+7; if(n==0) return 0; if(n==1) return k%mod; long long same=k%mod; long long diff= (k*(k-1))%mod; for(long long i=3;i<=n;i++) { long long prev=diff%mod; diff=((same+prev)*(k-1))%mod; same=prev%mod; } return (same+diff)%mod; }" }, { "code": null, "e": 3635, "s": 3633, "text": "0" }, { "code": null, "e": 3664, "s": 3635, "text": "ankitghanghas10721 month ago" }, { "code": null, "e": 3926, "s": 3664, "text": "long long countWays(int n, int k){ // code here int inf = 1e9 + 7; long long dp[n+1]; dp[1] = k; dp[2] = k*k; for(int i = 3; i<=n; i++){ dp[i] = ((k-1)*((dp[i-1] + dp[i-2])%inf))%inf; } return dp[n]; }" }, { "code": null, "e": 3929, "s": 3926, "text": "+4" }, { "code": null, "e": 3957, "s": 3929, "text": "aloksinghbais022 months ago" }, { "code": null, "e": 4048, "s": 3957, "text": "C++ solution having time complexity as O(N) and space complexity as O(1) is as follows :- " }, { "code": null, "e": 4082, "s": 4050, "text": "Execution Time :- 0.0 / 1.1 sec" }, { "code": null, "e": 4494, "s": 4084, "text": "long long countWays(int n, int k){ if(n == 1) return (k); int mod = (int)1e9 + 7; long long int same = k * 1; long long int diff = (k * (k-1)) % mod; long long int total = (same + diff) % mod; for(int i = 3; i <= n; i++){ same = diff * 1; diff = (total * (k-1)) % mod; total = (same + diff) % mod; } return total; }" }, { "code": null, "e": 4496, "s": 4494, "text": "0" }, { "code": null, "e": 4519, "s": 4496, "text": "bhargav_412 months ago" }, { "code": null, "e": 4557, "s": 4519, "text": "Java Solution | TC - O(N) | SC - O(1)" }, { "code": null, "e": 5186, "s": 4559, "text": "class Solution\n{\n long countWays(int n,int k)\n {\n if(n==1) return k;\n long last_two_same;\n long last_two_different;\n long total;\n \n last_two_same = (long)k;\n last_two_different = (long)k*((long)(k-1));\n total = last_two_same + last_two_different;\n \n int mod = 1000000007;\n \n for(int i=3;i<=n;i++){\n last_two_same = last_two_different%mod;\n last_two_different = ((total%mod)*(long)(k-1))%mod;\n total = (last_two_different%mod + last_two_same%mod)%mod;\n }\n \n return total%mod;\n }\n}" }, { "code": null, "e": 5188, "s": 5186, "text": "0" }, { "code": null, "e": 5214, "s": 5188, "text": "gauravkmr01102 months ago" }, { "code": null, "e": 5483, "s": 5214, "text": "long long countWays(int n, int k){ long long dp[n+1]; dp[0]=0; dp[1]=k; dp[2]=k*k; int m = 1e9+7; for(int i =3 ; i<=n ; i++){ dp[i]=((dp[i-2]+dp[i-1])*(k-1))%m; } return dp[n]; }" }, { "code": null, "e": 5485, "s": 5483, "text": "0" }, { "code": null, "e": 5511, "s": 5485, "text": "uttarandas5012 months ago" }, { "code": null, "e": 5890, "s": 5511, "text": "long long countWays(int n, int k){\n // code here\n \n int mod = 1e9+7;\n long long a = 1, b = k, c;\n if(n==1){return k;}\n if(n==2){return b*(k-1);}\n else{\n for(int i=3; i<=n; i++){\n c = ((a+b)*(k-1))%mod;\n a = b;\n b = c;\n }\n }\n return (b*k)%mod;\n }" }, { "code": null, "e": 6036, "s": 5890, "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": 6072, "s": 6036, "text": " Login to access your submissions. " }, { "code": null, "e": 6082, "s": 6072, "text": "\nProblem\n" }, { "code": null, "e": 6092, "s": 6082, "text": "\nContest\n" }, { "code": null, "e": 6155, "s": 6092, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6303, "s": 6155, "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": 6511, "s": 6303, "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": 6617, "s": 6511, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
What is the difference between Dictionary and HashTable in PowerShell?
PowerShell programmers generally prefer the Hashtable over the Dictionary although there are some advantages of using Dictionary. See the difference below. a. Hashtable is easy to declare while the Dictionary is a little complex compared to Hashtable. For example, To create a hashtable, $hash = @{ 'Country' = 'India' 'Code' = '91' } To create a Dictionary, $citydata = New-Object System.Collections.Generic.Dictionary"[String,Int]" $citydata.Add('India',91) b. Hashtable is included in the namespace called Collections while Dictionary is included in the namespace called System.Collections.Generic namespace. Hashtable is non-generic so it can be a collection of different data types and Dictionary belongs to a generic class so it is a collection of specific data types. c. Hashtable and Dictionary both have the BaseType is Object but their datatypes are different. Hashtable has a ‘Hashtable’ datatype and Dictionary has a Dictionary`2 datatype. Hashtable: IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Hashtable System.Object Dictionary: IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Dictionary`2 System.Object
[ { "code": null, "e": 1218, "s": 1062, "text": "PowerShell programmers generally prefer the Hashtable over the Dictionary although there are some advantages of using Dictionary. See the difference below." }, { "code": null, "e": 1327, "s": 1218, "text": "a. Hashtable is easy to declare while the Dictionary is a little complex compared to Hashtable. For example," }, { "code": null, "e": 1350, "s": 1327, "text": "To create a hashtable," }, { "code": null, "e": 1403, "s": 1350, "text": "$hash = @{\n 'Country' = 'India'\n 'Code' = '91'\n}" }, { "code": null, "e": 1427, "s": 1403, "text": "To create a Dictionary," }, { "code": null, "e": 1529, "s": 1427, "text": "$citydata = New-Object System.Collections.Generic.Dictionary\"[String,Int]\"\n$citydata.Add('India',91) " }, { "code": null, "e": 1844, "s": 1529, "text": "b. Hashtable is included in the namespace called Collections while Dictionary is included in the namespace called System.Collections.Generic namespace. Hashtable is non-generic so it can be a collection of different data types and Dictionary belongs to a generic class so it is a collection of specific data types." }, { "code": null, "e": 2021, "s": 1844, "text": "c. Hashtable and Dictionary both have the BaseType is Object but their datatypes are different. Hashtable has a ‘Hashtable’ datatype and Dictionary has a Dictionary`2 datatype." }, { "code": null, "e": 2032, "s": 2021, "text": "Hashtable:" }, { "code": null, "e": 2148, "s": 2032, "text": "IsPublic IsSerial Name BaseType\n-------- -------- ---- --------\nTrue True Hashtable System.Object" }, { "code": null, "e": 2160, "s": 2148, "text": "Dictionary:" }, { "code": null, "e": 2285, "s": 2160, "text": "IsPublic IsSerial Name BaseType\n-------- -------- ---- --------\nTrue True Dictionary`2 System.Object" } ]
ios manipulators showpoint() function in C++ - GeeksforGeeks
28 Aug, 2019 The showpoint() method of stream manipulators in C++ is used to set the showpoint format flag for the specified str stream. This flag always displays the floating point values along with their decimal values. Syntax: ios_base& showpoint (ios_base& str) Parameters: This method accepts str as a parameter which is the stream for which the format flag is affected. Return Value: This method returns the stream str with showpoint format flag set. Example 1: // C++ code to demonstrate// the working of showpoint() function #include <iostream> using namespace std; int main(){ // Initializing the floating values double n1 = 10; double n2 = 20.0; cout.precision(5); // Using showpoint() cout << "showpoint flag: " << showpoint << n1 << endl << n2 << endl; return 0;} showpoint flag: 10.000 20.000 Example 2: // C++ code to demonstrate// the working of showpoint() function #include <iostream> using namespace std; int main(){ // Initializing the floating values double n3 = 30.1223; cout.precision(5); // Using showpoint() cout << "showpoint flag: " << showpoint << n3 << endl; return 0;} showpoint flag: 30.122 Reference: http://www.cplusplus.com/reference/ios/showpoint/ cpp-ios cpp-manipulators C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Sorting a vector in C++ Friend class and function in C++ Pair in C++ Standard Template Library (STL) Convert string to char array in C++ Iterators in C++ STL Inline Functions in C++ List in C++ Standard Template Library (STL) Multithreading in C++
[ { "code": null, "e": 24098, "s": 24070, "text": "\n28 Aug, 2019" }, { "code": null, "e": 24307, "s": 24098, "text": "The showpoint() method of stream manipulators in C++ is used to set the showpoint format flag for the specified str stream. This flag always displays the floating point values along with their decimal values." }, { "code": null, "e": 24315, "s": 24307, "text": "Syntax:" }, { "code": null, "e": 24352, "s": 24315, "text": "ios_base& showpoint (ios_base& str)\n" }, { "code": null, "e": 24462, "s": 24352, "text": "Parameters: This method accepts str as a parameter which is the stream for which the format flag is affected." }, { "code": null, "e": 24543, "s": 24462, "text": "Return Value: This method returns the stream str with showpoint format flag set." }, { "code": null, "e": 24554, "s": 24543, "text": "Example 1:" }, { "code": "// C++ code to demonstrate// the working of showpoint() function #include <iostream> using namespace std; int main(){ // Initializing the floating values double n1 = 10; double n2 = 20.0; cout.precision(5); // Using showpoint() cout << \"showpoint flag: \" << showpoint << n1 << endl << n2 << endl; return 0;}", "e": 24918, "s": 24554, "text": null }, { "code": null, "e": 24949, "s": 24918, "text": "showpoint flag: 10.000\n20.000\n" }, { "code": null, "e": 24960, "s": 24949, "text": "Example 2:" }, { "code": "// C++ code to demonstrate// the working of showpoint() function #include <iostream> using namespace std; int main(){ // Initializing the floating values double n3 = 30.1223; cout.precision(5); // Using showpoint() cout << \"showpoint flag: \" << showpoint << n3 << endl; return 0;}", "e": 25286, "s": 24960, "text": null }, { "code": null, "e": 25310, "s": 25286, "text": "showpoint flag: 30.122\n" }, { "code": null, "e": 25371, "s": 25310, "text": "Reference: http://www.cplusplus.com/reference/ios/showpoint/" }, { "code": null, "e": 25379, "s": 25371, "text": "cpp-ios" }, { "code": null, "e": 25396, "s": 25379, "text": "cpp-manipulators" }, { "code": null, "e": 25400, "s": 25396, "text": "C++" }, { "code": null, "e": 25404, "s": 25400, "text": "CPP" }, { "code": null, "e": 25502, "s": 25404, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25530, "s": 25502, "text": "Operator Overloading in C++" }, { "code": null, "e": 25550, "s": 25530, "text": "Polymorphism in C++" }, { "code": null, "e": 25574, "s": 25550, "text": "Sorting a vector in C++" }, { "code": null, "e": 25607, "s": 25574, "text": "Friend class and function in C++" }, { "code": null, "e": 25651, "s": 25607, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 25687, "s": 25651, "text": "Convert string to char array in C++" }, { "code": null, "e": 25708, "s": 25687, "text": "Iterators in C++ STL" }, { "code": null, "e": 25732, "s": 25708, "text": "Inline Functions in C++" }, { "code": null, "e": 25776, "s": 25732, "text": "List in C++ Standard Template Library (STL)" } ]
Data Cleaning in R Made Simple. The title says it all. | by Emily Burns | Towards Data Science
Data cleaning. The process of identifying, correcting, or removing inaccurate raw data for downstream purposes. Or, more colloquially, an unglamorous yet wholely necessary first step towards an analysis-ready dataset. Data cleaning may not be the sexiest task in a data scientist’s day but never underestimate its ability to make or break a statistically-driven project. To elaborate, let’s instead think of data cleaning as the preparation of a blank canvas that brushstrokes of exploratory data analysis and statistical modeling paint will soon fully bring to life. If your canvas isn’t initially cleaned and properly fitted to project aims, the following interpretations of your art will remain muddled no matter how beautifully you paint. It is the same with data science projects. If your data is poorly prepped, unreliable results can plague your work no matter how cutting-edge your statistical artistry may be. Which, for anyone who translates data into company or academic value for a living, is a terrifying prospect. As the age-old saying goes: Garbage in, garbage out Unfortunately, real-world data cleaning can be an involved process. Much of preprocessing is data-dependent, with inaccurate observations and patterns of missing values often unique to each project and its method of data collection. This can hold especially true when data is entered by hand (data verification, anyone?) or is a product of unstandardized, free response (think scraped tweets or observational data from fields such as Conservation and Psychology). However, “involved” doesn’t have to translate to “lost.” Yes, every data frame is different. And yes, data cleaning techniques are dependent on personal data-wrangling preferences. But, rather than feeling overwhelmed by these unknowns or unsure of what really constitutes as “clean” data, there are a few general steps you can take to ensure your canvas will be ready for statistical paint in no time. TL;DR: Data cleaning can sound scary, but invalid findings are scarier. The following are a few tools and tips to help keep data cleaning steps clear and simple. Let’s get started. R is a wonderful tool for dealing with data. Packages like tidyverse make complex data manipulation nearly painless and, as the lingua franca of statistics, it’s a natural place to start for many data scientists and social science researchers (like myself). That said, it is by no means the only tool for data cleaning. It’s just the one we’ll be using here. For alternative data cleaning tools, check out these articles for Python, SQL, and language-neutral approaches. No matter how useful R is, your canvas will still be poorly prepped if you miss a staple data cleaning step. To keep it as simple as possible, here is a checklist of best practices you should always consider when cleaning raw data: Familiarize yourself with the data setCheck for structural errorsCheck for data irregularitiesDecide how to deal with missing valuesDocument data versions and changes made Familiarize yourself with the data set Check for structural errors Check for data irregularities Decide how to deal with missing values Document data versions and changes made Don’t worry if these steps are still a bit hazy. Each one will be covered in greater detail using the example dataset below. A toolbox and checklist are cool, but real-world applications of both are where true learning occurs. Throughout the following, we’ll go over each of the data cleaning checklist steps in sequential order. To demonstrate these steps, we’ll be using the “Mental Health in Tech Survey” dataset currently available on Kaggle, along with related snippets of R code. An important “pre-data cleaning” step is domain knowledge. If you’re working on a project related to the sleep patterns of Potoos in the Amazon but have no idea what a Potoo actually is, chances are you aren’t going to have a good grasp on what your variables mean, which ones are important, or what values might need some serious cleaning. The short of it: Be sure to read up or ask an expert before diving into data cleaning if your variables don’t make sense to you at first. To stay within my own realm of clinical psychology, I’ll be using the aforementioned “Mental Health in Tech Survey” dataset, a series of 2016 survey responses aiming to capture mental health statuses and workplace attitudes among tech employees. For more insight on the data, check out the original source here. Knowing your dataset well from file size to data types is another crucial step prior to hands-on data cleaning. Nothing is more annoying than realizing a central feature is cluttered with noise or discovering a shortage of RAM partway through your analyses. To avoid this, we can make some quick, initial steps to determine what will probably need extra attention. To determine the size of the data file before opening, we can use: file.info("~/YourDirectoryHere/mental-heath-in-tech-2016_20161114.csv")$size The data file we’re utilizing is 1104203 bytes (or 1.01 MB), not a big data venture by any means. RAM shortages most likely won’t be an issue here. #an initial look at the data framestr(df) From the output, we can also see that the data frame consists of 1433 observations (rows) and 63 variables (columns). Each variable’s name and data type is also listed. We’ll come back to this information in Step 2. Quick and dirty methods like the ones above can be an effective way to initially familiarize yourself with what’s on hand. But keep in mind these functions are the tip of the exploratory-type data analysis iceberg. Check out this resource for a sneak-peak of EDA in R beyond what’s covered here. Now that we have a feel for the data, we’ll evaluate the data frame for structural errors. These include entry errors such as faulty data types, non-unique ID numbers, mislabeled variables, and string inconsistencies. If there are more structural pitfalls in your own dataset than the ones covered below, be sure to include additional steps in your data cleaning to address the idiosyncrasies. a) Mislabeled variables: View all variable labels with the names() function. Our example dataset has long labels that will be difficult to call in the code to come. We can modify them with dplyr’s rename() like so: df <- df %>% rename(employees = How.many.employees.does.your.company.or.organization.have.)colnames(df)[2] b) Faulty data types: These can be determined by either the str() function utilized in Step 1 or the more explicit typeof() function. There are several incorrect data types in this dataset, but let’s continue using the “employees” variable to demonstrate how to identify and update these errors: typeof(df$employees) “Character” is returned but the variable should in fact be a factor with 5 levels: “6–25”, “26–100”, “100–500”, “500–1000”, and “More than 1000”. We can use the as.factor() function to change the data type accordingly: df$employees <- as.factor(df$employees) c) Non-unique ID numbers: This particular dataset doesn’t have ID labels, responders instead identified by row number. If ID numbers were included, however, we could remove duplicates with the duplicated() function or dplyr’s distinct() function like so: #with duplicated()df <- df[!duplicated(df$ID_Column_Name), ]#with distinct()df <- df %>% distinct(ID_Column_Name, .keep_all = TRUE) d) String inconsistencies: This includes typos, capitalization errors, misplaced punctuation, or similar character data errors that might interfere with data analysis. Take for instance our “gender” column. unique(df$gender) The output goes on. There are in fact 72 unique responses in total. As we can see, there is variation due to inconsistent capitalization and term abbreviation. To unify these responses, we can use regular expressions in combination with gsub() to identify common character patterns and convert all female-identifying responses to the dummy coded value “1” and all male-identifying responses to “0”. df$gender <- gsub("(?i)F|(?i)Female", "1", df$gender)df$gender <- gsub("(?i)M|(?i)Male", "0", df$gender) Regular expressions vary greatly according to string data. Check out this regular expression cheat sheet for R here for more insight on how to use them. Also, beware of missing values erroneously represented by character “NA” values rather than NA data types. Fix instances with the following code: df <- df %>% na_if(gender, "NA") Next, we’ll evaluate the dataset for irregularities, which consist of accuracy concerns like invalid values and outliers. Again, these are two common pitfalls in messy data frames, but be aware of irregularities specific to your own data. a) Invalid values: These are responses that don’t make logical sense. For example, the first question in our dataset (“Are you self-employed?”) should align with the second (“How many employees does your company or organization have?”). If there is a “1” in the first column indicating that the individual is self-employed, there should be an “NA” in the second column as he or she doesn’t work for a company. Another common example is age. Our dataset consists of responses from tech employees, meaning anyone reporting an age older than 80 or younger than 15 is likely to be an entry error. Let’s take a look: It is safe to say that a 3-yr-old and 323-yr-old did not complete an employee survey. To remove the invalid entries, we can use the following code: df <- df[-c(which(df$age > 80 | df$age < 15)), ] b) Outliers: This is a topic with much debate. Check out the Wikipedia article for an in-depth overview of what can constitute an outlier. After a little feature engineering (check out the full data cleaning script here for reference), our dataset has 3 continuous variables: age, the number of diagnosed mental illnesses each respondent has, and the number of believed mental illnesses each respondent has. To get a feeling for how the data is distributed, we can plot histograms for each variable: Both “total_dx” and “total_dx_belief” are heavily skewed. If we wanted to mitigate the impact of extreme outliers, there are 3 common ways to do so: delete the outlier, replace the value (aka Winsorize), or do nothing. Delete the observation: Locate and remove the observation with the extreme value. This is common when dealing with extreme values that are clearly the result of human entry error (like the 323-year value previously entered in our “age” column). However, be careful when this is not the case as deleting observations can lead to a loss of important information. Winsorize: When an outlier is negatively impacting your model assumptions or results, you may want to replace it with a less extreme maximum value. In Winsorizing, values outside a predetermined percentile of the data are identified and set to said percentile. The following is an example of 95% Winsorization with our dataset: #looking at number of values above 95th percentile sum(df$total_dx > quantile(df$total_dx, .95))df <- df %>% mutate(wins_total_dx = Winsorize(total_dx)) Do nothing: Yep, just... do nothing. This is the best approach if the outliers, although extreme, hold important information relevant to your project aims. This is the approach we’ll take with our “total_dx” variable as the number of reported mental illnesses for each respondent has the potential to be an important predictor of tech employees’ attitudes towards mental health. An additional note: It may be the era of big data, but small sample sizes are still a stark reality for those within clinical fields, myself included. If this is also your reality, take extra care with outliers as their effect on the sample mean, standard deviation, and variance increases as sample size decreases. I’ll cut straight to the chase here: There is no single “best” way to deal with missing values in a data set. This can sound daunting, but understanding your data and domain subject (recall Step 1?) can come in handy. If you know your data well, chances are you’ll have a decent idea of what method will best apply to your specific scenario too. Most of our dataset’s NA values are due to dependent responses (i.e. if you respond with “Yes” to one question, you can skip the following), rather than human error. This variance is widely explained by the diverging response patterns generated by self-employed and company-employed directed questions. After splitting the dataset into two frames (one for company-employed respondees and one for self-employed respondees), we calculate the total missing values for the company-employed specific dataset: sum(is.na(df))#percent missing values per variableapply(df, 2, function(col)sum(is.na(col))/length(col)) It may look like a lot of missing values, but, upon further inspection, the only columns with missing values are those directed at self-employed respondees (for instance, “Do you have medical coverage (private insurance or state-provided) which includes treatment of mental health issues?”). Missing values in this variable should be expected in our company-employed dataset as they are instead covered by company policy. Which leads us to the first option: a) Remove the variable. Delete the column with the NA value(s). In projects with large amounts of data and few missing values, this may be a valid approach. It is also acceptable in our case, where the self-employed variables add no significant information to our company-employed dataset. However, if you’re dealing with a smaller dataset and/or a multitude of NA values, keep in mind removing variables can result in a significant loss of information. b) Remove the observation. Delete the row with the NA value. Again, this may be an acceptable approach in large projects but beware of the potential loss of valuable information. To remove observations with missing values, we can easily employ the dplyr library again: #identifying the rows with NAsrownames(df)[apply(df, 2, anyNA)]#removing all observations with NAsdf_clean <- df %>% na.omit() c) Impute the missing value. Substitute NA values with inferred replacement values. We can do so using the mean, median, or mode of a given variable like so: for(i in 1:ncol(df)){ df[is.na(df[,i]), i] <- mean(df[,i], na.rm = TRUE)} We can additionally impute continuous values using predictive methods such as linear regression, or impute categorical values using methods like logistic regression or ANOVA. Multiple imputation with libraries such as MICE can also be used with either continuous or categorical data. When implementing these methods, be aware that the results can be misleading if there is no relationship between the missing value and dataset attributes. You can learn more about these techniques and their related R packages here. KNN imputation offers yet another probable alternative to imputing either continuous or categorical missing values, but keep in mind it can be time-consuming and highly dependent on the chosen k-value. #imputing missing values with the caret package's knn methoddf_preprocess <- preProcess(df %>% dplyr::select(primary_role), method = c("knnImpute"), k = 10, knnSummary = mean)df_impute <- predict(df_preprocess, df, na.action = na.pass) d) Use algorithms that support missing values. Some algorithms will break if used with NA values, others won’t. If you want to keep the NA’s in your dataset, consider using algorithms that can process missing values such as linear regression, k-Nearest Neighbors, or XGBoost. This decision will also strongly depend on long-term project aims. Let’s say it loud and clear for the folks in the back: Good research is reproducible research. If you or a third party cannot reproduce the same clean dataset from the same raw dataset you used, you (or anyone else) cannot validate your findings. Clear documentation is a crucial facet of good data cleaning. Why did you make the changes that you did? How did you do them? What version of the raw data did you use? These are all important questions you need to be able to answer. Tools like R Markdown and RPubs can seamlessly weave documentation into your R project. Check them out if you’re not already familiar. Your future self will thank you. For those of you who made it this far, thanks for reading! Throughout the post, we clarified the essential data cleaning steps and potential ways to approach them in R with the help of a simple checklist and real-dataset application. For further insight, you can find the full R script at my GitHub repo here. And remember, although this guideline is an effective anchor, data cleaning is a process strongly predicted by the dataset and long-term statistical aims at hand. Don’t be afraid to get creative with it! The canvas can quickly become a work of art itself 🎨
[ { "code": null, "e": 543, "s": 172, "text": "Data cleaning. The process of identifying, correcting, or removing inaccurate raw data for downstream purposes. Or, more colloquially, an unglamorous yet wholely necessary first step towards an analysis-ready dataset. Data cleaning may not be the sexiest task in a data scientist’s day but never underestimate its ability to make or break a statistically-driven project." }, { "code": null, "e": 915, "s": 543, "text": "To elaborate, let’s instead think of data cleaning as the preparation of a blank canvas that brushstrokes of exploratory data analysis and statistical modeling paint will soon fully bring to life. If your canvas isn’t initially cleaned and properly fitted to project aims, the following interpretations of your art will remain muddled no matter how beautifully you paint." }, { "code": null, "e": 1200, "s": 915, "text": "It is the same with data science projects. If your data is poorly prepped, unreliable results can plague your work no matter how cutting-edge your statistical artistry may be. Which, for anyone who translates data into company or academic value for a living, is a terrifying prospect." }, { "code": null, "e": 1252, "s": 1200, "text": "As the age-old saying goes: Garbage in, garbage out" }, { "code": null, "e": 1716, "s": 1252, "text": "Unfortunately, real-world data cleaning can be an involved process. Much of preprocessing is data-dependent, with inaccurate observations and patterns of missing values often unique to each project and its method of data collection. This can hold especially true when data is entered by hand (data verification, anyone?) or is a product of unstandardized, free response (think scraped tweets or observational data from fields such as Conservation and Psychology)." }, { "code": null, "e": 2119, "s": 1716, "text": "However, “involved” doesn’t have to translate to “lost.” Yes, every data frame is different. And yes, data cleaning techniques are dependent on personal data-wrangling preferences. But, rather than feeling overwhelmed by these unknowns or unsure of what really constitutes as “clean” data, there are a few general steps you can take to ensure your canvas will be ready for statistical paint in no time." }, { "code": null, "e": 2281, "s": 2119, "text": "TL;DR: Data cleaning can sound scary, but invalid findings are scarier. The following are a few tools and tips to help keep data cleaning steps clear and simple." }, { "code": null, "e": 2300, "s": 2281, "text": "Let’s get started." }, { "code": null, "e": 2659, "s": 2300, "text": "R is a wonderful tool for dealing with data. Packages like tidyverse make complex data manipulation nearly painless and, as the lingua franca of statistics, it’s a natural place to start for many data scientists and social science researchers (like myself). That said, it is by no means the only tool for data cleaning. It’s just the one we’ll be using here." }, { "code": null, "e": 2771, "s": 2659, "text": "For alternative data cleaning tools, check out these articles for Python, SQL, and language-neutral approaches." }, { "code": null, "e": 3003, "s": 2771, "text": "No matter how useful R is, your canvas will still be poorly prepped if you miss a staple data cleaning step. To keep it as simple as possible, here is a checklist of best practices you should always consider when cleaning raw data:" }, { "code": null, "e": 3175, "s": 3003, "text": "Familiarize yourself with the data setCheck for structural errorsCheck for data irregularitiesDecide how to deal with missing valuesDocument data versions and changes made" }, { "code": null, "e": 3214, "s": 3175, "text": "Familiarize yourself with the data set" }, { "code": null, "e": 3242, "s": 3214, "text": "Check for structural errors" }, { "code": null, "e": 3272, "s": 3242, "text": "Check for data irregularities" }, { "code": null, "e": 3311, "s": 3272, "text": "Decide how to deal with missing values" }, { "code": null, "e": 3351, "s": 3311, "text": "Document data versions and changes made" }, { "code": null, "e": 3476, "s": 3351, "text": "Don’t worry if these steps are still a bit hazy. Each one will be covered in greater detail using the example dataset below." }, { "code": null, "e": 3578, "s": 3476, "text": "A toolbox and checklist are cool, but real-world applications of both are where true learning occurs." }, { "code": null, "e": 3837, "s": 3578, "text": "Throughout the following, we’ll go over each of the data cleaning checklist steps in sequential order. To demonstrate these steps, we’ll be using the “Mental Health in Tech Survey” dataset currently available on Kaggle, along with related snippets of R code." }, { "code": null, "e": 4178, "s": 3837, "text": "An important “pre-data cleaning” step is domain knowledge. If you’re working on a project related to the sleep patterns of Potoos in the Amazon but have no idea what a Potoo actually is, chances are you aren’t going to have a good grasp on what your variables mean, which ones are important, or what values might need some serious cleaning." }, { "code": null, "e": 4316, "s": 4178, "text": "The short of it: Be sure to read up or ask an expert before diving into data cleaning if your variables don’t make sense to you at first." }, { "code": null, "e": 4628, "s": 4316, "text": "To stay within my own realm of clinical psychology, I’ll be using the aforementioned “Mental Health in Tech Survey” dataset, a series of 2016 survey responses aiming to capture mental health statuses and workplace attitudes among tech employees. For more insight on the data, check out the original source here." }, { "code": null, "e": 4886, "s": 4628, "text": "Knowing your dataset well from file size to data types is another crucial step prior to hands-on data cleaning. Nothing is more annoying than realizing a central feature is cluttered with noise or discovering a shortage of RAM partway through your analyses." }, { "code": null, "e": 5060, "s": 4886, "text": "To avoid this, we can make some quick, initial steps to determine what will probably need extra attention. To determine the size of the data file before opening, we can use:" }, { "code": null, "e": 5137, "s": 5060, "text": "file.info(\"~/YourDirectoryHere/mental-heath-in-tech-2016_20161114.csv\")$size" }, { "code": null, "e": 5285, "s": 5137, "text": "The data file we’re utilizing is 1104203 bytes (or 1.01 MB), not a big data venture by any means. RAM shortages most likely won’t be an issue here." }, { "code": null, "e": 5327, "s": 5285, "text": "#an initial look at the data framestr(df)" }, { "code": null, "e": 5543, "s": 5327, "text": "From the output, we can also see that the data frame consists of 1433 observations (rows) and 63 variables (columns). Each variable’s name and data type is also listed. We’ll come back to this information in Step 2." }, { "code": null, "e": 5839, "s": 5543, "text": "Quick and dirty methods like the ones above can be an effective way to initially familiarize yourself with what’s on hand. But keep in mind these functions are the tip of the exploratory-type data analysis iceberg. Check out this resource for a sneak-peak of EDA in R beyond what’s covered here." }, { "code": null, "e": 6233, "s": 5839, "text": "Now that we have a feel for the data, we’ll evaluate the data frame for structural errors. These include entry errors such as faulty data types, non-unique ID numbers, mislabeled variables, and string inconsistencies. If there are more structural pitfalls in your own dataset than the ones covered below, be sure to include additional steps in your data cleaning to address the idiosyncrasies." }, { "code": null, "e": 6448, "s": 6233, "text": "a) Mislabeled variables: View all variable labels with the names() function. Our example dataset has long labels that will be difficult to call in the code to come. We can modify them with dplyr’s rename() like so:" }, { "code": null, "e": 6555, "s": 6448, "text": "df <- df %>% rename(employees = How.many.employees.does.your.company.or.organization.have.)colnames(df)[2]" }, { "code": null, "e": 6851, "s": 6555, "text": "b) Faulty data types: These can be determined by either the str() function utilized in Step 1 or the more explicit typeof() function. There are several incorrect data types in this dataset, but let’s continue using the “employees” variable to demonstrate how to identify and update these errors:" }, { "code": null, "e": 6872, "s": 6851, "text": "typeof(df$employees)" }, { "code": null, "e": 7091, "s": 6872, "text": "“Character” is returned but the variable should in fact be a factor with 5 levels: “6–25”, “26–100”, “100–500”, “500–1000”, and “More than 1000”. We can use the as.factor() function to change the data type accordingly:" }, { "code": null, "e": 7131, "s": 7091, "text": "df$employees <- as.factor(df$employees)" }, { "code": null, "e": 7386, "s": 7131, "text": "c) Non-unique ID numbers: This particular dataset doesn’t have ID labels, responders instead identified by row number. If ID numbers were included, however, we could remove duplicates with the duplicated() function or dplyr’s distinct() function like so:" }, { "code": null, "e": 7518, "s": 7386, "text": "#with duplicated()df <- df[!duplicated(df$ID_Column_Name), ]#with distinct()df <- df %>% distinct(ID_Column_Name, .keep_all = TRUE)" }, { "code": null, "e": 7686, "s": 7518, "text": "d) String inconsistencies: This includes typos, capitalization errors, misplaced punctuation, or similar character data errors that might interfere with data analysis." }, { "code": null, "e": 7725, "s": 7686, "text": "Take for instance our “gender” column." }, { "code": null, "e": 7743, "s": 7725, "text": "unique(df$gender)" }, { "code": null, "e": 8142, "s": 7743, "text": "The output goes on. There are in fact 72 unique responses in total. As we can see, there is variation due to inconsistent capitalization and term abbreviation. To unify these responses, we can use regular expressions in combination with gsub() to identify common character patterns and convert all female-identifying responses to the dummy coded value “1” and all male-identifying responses to “0”." }, { "code": null, "e": 8247, "s": 8142, "text": "df$gender <- gsub(\"(?i)F|(?i)Female\", \"1\", df$gender)df$gender <- gsub(\"(?i)M|(?i)Male\", \"0\", df$gender)" }, { "code": null, "e": 8400, "s": 8247, "text": "Regular expressions vary greatly according to string data. Check out this regular expression cheat sheet for R here for more insight on how to use them." }, { "code": null, "e": 8546, "s": 8400, "text": "Also, beware of missing values erroneously represented by character “NA” values rather than NA data types. Fix instances with the following code:" }, { "code": null, "e": 8579, "s": 8546, "text": "df <- df %>% na_if(gender, \"NA\")" }, { "code": null, "e": 8818, "s": 8579, "text": "Next, we’ll evaluate the dataset for irregularities, which consist of accuracy concerns like invalid values and outliers. Again, these are two common pitfalls in messy data frames, but be aware of irregularities specific to your own data." }, { "code": null, "e": 9228, "s": 8818, "text": "a) Invalid values: These are responses that don’t make logical sense. For example, the first question in our dataset (“Are you self-employed?”) should align with the second (“How many employees does your company or organization have?”). If there is a “1” in the first column indicating that the individual is self-employed, there should be an “NA” in the second column as he or she doesn’t work for a company." }, { "code": null, "e": 9430, "s": 9228, "text": "Another common example is age. Our dataset consists of responses from tech employees, meaning anyone reporting an age older than 80 or younger than 15 is likely to be an entry error. Let’s take a look:" }, { "code": null, "e": 9578, "s": 9430, "text": "It is safe to say that a 3-yr-old and 323-yr-old did not complete an employee survey. To remove the invalid entries, we can use the following code:" }, { "code": null, "e": 9627, "s": 9578, "text": "df <- df[-c(which(df$age > 80 | df$age < 15)), ]" }, { "code": null, "e": 9766, "s": 9627, "text": "b) Outliers: This is a topic with much debate. Check out the Wikipedia article for an in-depth overview of what can constitute an outlier." }, { "code": null, "e": 10127, "s": 9766, "text": "After a little feature engineering (check out the full data cleaning script here for reference), our dataset has 3 continuous variables: age, the number of diagnosed mental illnesses each respondent has, and the number of believed mental illnesses each respondent has. To get a feeling for how the data is distributed, we can plot histograms for each variable:" }, { "code": null, "e": 10346, "s": 10127, "text": "Both “total_dx” and “total_dx_belief” are heavily skewed. If we wanted to mitigate the impact of extreme outliers, there are 3 common ways to do so: delete the outlier, replace the value (aka Winsorize), or do nothing." }, { "code": null, "e": 10707, "s": 10346, "text": "Delete the observation: Locate and remove the observation with the extreme value. This is common when dealing with extreme values that are clearly the result of human entry error (like the 323-year value previously entered in our “age” column). However, be careful when this is not the case as deleting observations can lead to a loss of important information." }, { "code": null, "e": 11035, "s": 10707, "text": "Winsorize: When an outlier is negatively impacting your model assumptions or results, you may want to replace it with a less extreme maximum value. In Winsorizing, values outside a predetermined percentile of the data are identified and set to said percentile. The following is an example of 95% Winsorization with our dataset:" }, { "code": null, "e": 11188, "s": 11035, "text": "#looking at number of values above 95th percentile sum(df$total_dx > quantile(df$total_dx, .95))df <- df %>% mutate(wins_total_dx = Winsorize(total_dx))" }, { "code": null, "e": 11567, "s": 11188, "text": "Do nothing: Yep, just... do nothing. This is the best approach if the outliers, although extreme, hold important information relevant to your project aims. This is the approach we’ll take with our “total_dx” variable as the number of reported mental illnesses for each respondent has the potential to be an important predictor of tech employees’ attitudes towards mental health." }, { "code": null, "e": 11883, "s": 11567, "text": "An additional note: It may be the era of big data, but small sample sizes are still a stark reality for those within clinical fields, myself included. If this is also your reality, take extra care with outliers as their effect on the sample mean, standard deviation, and variance increases as sample size decreases." }, { "code": null, "e": 11993, "s": 11883, "text": "I’ll cut straight to the chase here: There is no single “best” way to deal with missing values in a data set." }, { "code": null, "e": 12229, "s": 11993, "text": "This can sound daunting, but understanding your data and domain subject (recall Step 1?) can come in handy. If you know your data well, chances are you’ll have a decent idea of what method will best apply to your specific scenario too." }, { "code": null, "e": 12733, "s": 12229, "text": "Most of our dataset’s NA values are due to dependent responses (i.e. if you respond with “Yes” to one question, you can skip the following), rather than human error. This variance is widely explained by the diverging response patterns generated by self-employed and company-employed directed questions. After splitting the dataset into two frames (one for company-employed respondees and one for self-employed respondees), we calculate the total missing values for the company-employed specific dataset:" }, { "code": null, "e": 12838, "s": 12733, "text": "sum(is.na(df))#percent missing values per variableapply(df, 2, function(col)sum(is.na(col))/length(col))" }, { "code": null, "e": 13260, "s": 12838, "text": "It may look like a lot of missing values, but, upon further inspection, the only columns with missing values are those directed at self-employed respondees (for instance, “Do you have medical coverage (private insurance or state-provided) which includes treatment of mental health issues?”). Missing values in this variable should be expected in our company-employed dataset as they are instead covered by company policy." }, { "code": null, "e": 13296, "s": 13260, "text": "Which leads us to the first option:" }, { "code": null, "e": 13586, "s": 13296, "text": "a) Remove the variable. Delete the column with the NA value(s). In projects with large amounts of data and few missing values, this may be a valid approach. It is also acceptable in our case, where the self-employed variables add no significant information to our company-employed dataset." }, { "code": null, "e": 13750, "s": 13586, "text": "However, if you’re dealing with a smaller dataset and/or a multitude of NA values, keep in mind removing variables can result in a significant loss of information." }, { "code": null, "e": 14019, "s": 13750, "text": "b) Remove the observation. Delete the row with the NA value. Again, this may be an acceptable approach in large projects but beware of the potential loss of valuable information. To remove observations with missing values, we can easily employ the dplyr library again:" }, { "code": null, "e": 14146, "s": 14019, "text": "#identifying the rows with NAsrownames(df)[apply(df, 2, anyNA)]#removing all observations with NAsdf_clean <- df %>% na.omit()" }, { "code": null, "e": 14304, "s": 14146, "text": "c) Impute the missing value. Substitute NA values with inferred replacement values. We can do so using the mean, median, or mode of a given variable like so:" }, { "code": null, "e": 14379, "s": 14304, "text": "for(i in 1:ncol(df)){ df[is.na(df[,i]), i] <- mean(df[,i], na.rm = TRUE)}" }, { "code": null, "e": 14895, "s": 14379, "text": "We can additionally impute continuous values using predictive methods such as linear regression, or impute categorical values using methods like logistic regression or ANOVA. Multiple imputation with libraries such as MICE can also be used with either continuous or categorical data. When implementing these methods, be aware that the results can be misleading if there is no relationship between the missing value and dataset attributes. You can learn more about these techniques and their related R packages here." }, { "code": null, "e": 15097, "s": 14895, "text": "KNN imputation offers yet another probable alternative to imputing either continuous or categorical missing values, but keep in mind it can be time-consuming and highly dependent on the chosen k-value." }, { "code": null, "e": 15414, "s": 15097, "text": "#imputing missing values with the caret package's knn methoddf_preprocess <- preProcess(df %>% dplyr::select(primary_role), method = c(\"knnImpute\"), k = 10, knnSummary = mean)df_impute <- predict(df_preprocess, df, na.action = na.pass)" }, { "code": null, "e": 15757, "s": 15414, "text": "d) Use algorithms that support missing values. Some algorithms will break if used with NA values, others won’t. If you want to keep the NA’s in your dataset, consider using algorithms that can process missing values such as linear regression, k-Nearest Neighbors, or XGBoost. This decision will also strongly depend on long-term project aims." }, { "code": null, "e": 16004, "s": 15757, "text": "Let’s say it loud and clear for the folks in the back: Good research is reproducible research. If you or a third party cannot reproduce the same clean dataset from the same raw dataset you used, you (or anyone else) cannot validate your findings." }, { "code": null, "e": 16405, "s": 16004, "text": "Clear documentation is a crucial facet of good data cleaning. Why did you make the changes that you did? How did you do them? What version of the raw data did you use? These are all important questions you need to be able to answer. Tools like R Markdown and RPubs can seamlessly weave documentation into your R project. Check them out if you’re not already familiar. Your future self will thank you." }, { "code": null, "e": 16464, "s": 16405, "text": "For those of you who made it this far, thanks for reading!" }, { "code": null, "e": 16715, "s": 16464, "text": "Throughout the post, we clarified the essential data cleaning steps and potential ways to approach them in R with the help of a simple checklist and real-dataset application. For further insight, you can find the full R script at my GitHub repo here." } ]
A Comprehensive Guide to Pandas’ Advanced Features in 20 Minutes | by Fabian Bosler | Towards Data Science
I am going out on a limb here and assume that red pandas are smarter and thus more advanced than their black-and-white brethren. Hence, the cover picture. In Part I of this Pandas series, we explored the basics of Pandas, including: How to load data; How to inspect, sort, and filter data; How to analyze data using and groupby/transform If those concepts are new to you, head back to Part I, and get a quick refresher. towardsdatascience.com Data Types and ConversionsUseful accessor methods for certain data typesCombining DataFramesReshaping DataFrames Data Types and Conversions Useful accessor methods for certain data types Combining DataFrames Reshaping DataFrames A Python environment (I suggest Jupyter Notebook). If you haven’t set this up, don’t worry. It is effortless and takes less than 10 minutes. towardsdatascience.com Before doing any data manipulation, let’s get some data. We will be using some fictitious sales data. This GitHub Repo holds the data and the code for this article. Create a new notebook and import Pandas (import pandas as pd). I tend to adjust my notebook settings a bit like this: from IPython.core.display import display, HTMLdisplay(HTML("<style>.container {width:90% !important;}</style>")) These commands make the Notebookwider and thus utilize more space on the screen (typically the notebook has a fixed width, which sucks with wide screens). invoices = pd.read_csv('https://raw.githubusercontent.com/FBosler/you-datascientist/master/invoices.csv') Before diving into the data, let’s quickly summarize all the available Pandas data types. In total, there are seven types: object : This data type is used for strings (i.e., sequences of characters) int64 : Used for integers (whole numbers, no decimals) float64 : Used for floating-point numbers (i.e., figures with decimals/fractions) bool : Used for values that can only be True/False datetime64 : Used for date and time values timedelta : Used to represent the difference between datetimes category : Used for values that take one out of a limited number of available options (categories don’t have to, but can have explicit ordering) After reading the data and running a quick invoices.sample(5) we observe that the dataset seems to be fairly large, but well structured. To get a feel for the data, I would usually follow a first sample up with info and describe, but we are here to learn about data types and will skip the typical exploration steps for now. Not surprisingly, there is a command to print out the data types of a DataFrame. IN:invoices.dtypesOUT:Order Id objectDate objectMeal Id objectCompany Id objectDate of Meal objectParticipants objectMeal Price float64Type of Meal objectSuper Hero Present booldtype: object We loaded the data without any type-conversion, so Pandas made its best guess when assigning types. We can see that all columns, but Meal Price and Super Hero Present are of the type object (i.e., string). From the quick inspection we did earlier, it seems like some of the columns could have been assigned a more explicit data type. So let’s change that. There are two standard ways of converting pandas data types: <column>.astype(<desired type>) conversion helper functions, like pd.to_numeric or pd.to_datetime astype is quick and works well with clean data and when the conversion is straight forward, e.g., from int64 to float64 (or vice versa). astype has to be called directly on the column that you want to convert. Like this: invoices['Type of Meal'] = invoices['Type of Meal'].astype('category')invoices['Date'] = invoices['Date'].astype('datetime64')invoices['Meal Price'] = invoices['Meal Price'].astype('int') To validate the effect of our type conversion we just run invoices.dtypes again: OUT:Order Id objectDate datetime64[ns]Meal Id objectCompany Id objectDate of Meal objectParticipants objectMeal Price int64Type of Meal categorySuper Hero Present booldtype: object Note: There is a bit of a difference between Pandas versions. For Pandas version 0.23.x it is possible to convert the Date of Meal column by using .astype('datetime64') and Pandas would then automatically convert into UTC. The UTC format is helpful because it is a standardized time format and allows us to subtract or add dates from other dates. However, this does not work any longer for Pandas version 0.25.x where we will get a ValueError that lets us know that Tz-aware (timezone-aware) datetimes can not be converted without further adjustment. There are three pd.to_<some_type> functions, but for me, only two of them come up frequently: pd.to_numeric() pd.to_datetime() pd.to_timedelta() (I can’t remember if I’ve ever used this one, to be honest) Their main advantage over astype, is that it is possible to specify the behavior in case a value is encountered, that can not be converted. Both functions accept an additional parameter errors that defines how errors should be treated. We could choose to ignore errors by passingerrors='ignore' , or turn the offending values into np.nan values by passing errors='coerce'. The default behavior is to raise errors. I find that there is no cutty cutter solution, and I would typically investigate before making a decision. The fewer offending values compared to the number of observations you have, the more likely I am to coerce them. pd.to_numeric()For the sake of argument, let’s mess up our data a bit: invoices.loc[45612,'Meal Price'] = 'I am causing trouble'invoices.loc[35612,'Meal Price'] = 'Me too' invoices['Meal Price'].astype(int) will now fail with a ValueError: invalid literal for int() with base 10: ‘Me too.’ Because there is no obvious way to convert the string into an integer. Whenever I encounter unexpected conversion errors, I typically check the values of the column explicitly to get a better understanding of the magnitude of the strange values. IN:invoices['Meal Price'].apply(lambda x: type(x)).value_counts()OUT:<class 'int'> 49972<class 'str'> 2Name: Meal Price You could then identify the offending rows by doing this: IN:invoices['Meal Price'][invoices['Meal Price'].apply( lambda x: isinstance(x,str))]OUT:35612 Me too45612 I am causing troubleName: Meal Price, dtype: object From there on it is a quick step to either fix the values or make an informed decision about how you want to handle failing conversion. The example above is a prime example, where it would be very reasonable to just convert the values into np.nan by passing errors='coerce' to pd.to_numeric() like this: pd.to_numeric(invoices['Meal Price'], errors='coerce') Now it should be noted that you will by construction have two np.nan value in your data, so it might be a good idea to handle them on the spot. The problem with the np.nan`s is that integer columns don’t know how to handle them. Thus the column will be a float column. # convert the offending values into np.naninvoices['Meal Price'] = pd.to_numeric(invoices['Meal Price'],errors='coerce')# fill np.nan with the median of the datainvoices['Meal Price'] = invoices['Meal Price'].fillna(invoices['Meal Price'].median())# convert the column into integerinvoices['Meal Price'].astype(int) pd.to_datetime()Does what the name implies, the method converts a string into a datetime format. To call to_datetime on a column you would do: pd.to_datetime(invoices['Date of Meal']). Pandas will then guess the format and try to parse the date from the Input. And it does so impressively well: IN:print(pd.to_datetime('2019-8-1'))print(pd.to_datetime('2019/8/1'))print(pd.to_datetime('8/1/2019'))print(pd.to_datetime('Aug, 1 2019'))print(pd.to_datetime('Aug - 1 2019'))print(pd.to_datetime('August - 1 2019'))print(pd.to_datetime('2019, August - 1'))print(pd.to_datetime('20190108'))OUT:2019-08-01 00:00:002019-08-01 00:00:002019-08-01 00:00:002019-08-01 00:00:002019-08-01 00:00:002019-08-01 00:00:002019-08-01 00:00:002019-01-08 00:00:00 However, now and then you might encounter some atypical formatting, like the last example from the list above. In this case, you probably want to provide a custom format, which can you can do like this: pd.to_datetime('20190108',format='%Y%d%m'). Think of the format string as a mask to check against the date string, and if the mask fits, the conversion will take place. Check this link out for a list of all the possible date format components. One additional noteworthy parameter when working with custom formats is exact=False. print(pd.to_datetime('yolo 20190108', format='%Y%d%m', exact=False)) will work, while it would fail without the exact parameter. With exact=False Pandas tries to match the pattern anywhere in the date string. Before moving on let’s convert our Date of Meal column, like this invoices['Date of Meal'] = pd.to_datetime(invoices['Date of Meal'], utc=True) If your only tool is a hammer, every problem looks like a nail. Think of a Pandas accessor as a property that acts as an interface to methods specific to the type you are trying to access. Those methods are highly specialized. They serve one job and one job only. However, they are excellent and extremely concise for that particular job. There are three different accessors: dt str cat All of the methods are accessed by calling .<accessor>.method on the column of choice, like this: invoices['Date of Meal'].dt.date This one I think is the most useful and most straight forward of the accessor methods: date (returns the date of the datetime value), or IN:invoices['Date of Meal'].dt.dateOUT:0 2015-01-291 2017-10-30 ... 49972 2017-09-0649973 2015-08-20Name: Date of Meal, Length: 49974, dtype: object weekday_name (returns the name of the day), month_name() (this is implemented somewhat inconsistently, as weekday_name is a property, but month_name is a method and needs to be called with the parenthesis) IN:invoices['Date of Meal'].dt.weekday_nameOUT:0 Thursday1 Monday ... 49972 Wednesday49973 ThursdayName: Date of Meal, Length: 49974, dtype: objectIN:invoices['Date of Meal'].dt.month_name()OUT:0 January1 October ... 49972 September49973 AugustName: Date of Meal, Length: 49974, dtype: object days_in_month IN:invoices['Date of Meal'].dt.days_in_monthOUT:0 311 31 ..49972 3049973 31Name: Date of Meal, Length: 49974, dtype: int64 nanosecond,microsecond,second,minute,hour ,day, week, month, quarter, year gets the integer of the corresponding frequency. EXAMPLES: (same logic applies for nanosecond, microsecond, second, minute, hour)IN:invoices['Date of Meal'].dt.dayOUT:0 291 30 ..49972 649973 20Name: Date of Meal, Length: 49974, dtype: int64IN:invoices['Date of Meal'].dt.weekOUT:0 51 44 ..49972 3649973 34Name: Date of Meal, Length: 49974, dtype: int64IN:invoices['Date of Meal'].dt.monthOUT:0 11 10 ..49972 949973 8Name: Date of Meal, Length: 49974, dtype: int64IN:invoices['Date of Meal'].dt.quarterOUT:0 11 4 ..49972 349973 3Name: Date of Meal, Length: 49974, dtype: int64IN:invoices['Date of Meal'].dt.yearOUT:0 20151 2017 ... 49972 201749973 2015Name: Date of Meal, Length: 49974, dtype: int64 is_leap_year, is_month_start, is_month_end, is_quarter_start, is_quarter_end, is_year_start, is_year_end returns True or False respectively for each value. See the following example for is_month_end IN:invoices['Date of Meal'].dt.is_month_endOUT:0 False1 False ... 49972 False49973 FalseName: Date of Meal, Length: 49974, dtype: bool We can use the results to filter our data down to only rows, where Date of Meal is at the month's end. to_pydatetime(), which converts the Pandas datetime into a regular Python datetime format (which you might need sometimes) and to_period(<PERIOD>) [available periods are W, M, Q, and Y], which converts the dates into periods. IN:invoices['Date of Meal'].dt.to_pydatetime()OUT:array([datetime.datetime(2015, 1, 29, 8, 0), datetime.datetime(2017, 10, 30, 20, 0), datetime.datetime(2015, 2, 10, 11, 0), ..., datetime.datetime(2017, 3, 7, 19, 0), datetime.datetime(2017, 9, 6, 6, 0), datetime.datetime(2015, 8, 20, 18, 0)], dtype=object)IN:invoices['Date of Meal'].dt.to_period('W')OUT:0 2015-01-26/2015-02-011 2017-10-30/2017-11-05 ... 49972 2017-09-04/2017-09-1049973 2015-08-17/2015-08-23Name: Date of Meal, Length: 49974, dtype: object The str accessor is also quite helpful, not because it enables additional functionality, but makes for much more readable code. lower() / upper() to manage capitalization of strings IN:invoices['Type of Meal'].str.lower()OUT:0 breakfast1 dinner ... 49972 breakfast49973 dinnerName: Type of Meal, Length: 49974, dtype: objectIN:invoices['Type of Meal'].str.upper()OUT:0 BREAKFAST1 DINNER ... 49972 BREAKFAST49973 DINNERName: Type of Meal, Length: 49974, dtype: object ljust(width), rjust(width), center(width), zfill(width) to control the positioning of strings. All of them take a total width of the desired resulting string as an input. ljust, rjust, and center fill the difference to the desired length with whitespaces.zfill adds that many leading zeroes. ljustis left-bound, rjustis right-bound. IN:invoices['Type of Meal'].str.ljust(width=15)OUT:0 Breakfast 1 Dinner ... 49972 Breakfast 49973 Dinner Name: Type of Meal, Length: 49974, dtype: objectIN:invoices['Type of Meal'].str.rjust(width=15)OUT:0 Breakfast1 Dinner ... 49972 Breakfast49973 DinnerName: Type of Meal, Length: 49974, dtype: objectIN:invoices['Type of Meal'].str.center(width=15)OUT:0 Breakfast 1 Dinner ... 49972 Breakfast 49973 Dinner Name: Type of Meal, Length: 49974, dtype: objectIN:invoices['Type of Meal'].str.zfill(width=15)OUT:0 000000Breakfast1 000000000Dinner ... 49972 000000Breakfast49973 000000000DinnerName: Type of Meal, Length: 49974, dtype: object startswith(<substring>), endswith(<substring>), contains(<substring>) checks for the presence of a substring IN:invoices['Type of Meal'].str.endswith('ast')OUT:0 True1 False ... 49972 True49973 FalseName: Type of Meal, Length: 49974, dtype: bool swapcase(), repeat(times) for kicks and giggles IN:invoices['Type of Meal'].str.swapcase()OUT:0 bREAKFAST1 dINNER ... 49972 bREAKFAST49973 dINNERName: Type of Meal, Length: 49974, dtype: objectIN:invoices['Type of Meal'].str.repeat(2)OUT:0 BreakfastBreakfast1 DinnerDinner ... 49972 BreakfastBreakfast49973 DinnerDinnerName: Type of Meal, Length: 49974, dtype: object In my opinion the least powerful of the three, or at least the one I use the most infrequently. cat provides access to a couple of categorial operations, like: ordered lets you know if the column is ordered IN:invoices['Type of Meal'].cat.orderedOUT:False categories to return the categories IN:invoices['Type of Meal'].cat.categoriesOUT:Index(['Breakfast', 'Dinner', 'Lunch'], dtype='object') codes for quick conversion of the category into its numerical representation IN:invoices['Type of Meal'].cat.codesOUT:0 01 12 23 24 2 ..49969 149970 249971 149972 049973 1Length: 49974, dtype: int8 reorder_categories to change the existing order of the categories IN:invoices['Type of Meal'].cat.reorder_categories( ['Lunch','Breakfast','Dinner'])OUT:0 Breakfast1 Dinner2 Lunch3 Lunch4 Lunch ... 49969 Dinner49970 Lunch49971 Dinner49972 Breakfast49973 DinnerName: Type of Meal, Length: 49974, dtype: categoryCategories (3, object): [Lunch, Breakfast, Dinner] Concatenating comes in handy when you have similar data (structurally and in terms of content) spread out across multiple files. You can concatenate data vertically (i.e., stack the data on top of each other) or horizontally (i.e., stack the data next to each other). As an example, imagine that a client provides you one file per month or year of data (because their reporting runs at months end, for example). Those files are conceptually identically and thus a prime example of vertical stacking. Let’s have a look at how we can do this with Python’s Pandas. Let’s artificially split out invoices file by years. # Use dt accessor to count all the yearsIN:invoices['Date of Meal'].dt.year.value_counts().sort_index()OUT:2013 382014 99882015 100602016 99612017 99642018 99312019 32Name: Date of Meal, dtype: int64# Split the data y_2013 = invoices[invoices['Date of Meal'].dt.year == 2013].copy()y_2014 = invoices[invoices['Date of Meal'].dt.year == 2014].copy()y_2015 = invoices[invoices['Date of Meal'].dt.year == 2015].copy()y_2016 = invoices[invoices['Date of Meal'].dt.year == 2016].copy()y_2017 = invoices[invoices['Date of Meal'].dt.year == 2017].copy()y_2018 = invoices[invoices['Date of Meal'].dt.year == 2018].copy()y_2019 = invoices[invoices['Date of Meal'].dt.year == 2019].copy() We use .copy() to make sure that the resulting DataFrames are going to be a copy of the data and not just a reference to the original DataFrame. Let’s validate that the splitting worked. Now for concatenating the data into a unified DataFrame, we would call pd.concat(<LIST OF DATAFRAMES>) like this: pd.concat takes a couple of optional parameters next to the list of DataFrames that you call concat on: axis : 0 for vertical, 1 for horizontal. axis defaults to 0 join : 'inner' for the intersection, 'outer' for the union of indices of the non-concatenating axis. When we use axis=0 and join='inner' we will consider only overlapping columns. When using axis=1 and join='inner' we consider only overlapping indices. In the case of outer non-overlapping columns/indices will be filled with nan values. join defaults to outer ignore_index : True to ignore preexisting indices and instead use labels from 0 to n-1 for the resulting DataFrame. ignore_index defaults to False keys : If we provide a list (has to be the same length as the number of DataFrames) a hierarchical index will be constructed. keys defaults to None. Use keys for example, to add the source of the data. Best used in combination with names. names : Assuming that you provide keys, the names will be used to label the resulting hierarchical index. names defaults to None. A use case for horizontal stacking is a case where you have multiple time series with overlapping but not identical indices. In which case, you wouldn’t want to end up with a DataFrame with potentially thousands of columns, but much rather a DataFrame with thousands of rows. Running the following snippet in Python will result in the following screenshot: range_a = pd.date_range( datetime.datetime(2019,1,2), datetime.datetime(2019,1,8))df_a = pd.DataFrame( index=range_a, data=np.random.randint(2,10,size=len(range_a)), columns=['observations_A'])range_b = pd.date_range( datetime.datetime(2019,1,5), datetime.datetime(2019,1,12))df_b = pd.DataFrame( index=range_b, data=np.random.randint(2,10,size=len(range_b)), columns=['observations_B'])pd.concat([df_a,df_b],axis=1) Note on Append :You might have seen the usage of appendto the same end asconcat. I advise against the usage of appendas it is just a special case of concatand does not provide a benefit over concatenating. Merging, as opposed to concatenating DataFrames together, allows us to combine two DataFrames in a more traditional SQL-query kind of way. When merging DataFrames, most of the time you want some information from one source and another piece of information from another source. Whereas when concatenating your DataFrames are structurally and in terms of content quite similar, and you want to combine them into one unified DataFrame. A simple example I like to use during interviews is something along the lines of: Suppose you have two tables. One table contains the names of your employees and a location id, the other table contains location ids and a city name. How can you get a list of every employee and the city they work in? Merging two DataFrames in Pandas is done with pd.merge. Let’s have a look at the function`s signature (signature means a list of all the possible parameters for the function and typically also the output). I bolded the most relevant parameters. pd.merge( left, right, how='inner', on=None, left_on=None, right_on=None, left_index=False, right_index=False, sort=True, suffixes=('_x', '_y'), copy=True, indicator=False, validate=None) -> pd.DataFrame Let’s go through the parameters one by one: left/right : the left, respectively right, DataFrame you want to merge how : 'left', 'right', 'outer', 'inner'. how defaults to 'inner'. See below a schematic overview of what each of them does. We will discuss specific examples a little bit later. left_index/right_index : If True, use the index from the left/right DataFrame to merge on. left_index/right_index defaults to False on : Column name(s) to merge on. Column name(s) have to exist in both the left and right DataFrame. If not passed and left_index and right_index are False, the intersection of the columns in both DataFrames will be inferred to join on. left_on/right_on : Column name(s) from the left/right DataFrame to join on. Typical use case: Keys you are joining on are differently labeled in your DataFrames. E.g., what is location_id in your left DataFrame, might be _id in your right DataFrame. In this case, you would do left_on='location_id', right_on='_id' . suffixes: A tuple of string suffixes to apply to overlapping columns. suffixes defaults to ('_x', '_y'). I like to use ('_base', '_joined'). Enough theory, let’s have a look at some examples. To do this, we need some additional data to merge on. Load data: # Load some additional Dataorder_data = pd.read_csv('https://raw.githubusercontent.com/FBosler/you-datascientist/master/order_leads.csv', parse_dates=[3])# Note the parse_dates? We need this to have consistent types with invoices, otherwise the subsequent merges would throw errorssales_team = pd.read_csv('https://raw.githubusercontent.com/FBosler/you-datascientist/master/sales_team.csv') Inspect data: We see pretty much right away, that Order ID ,Company ID , and Date appear in multiple of the DataFrames and are thus good candidates to merge on. Let’s merge invoices with order_data and experiment with the parameters a bit. No parameters provided: All parameters will use their defaults. The merge is going to be an inner merge (equivalent to how='inner'). The merge is going to be done on all common columns, i.e., Date, Order Id, and Company Id(equivalent to on=['Date','Order Id','Company Id]).Suffixes are not relevant as all common columns will be used to merge on, so there will no be duplicated columns remaining.Runpd.merge(order_data,invoices) : how='left' : Again, the merge is based on all common columns. Suffixes are not relevant as all common columns will be used to merge on, so there will no be duplicated columns remaining. However, this time around, we merge with how='left' which means that we will take all rows from the left frame and only add data from the right frame where we find some. Runpd.merge(order_data,invoices,how='left') : how='right' : Again, the merge is based on all common columns. Suffixes are not relevant as all common columns will be used to merge on, so there will no be duplicated columns remaining. However, this time around, we merge with how='right' which means that we will take all rows from the right frame and only add data from the left frame where we find some. This case is equivalent to 'inner' in our example as every row in the left DataFrame has a corresponding row in the right DataFrame. Runpd.merge(order_data,invoices,how='right') : how='outer' : Again, the merge is based on all common columns. Suffixes are not relevant as all common columns will be used to merge on, so there will no be duplicated columns remaining. However, this time around, we merge with how='outer'. We take all rows from either, the left or the right DataFrame and add corresponding data where we find some in the other DataFrame. This case is equivalent to 'left' in our example as every row in the left DataFrame has a corresponding row in the right DataFrame. Runpd.merge(order_data,invoices,how='outer') : If we do explicitly provide an on parameter this will override the default behavior and try to find the provided column in both DataFrames. Remaining duplicated columns that are not being used to merge on will be suffixed. In the following example, we only merge on Order Id. However, since the Date and Company Id columns are also present in both DataFrames. Those columns will be sufficed to indicate from which source DataFrame they are originating from as can be seen in the following example. Run: pd.merge(order_data,invoices,on='Order Id') We can also specify custom suffixes like this:pd.merge(order_data,invoices,on='Order Id',suffixes=('_base','_join')) You would typically use the left_on and right_on parameters when the columns are named differently in the two DataFrames. Note on Join :You might have seen the usage of jointo the same end asmerge. join by default merges on the index of both DataFrames. I advise against the usage of joinas it is just a special case of mergeand does not provide a benefit over merging. To wrap up the chapter on combining DataFrames, we should quickly talk about map. map can be called on a DataFrame column or its Index like this: The argument (in our case lookup) for map always has to be a series or a dictionary. While not precisely the same Pandas` series and regular dictionaries share a lot of functionalities and can often be used interchangeably. Like through a dictionary you could loop through a series by calling for k,v in series.items(): . Use pd.concat to “stack” multiple DataFrame on top or next to each other. By default, the stacking is vertical. To overwrite the default use axis=1. By default, stack will carry over all columns/indices. To limit to common columns/indices use join='inner'. Do not use pd.DataFrame.append as it is only a special, limited case of pd.concat and will only make your code less standardized and less coherent. Instead, use pd.concat. Use pd.merge to combine information from two DataFrames. Merge defaults to an inner join and will infer the columns to merge on from the largest subset of common columns across the DataFrames. Do not use pd.DataFrame.join as it is only a special, limited case of pd.merge and will only make your code less standardized and less coherent. Instead, use pd.merge. Use pd.Series.map as a lookup-esque kind of functionality to get the value for a specific index/key from a series/dictionary. Transposing a DataFrame means to swap the index and column. In other words, you are rotating the DataFrame around the origin. Transposing does not change the content of the DataFrame. The DataFrame only changes the orientation. Let’s visualize this with an example: A DataFrame is transposed by simply calling .T on the DataFrame e.g.invoices.T). Melt transforms a DataFrame from wide format to long format. Melt gives flexibility around how the transformation should take place. In other words, melt allows grabbing columns and transforming them into rows while leaving other columns unchanged. Melt is best explained with an example. Let’s create some sample data: melt_experiment = pd.merge( invoices, pd.get_dummies(invoices['Type of Meal']).mul(invoices['Meal Price'].values,axis=0), left_index=True, right_index=True)del melt_experiment['Type of Meal']del melt_experiment['Meal Price']melt_experiment Admittedly, this example is a bit contrived but illustrates the point. We turned the Type of Meal into columns and assigned the prices into the corresponding rows. Now to turn this back into a version where the Type of Meal is a column and the value is the price we could use pd.melt like this: pd.melt( frame=melt_experiment, id_vars=['Order Id', 'Date', 'Meal Id', 'Company Id', 'Date of Meal','Participants', 'Heroes Adjustment'], value_vars=['Breakfast', 'Dinner', 'Lunch'], var_name='Type of Meal', value_name='Expenses') resulting in: Melt is useful to transform a DataFrame into a format where one or more columns are identifier variables (id_vars), while all other columns, considered measured variables (value_vars), are moved to the row axis, leaving just two non-identifier columns. For each column we melt (value_vars), the corresponding existing row is duplicated to accommodate fusing data into a single column and our DataFrame extends. After melting, we have three times as many rows as before (because we used three value_vars and thus triplicated every row). We discussed in the previous article, but a quick recap makes sense here, especially in the light of stacking and unstacking, which we will talk about later. Where transpose and melt leave the content of the DataFrame intact and “only” rearrange the appearance groupby and the following methods are aggregating the data in one form or another. Groupby will result in an aggregated DataFrame with a new index (the values of the columns, by which you are grouping). If you are grouping by more than one value, the resulting DataFrame will have a multi-index. invoices.groupby(['Company Id','Type of Meal']).agg( {'Meal Price':np.mean}) Starting with pandas version 0.25.1, there are also named aggregation, which make groupby a little more readable. invoices.groupby(['Company Id','Type of Meal']).agg( Avg_Price = pd.NamedAgg(column='Meal Price', aggfunc=np.mean)) Resulting in virtually the same as the previous calculation. However, the column is renamed during the process. Pandas also incorporates a pivot_table functionality, not unlike Excel’s Pivot Table. I must admit though, I never use pivot, as I don’t see the advantage over groupby operations. Generally speaking, I think it makes sense to use what you are comfortable with and stick to that. I would advise against mixing different approaches when there is no necessity for doing so. The one good thing pivot_table has in its favor though is margin=True pd.pivot_table( invoices, index=['Company Id','Type of Meal'], values='Meal Price', aggfunc=np.mean, margins=True) The result should look somewhat familiar, as we basically recreated the groupby functionality. However, we get the added benefit of getting the calculated value across all groups in addition to the individual group’s results (as indicated by the last line). We can also specify the columns for the pivot table: pd.pivot_table( invoices, index=['Company Id'], columns=['Type of Meal'], values='Meal Price', aggfunc=np.mean, margins=True) Stack and unstack come in really handy when rearranging your columns and indices. Unstack will by default be called on the outmost level of the index as can be seen nicely in the following example, where calling unstack() turns the Heroes Adjustment Index into two columns. We can also unstack a specific level of the index, like in the following example, where we unstack the Type of Meal column Stacking, on the other hand, does the opposite. Stacking turns columns into rows, but also extends the index in the process (as opposed to melt). Let’s have a look at an example. We have to build some data first where stacking would come in handy. Executing the following code snippet results in a multi-index, multi-level-columns DataFrame. stack_test = invoices.groupby(['Company Id','Type of Meal']).agg({ 'Meal Price':[max,min,np.mean], 'Date of Meal':[max,min],})stack_test If we want to stack this DataFrame, we would call stack_test.stack() and get: Here stack used the outmost level of our multi-level columns and turned it into an index. We now have only single-level columns. Alternatively, we could also call stack with level=0 and get the following result: In this article, you learned how to become a real Pandas Ninja. You learned how to convert data into desired types and between types. You learned how to use unique methods for those types to get access to functionalities, that would otherwise take lines and lines of code. You learned how to combine different DataFrames by just stacking them on top of each other, or logically extracting information from the DataFrames and combining them into something more meaningful. You learned how to flip your DataFrame around as if it were a pancake. You learned to rotate on its origin point, to move columns into rows, to aggregate data through pivot or groupby and then to stack and unstack the results. Good job, and thanks for reading!
[ { "code": null, "e": 327, "s": 172, "text": "I am going out on a limb here and assume that red pandas are smarter and thus more advanced than their black-and-white brethren. Hence, the cover picture." }, { "code": null, "e": 405, "s": 327, "text": "In Part I of this Pandas series, we explored the basics of Pandas, including:" }, { "code": null, "e": 423, "s": 405, "text": "How to load data;" }, { "code": null, "e": 462, "s": 423, "text": "How to inspect, sort, and filter data;" }, { "code": null, "e": 510, "s": 462, "text": "How to analyze data using and groupby/transform" }, { "code": null, "e": 592, "s": 510, "text": "If those concepts are new to you, head back to Part I, and get a quick refresher." }, { "code": null, "e": 615, "s": 592, "text": "towardsdatascience.com" }, { "code": null, "e": 728, "s": 615, "text": "Data Types and ConversionsUseful accessor methods for certain data typesCombining DataFramesReshaping DataFrames" }, { "code": null, "e": 755, "s": 728, "text": "Data Types and Conversions" }, { "code": null, "e": 802, "s": 755, "text": "Useful accessor methods for certain data types" }, { "code": null, "e": 823, "s": 802, "text": "Combining DataFrames" }, { "code": null, "e": 844, "s": 823, "text": "Reshaping DataFrames" }, { "code": null, "e": 985, "s": 844, "text": "A Python environment (I suggest Jupyter Notebook). If you haven’t set this up, don’t worry. It is effortless and takes less than 10 minutes." }, { "code": null, "e": 1008, "s": 985, "text": "towardsdatascience.com" }, { "code": null, "e": 1173, "s": 1008, "text": "Before doing any data manipulation, let’s get some data. We will be using some fictitious sales data. This GitHub Repo holds the data and the code for this article." }, { "code": null, "e": 1291, "s": 1173, "text": "Create a new notebook and import Pandas (import pandas as pd). I tend to adjust my notebook settings a bit like this:" }, { "code": null, "e": 1404, "s": 1291, "text": "from IPython.core.display import display, HTMLdisplay(HTML(\"<style>.container {width:90% !important;}</style>\"))" }, { "code": null, "e": 1559, "s": 1404, "text": "These commands make the Notebookwider and thus utilize more space on the screen (typically the notebook has a fixed width, which sucks with wide screens)." }, { "code": null, "e": 1665, "s": 1559, "text": "invoices = pd.read_csv('https://raw.githubusercontent.com/FBosler/you-datascientist/master/invoices.csv')" }, { "code": null, "e": 1788, "s": 1665, "text": "Before diving into the data, let’s quickly summarize all the available Pandas data types. In total, there are seven types:" }, { "code": null, "e": 1864, "s": 1788, "text": "object : This data type is used for strings (i.e., sequences of characters)" }, { "code": null, "e": 1919, "s": 1864, "text": "int64 : Used for integers (whole numbers, no decimals)" }, { "code": null, "e": 2001, "s": 1919, "text": "float64 : Used for floating-point numbers (i.e., figures with decimals/fractions)" }, { "code": null, "e": 2052, "s": 2001, "text": "bool : Used for values that can only be True/False" }, { "code": null, "e": 2095, "s": 2052, "text": "datetime64 : Used for date and time values" }, { "code": null, "e": 2158, "s": 2095, "text": "timedelta : Used to represent the difference between datetimes" }, { "code": null, "e": 2303, "s": 2158, "text": "category : Used for values that take one out of a limited number of available options (categories don’t have to, but can have explicit ordering)" }, { "code": null, "e": 2440, "s": 2303, "text": "After reading the data and running a quick invoices.sample(5) we observe that the dataset seems to be fairly large, but well structured." }, { "code": null, "e": 2709, "s": 2440, "text": "To get a feel for the data, I would usually follow a first sample up with info and describe, but we are here to learn about data types and will skip the typical exploration steps for now. Not surprisingly, there is a command to print out the data types of a DataFrame." }, { "code": null, "e": 3006, "s": 2709, "text": "IN:invoices.dtypesOUT:Order Id objectDate objectMeal Id objectCompany Id objectDate of Meal objectParticipants objectMeal Price float64Type of Meal objectSuper Hero Present booldtype: object" }, { "code": null, "e": 3362, "s": 3006, "text": "We loaded the data without any type-conversion, so Pandas made its best guess when assigning types. We can see that all columns, but Meal Price and Super Hero Present are of the type object (i.e., string). From the quick inspection we did earlier, it seems like some of the columns could have been assigned a more explicit data type. So let’s change that." }, { "code": null, "e": 3423, "s": 3362, "text": "There are two standard ways of converting pandas data types:" }, { "code": null, "e": 3455, "s": 3423, "text": "<column>.astype(<desired type>)" }, { "code": null, "e": 3521, "s": 3455, "text": "conversion helper functions, like pd.to_numeric or pd.to_datetime" }, { "code": null, "e": 3742, "s": 3521, "text": "astype is quick and works well with clean data and when the conversion is straight forward, e.g., from int64 to float64 (or vice versa). astype has to be called directly on the column that you want to convert. Like this:" }, { "code": null, "e": 3930, "s": 3742, "text": "invoices['Type of Meal'] = invoices['Type of Meal'].astype('category')invoices['Date'] = invoices['Date'].astype('datetime64')invoices['Meal Price'] = invoices['Meal Price'].astype('int')" }, { "code": null, "e": 4011, "s": 3930, "text": "To validate the effect of our type conversion we just run invoices.dtypes again:" }, { "code": null, "e": 4353, "s": 4011, "text": "OUT:Order Id objectDate datetime64[ns]Meal Id objectCompany Id objectDate of Meal objectParticipants objectMeal Price int64Type of Meal categorySuper Hero Present booldtype: object" }, { "code": null, "e": 4700, "s": 4353, "text": "Note: There is a bit of a difference between Pandas versions. For Pandas version 0.23.x it is possible to convert the Date of Meal column by using .astype('datetime64') and Pandas would then automatically convert into UTC. The UTC format is helpful because it is a standardized time format and allows us to subtract or add dates from other dates." }, { "code": null, "e": 4904, "s": 4700, "text": "However, this does not work any longer for Pandas version 0.25.x where we will get a ValueError that lets us know that Tz-aware (timezone-aware) datetimes can not be converted without further adjustment." }, { "code": null, "e": 4998, "s": 4904, "text": "There are three pd.to_<some_type> functions, but for me, only two of them come up frequently:" }, { "code": null, "e": 5014, "s": 4998, "text": "pd.to_numeric()" }, { "code": null, "e": 5031, "s": 5014, "text": "pd.to_datetime()" }, { "code": null, "e": 5109, "s": 5031, "text": "pd.to_timedelta() (I can’t remember if I’ve ever used this one, to be honest)" }, { "code": null, "e": 5523, "s": 5109, "text": "Their main advantage over astype, is that it is possible to specify the behavior in case a value is encountered, that can not be converted. Both functions accept an additional parameter errors that defines how errors should be treated. We could choose to ignore errors by passingerrors='ignore' , or turn the offending values into np.nan values by passing errors='coerce'. The default behavior is to raise errors." }, { "code": null, "e": 5743, "s": 5523, "text": "I find that there is no cutty cutter solution, and I would typically investigate before making a decision. The fewer offending values compared to the number of observations you have, the more likely I am to coerce them." }, { "code": null, "e": 5814, "s": 5743, "text": "pd.to_numeric()For the sake of argument, let’s mess up our data a bit:" }, { "code": null, "e": 5915, "s": 5814, "text": "invoices.loc[45612,'Meal Price'] = 'I am causing trouble'invoices.loc[35612,'Meal Price'] = 'Me too'" }, { "code": null, "e": 6279, "s": 5915, "text": "invoices['Meal Price'].astype(int) will now fail with a ValueError: invalid literal for int() with base 10: ‘Me too.’ Because there is no obvious way to convert the string into an integer. Whenever I encounter unexpected conversion errors, I typically check the values of the column explicitly to get a better understanding of the magnitude of the strange values." }, { "code": null, "e": 6409, "s": 6279, "text": "IN:invoices['Meal Price'].apply(lambda x: type(x)).value_counts()OUT:<class 'int'> 49972<class 'str'> 2Name: Meal Price" }, { "code": null, "e": 6467, "s": 6409, "text": "You could then identify the offending rows by doing this:" }, { "code": null, "e": 6647, "s": 6467, "text": "IN:invoices['Meal Price'][invoices['Meal Price'].apply( lambda x: isinstance(x,str))]OUT:35612 Me too45612 I am causing troubleName: Meal Price, dtype: object" }, { "code": null, "e": 6783, "s": 6647, "text": "From there on it is a quick step to either fix the values or make an informed decision about how you want to handle failing conversion." }, { "code": null, "e": 6951, "s": 6783, "text": "The example above is a prime example, where it would be very reasonable to just convert the values into np.nan by passing errors='coerce' to pd.to_numeric() like this:" }, { "code": null, "e": 7006, "s": 6951, "text": "pd.to_numeric(invoices['Meal Price'], errors='coerce')" }, { "code": null, "e": 7275, "s": 7006, "text": "Now it should be noted that you will by construction have two np.nan value in your data, so it might be a good idea to handle them on the spot. The problem with the np.nan`s is that integer columns don’t know how to handle them. Thus the column will be a float column." }, { "code": null, "e": 7591, "s": 7275, "text": "# convert the offending values into np.naninvoices['Meal Price'] = pd.to_numeric(invoices['Meal Price'],errors='coerce')# fill np.nan with the median of the datainvoices['Meal Price'] = invoices['Meal Price'].fillna(invoices['Meal Price'].median())# convert the column into integerinvoices['Meal Price'].astype(int)" }, { "code": null, "e": 7886, "s": 7591, "text": "pd.to_datetime()Does what the name implies, the method converts a string into a datetime format. To call to_datetime on a column you would do: pd.to_datetime(invoices['Date of Meal']). Pandas will then guess the format and try to parse the date from the Input. And it does so impressively well:" }, { "code": null, "e": 8332, "s": 7886, "text": "IN:print(pd.to_datetime('2019-8-1'))print(pd.to_datetime('2019/8/1'))print(pd.to_datetime('8/1/2019'))print(pd.to_datetime('Aug, 1 2019'))print(pd.to_datetime('Aug - 1 2019'))print(pd.to_datetime('August - 1 2019'))print(pd.to_datetime('2019, August - 1'))print(pd.to_datetime('20190108'))OUT:2019-08-01 00:00:002019-08-01 00:00:002019-08-01 00:00:002019-08-01 00:00:002019-08-01 00:00:002019-08-01 00:00:002019-08-01 00:00:002019-01-08 00:00:00" }, { "code": null, "e": 9073, "s": 8332, "text": "However, now and then you might encounter some atypical formatting, like the last example from the list above. In this case, you probably want to provide a custom format, which can you can do like this: pd.to_datetime('20190108',format='%Y%d%m'). Think of the format string as a mask to check against the date string, and if the mask fits, the conversion will take place. Check this link out for a list of all the possible date format components. One additional noteworthy parameter when working with custom formats is exact=False. print(pd.to_datetime('yolo 20190108', format='%Y%d%m', exact=False)) will work, while it would fail without the exact parameter. With exact=False Pandas tries to match the pattern anywhere in the date string." }, { "code": null, "e": 9217, "s": 9073, "text": "Before moving on let’s convert our Date of Meal column, like this invoices['Date of Meal'] = pd.to_datetime(invoices['Date of Meal'], utc=True)" }, { "code": null, "e": 9281, "s": 9217, "text": "If your only tool is a hammer, every problem looks like a nail." }, { "code": null, "e": 9556, "s": 9281, "text": "Think of a Pandas accessor as a property that acts as an interface to methods specific to the type you are trying to access. Those methods are highly specialized. They serve one job and one job only. However, they are excellent and extremely concise for that particular job." }, { "code": null, "e": 9593, "s": 9556, "text": "There are three different accessors:" }, { "code": null, "e": 9596, "s": 9593, "text": "dt" }, { "code": null, "e": 9600, "s": 9596, "text": "str" }, { "code": null, "e": 9604, "s": 9600, "text": "cat" }, { "code": null, "e": 9735, "s": 9604, "text": "All of the methods are accessed by calling .<accessor>.method on the column of choice, like this: invoices['Date of Meal'].dt.date" }, { "code": null, "e": 9822, "s": 9735, "text": "This one I think is the most useful and most straight forward of the accessor methods:" }, { "code": null, "e": 9872, "s": 9822, "text": "date (returns the date of the datetime value), or" }, { "code": null, "e": 10055, "s": 9872, "text": "IN:invoices['Date of Meal'].dt.dateOUT:0 2015-01-291 2017-10-30 ... 49972 2017-09-0649973 2015-08-20Name: Date of Meal, Length: 49974, dtype: object" }, { "code": null, "e": 10261, "s": 10055, "text": "weekday_name (returns the name of the day), month_name() (this is implemented somewhat inconsistently, as weekday_name is a property, but month_name is a method and needs to be called with the parenthesis)" }, { "code": null, "e": 10632, "s": 10261, "text": "IN:invoices['Date of Meal'].dt.weekday_nameOUT:0 Thursday1 Monday ... 49972 Wednesday49973 ThursdayName: Date of Meal, Length: 49974, dtype: objectIN:invoices['Date of Meal'].dt.month_name()OUT:0 January1 October ... 49972 September49973 AugustName: Date of Meal, Length: 49974, dtype: object" }, { "code": null, "e": 10646, "s": 10632, "text": "days_in_month" }, { "code": null, "e": 10797, "s": 10646, "text": "IN:invoices['Date of Meal'].dt.days_in_monthOUT:0 311 31 ..49972 3049973 31Name: Date of Meal, Length: 49974, dtype: int64" }, { "code": null, "e": 10921, "s": 10797, "text": "nanosecond,microsecond,second,minute,hour ,day, week, month, quarter, year gets the integer of the corresponding frequency." }, { "code": null, "e": 11715, "s": 10921, "text": "EXAMPLES: (same logic applies for nanosecond, microsecond, second, minute, hour)IN:invoices['Date of Meal'].dt.dayOUT:0 291 30 ..49972 649973 20Name: Date of Meal, Length: 49974, dtype: int64IN:invoices['Date of Meal'].dt.weekOUT:0 51 44 ..49972 3649973 34Name: Date of Meal, Length: 49974, dtype: int64IN:invoices['Date of Meal'].dt.monthOUT:0 11 10 ..49972 949973 8Name: Date of Meal, Length: 49974, dtype: int64IN:invoices['Date of Meal'].dt.quarterOUT:0 11 4 ..49972 349973 3Name: Date of Meal, Length: 49974, dtype: int64IN:invoices['Date of Meal'].dt.yearOUT:0 20151 2017 ... 49972 201749973 2015Name: Date of Meal, Length: 49974, dtype: int64" }, { "code": null, "e": 11914, "s": 11715, "text": "is_leap_year, is_month_start, is_month_end, is_quarter_start, is_quarter_end, is_year_start, is_year_end returns True or False respectively for each value. See the following example for is_month_end" }, { "code": null, "e": 12078, "s": 11914, "text": "IN:invoices['Date of Meal'].dt.is_month_endOUT:0 False1 False ... 49972 False49973 FalseName: Date of Meal, Length: 49974, dtype: bool" }, { "code": null, "e": 12181, "s": 12078, "text": "We can use the results to filter our data down to only rows, where Date of Meal is at the month's end." }, { "code": null, "e": 12407, "s": 12181, "text": "to_pydatetime(), which converts the Pandas datetime into a regular Python datetime format (which you might need sometimes) and to_period(<PERIOD>) [available periods are W, M, Q, and Y], which converts the dates into periods." }, { "code": null, "e": 12987, "s": 12407, "text": "IN:invoices['Date of Meal'].dt.to_pydatetime()OUT:array([datetime.datetime(2015, 1, 29, 8, 0), datetime.datetime(2017, 10, 30, 20, 0), datetime.datetime(2015, 2, 10, 11, 0), ..., datetime.datetime(2017, 3, 7, 19, 0), datetime.datetime(2017, 9, 6, 6, 0), datetime.datetime(2015, 8, 20, 18, 0)], dtype=object)IN:invoices['Date of Meal'].dt.to_period('W')OUT:0 2015-01-26/2015-02-011 2017-10-30/2017-11-05 ... 49972 2017-09-04/2017-09-1049973 2015-08-17/2015-08-23Name: Date of Meal, Length: 49974, dtype: object" }, { "code": null, "e": 13115, "s": 12987, "text": "The str accessor is also quite helpful, not because it enables additional functionality, but makes for much more readable code." }, { "code": null, "e": 13169, "s": 13115, "text": "lower() / upper() to manage capitalization of strings" }, { "code": null, "e": 13532, "s": 13169, "text": "IN:invoices['Type of Meal'].str.lower()OUT:0 breakfast1 dinner ... 49972 breakfast49973 dinnerName: Type of Meal, Length: 49974, dtype: objectIN:invoices['Type of Meal'].str.upper()OUT:0 BREAKFAST1 DINNER ... 49972 BREAKFAST49973 DINNERName: Type of Meal, Length: 49974, dtype: object" }, { "code": null, "e": 13865, "s": 13532, "text": "ljust(width), rjust(width), center(width), zfill(width) to control the positioning of strings. All of them take a total width of the desired resulting string as an input. ljust, rjust, and center fill the difference to the desired length with whitespaces.zfill adds that many leading zeroes. ljustis left-bound, rjustis right-bound." }, { "code": null, "e": 14743, "s": 13865, "text": "IN:invoices['Type of Meal'].str.ljust(width=15)OUT:0 Breakfast 1 Dinner ... 49972 Breakfast 49973 Dinner Name: Type of Meal, Length: 49974, dtype: objectIN:invoices['Type of Meal'].str.rjust(width=15)OUT:0 Breakfast1 Dinner ... 49972 Breakfast49973 DinnerName: Type of Meal, Length: 49974, dtype: objectIN:invoices['Type of Meal'].str.center(width=15)OUT:0 Breakfast 1 Dinner ... 49972 Breakfast 49973 Dinner Name: Type of Meal, Length: 49974, dtype: objectIN:invoices['Type of Meal'].str.zfill(width=15)OUT:0 000000Breakfast1 000000000Dinner ... 49972 000000Breakfast49973 000000000DinnerName: Type of Meal, Length: 49974, dtype: object" }, { "code": null, "e": 14852, "s": 14743, "text": "startswith(<substring>), endswith(<substring>), contains(<substring>) checks for the presence of a substring" }, { "code": null, "e": 15020, "s": 14852, "text": "IN:invoices['Type of Meal'].str.endswith('ast')OUT:0 True1 False ... 49972 True49973 FalseName: Type of Meal, Length: 49974, dtype: bool" }, { "code": null, "e": 15068, "s": 15020, "text": "swapcase(), repeat(times) for kicks and giggles" }, { "code": null, "e": 15481, "s": 15068, "text": "IN:invoices['Type of Meal'].str.swapcase()OUT:0 bREAKFAST1 dINNER ... 49972 bREAKFAST49973 dINNERName: Type of Meal, Length: 49974, dtype: objectIN:invoices['Type of Meal'].str.repeat(2)OUT:0 BreakfastBreakfast1 DinnerDinner ... 49972 BreakfastBreakfast49973 DinnerDinnerName: Type of Meal, Length: 49974, dtype: object" }, { "code": null, "e": 15641, "s": 15481, "text": "In my opinion the least powerful of the three, or at least the one I use the most infrequently. cat provides access to a couple of categorial operations, like:" }, { "code": null, "e": 15688, "s": 15641, "text": "ordered lets you know if the column is ordered" }, { "code": null, "e": 15737, "s": 15688, "text": "IN:invoices['Type of Meal'].cat.orderedOUT:False" }, { "code": null, "e": 15773, "s": 15737, "text": "categories to return the categories" }, { "code": null, "e": 15875, "s": 15773, "text": "IN:invoices['Type of Meal'].cat.categoriesOUT:Index(['Breakfast', 'Dinner', 'Lunch'], dtype='object')" }, { "code": null, "e": 15952, "s": 15875, "text": "codes for quick conversion of the category into its numerical representation" }, { "code": null, "e": 16130, "s": 15952, "text": "IN:invoices['Type of Meal'].cat.codesOUT:0 01 12 23 24 2 ..49969 149970 249971 149972 049973 1Length: 49974, dtype: int8" }, { "code": null, "e": 16196, "s": 16130, "text": "reorder_categories to change the existing order of the categories" }, { "code": null, "e": 16585, "s": 16196, "text": "IN:invoices['Type of Meal'].cat.reorder_categories( ['Lunch','Breakfast','Dinner'])OUT:0 Breakfast1 Dinner2 Lunch3 Lunch4 Lunch ... 49969 Dinner49970 Lunch49971 Dinner49972 Breakfast49973 DinnerName: Type of Meal, Length: 49974, dtype: categoryCategories (3, object): [Lunch, Breakfast, Dinner]" }, { "code": null, "e": 16853, "s": 16585, "text": "Concatenating comes in handy when you have similar data (structurally and in terms of content) spread out across multiple files. You can concatenate data vertically (i.e., stack the data on top of each other) or horizontally (i.e., stack the data next to each other)." }, { "code": null, "e": 17085, "s": 16853, "text": "As an example, imagine that a client provides you one file per month or year of data (because their reporting runs at months end, for example). Those files are conceptually identically and thus a prime example of vertical stacking." }, { "code": null, "e": 17200, "s": 17085, "text": "Let’s have a look at how we can do this with Python’s Pandas. Let’s artificially split out invoices file by years." }, { "code": null, "e": 17910, "s": 17200, "text": "# Use dt accessor to count all the yearsIN:invoices['Date of Meal'].dt.year.value_counts().sort_index()OUT:2013 382014 99882015 100602016 99612017 99642018 99312019 32Name: Date of Meal, dtype: int64# Split the data y_2013 = invoices[invoices['Date of Meal'].dt.year == 2013].copy()y_2014 = invoices[invoices['Date of Meal'].dt.year == 2014].copy()y_2015 = invoices[invoices['Date of Meal'].dt.year == 2015].copy()y_2016 = invoices[invoices['Date of Meal'].dt.year == 2016].copy()y_2017 = invoices[invoices['Date of Meal'].dt.year == 2017].copy()y_2018 = invoices[invoices['Date of Meal'].dt.year == 2018].copy()y_2019 = invoices[invoices['Date of Meal'].dt.year == 2019].copy()" }, { "code": null, "e": 18055, "s": 17910, "text": "We use .copy() to make sure that the resulting DataFrames are going to be a copy of the data and not just a reference to the original DataFrame." }, { "code": null, "e": 18097, "s": 18055, "text": "Let’s validate that the splitting worked." }, { "code": null, "e": 18211, "s": 18097, "text": "Now for concatenating the data into a unified DataFrame, we would call pd.concat(<LIST OF DATAFRAMES>) like this:" }, { "code": null, "e": 18315, "s": 18211, "text": "pd.concat takes a couple of optional parameters next to the list of DataFrames that you call concat on:" }, { "code": null, "e": 18375, "s": 18315, "text": "axis : 0 for vertical, 1 for horizontal. axis defaults to 0" }, { "code": null, "e": 18736, "s": 18375, "text": "join : 'inner' for the intersection, 'outer' for the union of indices of the non-concatenating axis. When we use axis=0 and join='inner' we will consider only overlapping columns. When using axis=1 and join='inner' we consider only overlapping indices. In the case of outer non-overlapping columns/indices will be filled with nan values. join defaults to outer" }, { "code": null, "e": 18883, "s": 18736, "text": "ignore_index : True to ignore preexisting indices and instead use labels from 0 to n-1 for the resulting DataFrame. ignore_index defaults to False" }, { "code": null, "e": 19122, "s": 18883, "text": "keys : If we provide a list (has to be the same length as the number of DataFrames) a hierarchical index will be constructed. keys defaults to None. Use keys for example, to add the source of the data. Best used in combination with names." }, { "code": null, "e": 19252, "s": 19122, "text": "names : Assuming that you provide keys, the names will be used to label the resulting hierarchical index. names defaults to None." }, { "code": null, "e": 19528, "s": 19252, "text": "A use case for horizontal stacking is a case where you have multiple time series with overlapping but not identical indices. In which case, you wouldn’t want to end up with a DataFrame with potentially thousands of columns, but much rather a DataFrame with thousands of rows." }, { "code": null, "e": 19609, "s": 19528, "text": "Running the following snippet in Python will result in the following screenshot:" }, { "code": null, "e": 20058, "s": 19609, "text": "range_a = pd.date_range( datetime.datetime(2019,1,2), datetime.datetime(2019,1,8))df_a = pd.DataFrame( index=range_a, data=np.random.randint(2,10,size=len(range_a)), columns=['observations_A'])range_b = pd.date_range( datetime.datetime(2019,1,5), datetime.datetime(2019,1,12))df_b = pd.DataFrame( index=range_b, data=np.random.randint(2,10,size=len(range_b)), columns=['observations_B'])pd.concat([df_a,df_b],axis=1)" }, { "code": null, "e": 20264, "s": 20058, "text": "Note on Append :You might have seen the usage of appendto the same end asconcat. I advise against the usage of appendas it is just a special case of concatand does not provide a benefit over concatenating." }, { "code": null, "e": 20697, "s": 20264, "text": "Merging, as opposed to concatenating DataFrames together, allows us to combine two DataFrames in a more traditional SQL-query kind of way. When merging DataFrames, most of the time you want some information from one source and another piece of information from another source. Whereas when concatenating your DataFrames are structurally and in terms of content quite similar, and you want to combine them into one unified DataFrame." }, { "code": null, "e": 20779, "s": 20697, "text": "A simple example I like to use during interviews is something along the lines of:" }, { "code": null, "e": 20997, "s": 20779, "text": "Suppose you have two tables. One table contains the names of your employees and a location id, the other table contains location ids and a city name. How can you get a list of every employee and the city they work in?" }, { "code": null, "e": 21242, "s": 20997, "text": "Merging two DataFrames in Pandas is done with pd.merge. Let’s have a look at the function`s signature (signature means a list of all the possible parameters for the function and typically also the output). I bolded the most relevant parameters." }, { "code": null, "e": 21463, "s": 21242, "text": "pd.merge( left, right, how='inner', on=None, left_on=None, right_on=None, left_index=False, right_index=False, sort=True, suffixes=('_x', '_y'), copy=True, indicator=False, validate=None) -> pd.DataFrame" }, { "code": null, "e": 21507, "s": 21463, "text": "Let’s go through the parameters one by one:" }, { "code": null, "e": 21578, "s": 21507, "text": "left/right : the left, respectively right, DataFrame you want to merge" }, { "code": null, "e": 21756, "s": 21578, "text": "how : 'left', 'right', 'outer', 'inner'. how defaults to 'inner'. See below a schematic overview of what each of them does. We will discuss specific examples a little bit later." }, { "code": null, "e": 21888, "s": 21756, "text": "left_index/right_index : If True, use the index from the left/right DataFrame to merge on. left_index/right_index defaults to False" }, { "code": null, "e": 22124, "s": 21888, "text": "on : Column name(s) to merge on. Column name(s) have to exist in both the left and right DataFrame. If not passed and left_index and right_index are False, the intersection of the columns in both DataFrames will be inferred to join on." }, { "code": null, "e": 22441, "s": 22124, "text": "left_on/right_on : Column name(s) from the left/right DataFrame to join on. Typical use case: Keys you are joining on are differently labeled in your DataFrames. E.g., what is location_id in your left DataFrame, might be _id in your right DataFrame. In this case, you would do left_on='location_id', right_on='_id' ." }, { "code": null, "e": 22582, "s": 22441, "text": "suffixes: A tuple of string suffixes to apply to overlapping columns. suffixes defaults to ('_x', '_y'). I like to use ('_base', '_joined')." }, { "code": null, "e": 22687, "s": 22582, "text": "Enough theory, let’s have a look at some examples. To do this, we need some additional data to merge on." }, { "code": null, "e": 22698, "s": 22687, "text": "Load data:" }, { "code": null, "e": 23089, "s": 22698, "text": "# Load some additional Dataorder_data = pd.read_csv('https://raw.githubusercontent.com/FBosler/you-datascientist/master/order_leads.csv', parse_dates=[3])# Note the parse_dates? We need this to have consistent types with invoices, otherwise the subsequent merges would throw errorssales_team = pd.read_csv('https://raw.githubusercontent.com/FBosler/you-datascientist/master/sales_team.csv')" }, { "code": null, "e": 23103, "s": 23089, "text": "Inspect data:" }, { "code": null, "e": 23250, "s": 23103, "text": "We see pretty much right away, that Order ID ,Company ID , and Date appear in multiple of the DataFrames and are thus good candidates to merge on." }, { "code": null, "e": 23329, "s": 23250, "text": "Let’s merge invoices with order_data and experiment with the parameters a bit." }, { "code": null, "e": 23760, "s": 23329, "text": "No parameters provided: All parameters will use their defaults. The merge is going to be an inner merge (equivalent to how='inner'). The merge is going to be done on all common columns, i.e., Date, Order Id, and Company Id(equivalent to on=['Date','Order Id','Company Id]).Suffixes are not relevant as all common columns will be used to merge on, so there will no be duplicated columns remaining.Runpd.merge(order_data,invoices) :" }, { "code": null, "e": 24162, "s": 23760, "text": "how='left' : Again, the merge is based on all common columns. Suffixes are not relevant as all common columns will be used to merge on, so there will no be duplicated columns remaining. However, this time around, we merge with how='left' which means that we will take all rows from the left frame and only add data from the right frame where we find some. Runpd.merge(order_data,invoices,how='left') :" }, { "code": null, "e": 24700, "s": 24162, "text": "how='right' : Again, the merge is based on all common columns. Suffixes are not relevant as all common columns will be used to merge on, so there will no be duplicated columns remaining. However, this time around, we merge with how='right' which means that we will take all rows from the right frame and only add data from the left frame where we find some. This case is equivalent to 'inner' in our example as every row in the left DataFrame has a corresponding row in the right DataFrame. Runpd.merge(order_data,invoices,how='right') :" }, { "code": null, "e": 25252, "s": 24700, "text": "how='outer' : Again, the merge is based on all common columns. Suffixes are not relevant as all common columns will be used to merge on, so there will no be duplicated columns remaining. However, this time around, we merge with how='outer'. We take all rows from either, the left or the right DataFrame and add corresponding data where we find some in the other DataFrame. This case is equivalent to 'left' in our example as every row in the left DataFrame has a corresponding row in the right DataFrame. Runpd.merge(order_data,invoices,how='outer') :" }, { "code": null, "e": 25475, "s": 25252, "text": "If we do explicitly provide an on parameter this will override the default behavior and try to find the provided column in both DataFrames. Remaining duplicated columns that are not being used to merge on will be suffixed." }, { "code": null, "e": 25750, "s": 25475, "text": "In the following example, we only merge on Order Id. However, since the Date and Company Id columns are also present in both DataFrames. Those columns will be sufficed to indicate from which source DataFrame they are originating from as can be seen in the following example." }, { "code": null, "e": 25799, "s": 25750, "text": "Run: pd.merge(order_data,invoices,on='Order Id')" }, { "code": null, "e": 25916, "s": 25799, "text": "We can also specify custom suffixes like this:pd.merge(order_data,invoices,on='Order Id',suffixes=('_base','_join'))" }, { "code": null, "e": 26038, "s": 25916, "text": "You would typically use the left_on and right_on parameters when the columns are named differently in the two DataFrames." }, { "code": null, "e": 26286, "s": 26038, "text": "Note on Join :You might have seen the usage of jointo the same end asmerge. join by default merges on the index of both DataFrames. I advise against the usage of joinas it is just a special case of mergeand does not provide a benefit over merging." }, { "code": null, "e": 26432, "s": 26286, "text": "To wrap up the chapter on combining DataFrames, we should quickly talk about map. map can be called on a DataFrame column or its Index like this:" }, { "code": null, "e": 26754, "s": 26432, "text": "The argument (in our case lookup) for map always has to be a series or a dictionary. While not precisely the same Pandas` series and regular dictionaries share a lot of functionalities and can often be used interchangeably. Like through a dictionary you could loop through a series by calling for k,v in series.items(): ." }, { "code": null, "e": 27011, "s": 26754, "text": "Use pd.concat to “stack” multiple DataFrame on top or next to each other. By default, the stacking is vertical. To overwrite the default use axis=1. By default, stack will carry over all columns/indices. To limit to common columns/indices use join='inner'." }, { "code": null, "e": 27183, "s": 27011, "text": "Do not use pd.DataFrame.append as it is only a special, limited case of pd.concat and will only make your code less standardized and less coherent. Instead, use pd.concat." }, { "code": null, "e": 27376, "s": 27183, "text": "Use pd.merge to combine information from two DataFrames. Merge defaults to an inner join and will infer the columns to merge on from the largest subset of common columns across the DataFrames." }, { "code": null, "e": 27544, "s": 27376, "text": "Do not use pd.DataFrame.join as it is only a special, limited case of pd.merge and will only make your code less standardized and less coherent. Instead, use pd.merge." }, { "code": null, "e": 27670, "s": 27544, "text": "Use pd.Series.map as a lookup-esque kind of functionality to get the value for a specific index/key from a series/dictionary." }, { "code": null, "e": 27936, "s": 27670, "text": "Transposing a DataFrame means to swap the index and column. In other words, you are rotating the DataFrame around the origin. Transposing does not change the content of the DataFrame. The DataFrame only changes the orientation. Let’s visualize this with an example:" }, { "code": null, "e": 28017, "s": 27936, "text": "A DataFrame is transposed by simply calling .T on the DataFrame e.g.invoices.T)." }, { "code": null, "e": 28337, "s": 28017, "text": "Melt transforms a DataFrame from wide format to long format. Melt gives flexibility around how the transformation should take place. In other words, melt allows grabbing columns and transforming them into rows while leaving other columns unchanged. Melt is best explained with an example. Let’s create some sample data:" }, { "code": null, "e": 28589, "s": 28337, "text": "melt_experiment = pd.merge( invoices, pd.get_dummies(invoices['Type of Meal']).mul(invoices['Meal Price'].values,axis=0), left_index=True, right_index=True)del melt_experiment['Type of Meal']del melt_experiment['Meal Price']melt_experiment" }, { "code": null, "e": 28884, "s": 28589, "text": "Admittedly, this example is a bit contrived but illustrates the point. We turned the Type of Meal into columns and assigned the prices into the corresponding rows. Now to turn this back into a version where the Type of Meal is a column and the value is the price we could use pd.melt like this:" }, { "code": null, "e": 29131, "s": 28884, "text": "pd.melt( frame=melt_experiment, id_vars=['Order Id', 'Date', 'Meal Id', 'Company Id', 'Date of Meal','Participants', 'Heroes Adjustment'], value_vars=['Breakfast', 'Dinner', 'Lunch'], var_name='Type of Meal', value_name='Expenses')" }, { "code": null, "e": 29145, "s": 29131, "text": "resulting in:" }, { "code": null, "e": 29681, "s": 29145, "text": "Melt is useful to transform a DataFrame into a format where one or more columns are identifier variables (id_vars), while all other columns, considered measured variables (value_vars), are moved to the row axis, leaving just two non-identifier columns. For each column we melt (value_vars), the corresponding existing row is duplicated to accommodate fusing data into a single column and our DataFrame extends. After melting, we have three times as many rows as before (because we used three value_vars and thus triplicated every row)." }, { "code": null, "e": 30238, "s": 29681, "text": "We discussed in the previous article, but a quick recap makes sense here, especially in the light of stacking and unstacking, which we will talk about later. Where transpose and melt leave the content of the DataFrame intact and “only” rearrange the appearance groupby and the following methods are aggregating the data in one form or another. Groupby will result in an aggregated DataFrame with a new index (the values of the columns, by which you are grouping). If you are grouping by more than one value, the resulting DataFrame will have a multi-index." }, { "code": null, "e": 30318, "s": 30238, "text": "invoices.groupby(['Company Id','Type of Meal']).agg( {'Meal Price':np.mean})" }, { "code": null, "e": 30432, "s": 30318, "text": "Starting with pandas version 0.25.1, there are also named aggregation, which make groupby a little more readable." }, { "code": null, "e": 30551, "s": 30432, "text": "invoices.groupby(['Company Id','Type of Meal']).agg( Avg_Price = pd.NamedAgg(column='Meal Price', aggfunc=np.mean))" }, { "code": null, "e": 30663, "s": 30551, "text": "Resulting in virtually the same as the previous calculation. However, the column is renamed during the process." }, { "code": null, "e": 31104, "s": 30663, "text": "Pandas also incorporates a pivot_table functionality, not unlike Excel’s Pivot Table. I must admit though, I never use pivot, as I don’t see the advantage over groupby operations. Generally speaking, I think it makes sense to use what you are comfortable with and stick to that. I would advise against mixing different approaches when there is no necessity for doing so. The one good thing pivot_table has in its favor though is margin=True" }, { "code": null, "e": 31234, "s": 31104, "text": "pd.pivot_table( invoices, index=['Company Id','Type of Meal'], values='Meal Price', aggfunc=np.mean, margins=True)" }, { "code": null, "e": 31492, "s": 31234, "text": "The result should look somewhat familiar, as we basically recreated the groupby functionality. However, we get the added benefit of getting the calculated value across all groups in addition to the individual group’s results (as indicated by the last line)." }, { "code": null, "e": 31545, "s": 31492, "text": "We can also specify the columns for the pivot table:" }, { "code": null, "e": 31689, "s": 31545, "text": "pd.pivot_table( invoices, index=['Company Id'], columns=['Type of Meal'], values='Meal Price', aggfunc=np.mean, margins=True)" }, { "code": null, "e": 31963, "s": 31689, "text": "Stack and unstack come in really handy when rearranging your columns and indices. Unstack will by default be called on the outmost level of the index as can be seen nicely in the following example, where calling unstack() turns the Heroes Adjustment Index into two columns." }, { "code": null, "e": 32086, "s": 31963, "text": "We can also unstack a specific level of the index, like in the following example, where we unstack the Type of Meal column" }, { "code": null, "e": 32265, "s": 32086, "text": "Stacking, on the other hand, does the opposite. Stacking turns columns into rows, but also extends the index in the process (as opposed to melt). Let’s have a look at an example." }, { "code": null, "e": 32428, "s": 32265, "text": "We have to build some data first where stacking would come in handy. Executing the following code snippet results in a multi-index, multi-level-columns DataFrame." }, { "code": null, "e": 32571, "s": 32428, "text": "stack_test = invoices.groupby(['Company Id','Type of Meal']).agg({ 'Meal Price':[max,min,np.mean], 'Date of Meal':[max,min],})stack_test" }, { "code": null, "e": 32649, "s": 32571, "text": "If we want to stack this DataFrame, we would call stack_test.stack() and get:" }, { "code": null, "e": 32861, "s": 32649, "text": "Here stack used the outmost level of our multi-level columns and turned it into an index. We now have only single-level columns. Alternatively, we could also call stack with level=0 and get the following result:" }, { "code": null, "e": 33560, "s": 32861, "text": "In this article, you learned how to become a real Pandas Ninja. You learned how to convert data into desired types and between types. You learned how to use unique methods for those types to get access to functionalities, that would otherwise take lines and lines of code. You learned how to combine different DataFrames by just stacking them on top of each other, or logically extracting information from the DataFrames and combining them into something more meaningful. You learned how to flip your DataFrame around as if it were a pancake. You learned to rotate on its origin point, to move columns into rows, to aggregate data through pivot or groupby and then to stack and unstack the results." } ]
How to find strings with a given prefix in MySQL?
You can use LIKE operator to find strings with a given prefix. The syntax is as follows select *from yourTableName where yourColumnName LIKE 'yourPrefixValue%'; To understand the above syntax, let us create a table. The query to create a table is as follows mysql> create table findStringWithGivenPrefixDemo -> ( -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> UserMessage text -> ); Query OK, 0 rows affected (0.82 sec) Insert some records in the table using insert command. The query is as follows mysql> insert into findStringWithGivenPrefixDemo(UserMessage) values('Hi Good Morning !!!'); Query OK, 1 row affected (0.17 sec) mysql> insert into findStringWithGivenPrefixDemo(UserMessage) values('Hey I am busy!!'); Query OK, 1 row affected (0.20 sec) mysql> insert into findStringWithGivenPrefixDemo(UserMessage) values('Hello what are you doing!!!'); Query OK, 1 row affected (0.47 sec) mysql> insert into findStringWithGivenPrefixDemo(UserMessage) values('Hi I am learning MongoDB!!!'); Query OK, 1 row affected (0.15 sec) Display all records from the table using select statement. The query is as follows mysql> select *from findStringWithGivenPrefixDemo; The following is the output +--------+-----------------------------+ | UserId | UserMessage | +--------+-----------------------------+ | 1 | Hi Good Morning !!! | | 2 | Hey I am busy!! | | 3 | Hello what are you doing!!! | | 4 | Hi I am learning MongoDB!!! | +--------+-----------------------------+ 4 rows in set (0.00 sec) Here is the query to find strings with given prefix mysql> select *from findStringWithGivenPrefixDemo where UserMessage LIKE 'Hi%'; The following is the output displaying only the strings with prefix “Hi” +--------+-----------------------------+ | UserId | UserMessage | +--------+-----------------------------+ | 1 | Hi Good Morning !!! | | 4 | Hi i am learning MongoDB!!! | +--------+-----------------------------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1125, "s": 1062, "text": "You can use LIKE operator to find strings with a given prefix." }, { "code": null, "e": 1150, "s": 1125, "text": "The syntax is as follows" }, { "code": null, "e": 1223, "s": 1150, "text": "select *from yourTableName where yourColumnName LIKE 'yourPrefixValue%';" }, { "code": null, "e": 1320, "s": 1223, "text": "To understand the above syntax, let us create a table. The query to create a table is as follows" }, { "code": null, "e": 1501, "s": 1320, "text": "mysql> create table findStringWithGivenPrefixDemo\n -> (\n -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> UserMessage text\n -> );\nQuery OK, 0 rows affected (0.82 sec)" }, { "code": null, "e": 1556, "s": 1501, "text": "Insert some records in the table using insert command." }, { "code": null, "e": 1580, "s": 1556, "text": "The query is as follows" }, { "code": null, "e": 2108, "s": 1580, "text": "mysql> insert into findStringWithGivenPrefixDemo(UserMessage) values('Hi Good Morning !!!');\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into findStringWithGivenPrefixDemo(UserMessage) values('Hey I am busy!!');\nQuery OK, 1 row affected (0.20 sec)\nmysql> insert into findStringWithGivenPrefixDemo(UserMessage) values('Hello what are you doing!!!');\nQuery OK, 1 row affected (0.47 sec)\nmysql> insert into findStringWithGivenPrefixDemo(UserMessage) values('Hi I am learning MongoDB!!!');\nQuery OK, 1 row affected (0.15 sec)" }, { "code": null, "e": 2167, "s": 2108, "text": "Display all records from the table using select statement." }, { "code": null, "e": 2191, "s": 2167, "text": "The query is as follows" }, { "code": null, "e": 2242, "s": 2191, "text": "mysql> select *from findStringWithGivenPrefixDemo;" }, { "code": null, "e": 2270, "s": 2242, "text": "The following is the output" }, { "code": null, "e": 2623, "s": 2270, "text": "+--------+-----------------------------+\n| UserId | UserMessage |\n+--------+-----------------------------+\n| 1 | Hi Good Morning !!! |\n| 2 | Hey I am busy!! |\n| 3 | Hello what are you doing!!! |\n| 4 | Hi I am learning MongoDB!!! |\n+--------+-----------------------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2675, "s": 2623, "text": "Here is the query to find strings with given prefix" }, { "code": null, "e": 2755, "s": 2675, "text": "mysql> select *from findStringWithGivenPrefixDemo where UserMessage LIKE 'Hi%';" }, { "code": null, "e": 2828, "s": 2755, "text": "The following is the output displaying only the strings with prefix “Hi”" }, { "code": null, "e": 3099, "s": 2828, "text": "+--------+-----------------------------+\n| UserId | UserMessage |\n+--------+-----------------------------+\n| 1 | Hi Good Morning !!! |\n| 4 | Hi i am learning MongoDB!!! |\n+--------+-----------------------------+\n2 rows in set (0.00 sec)" } ]
mdir - Unix, Linux Command
The mdir command is used to display an MS-DOS directory. Its syntax is: mdir [-/] [-f] [-w] [-a] [-b] msdosfile [ msdosfiles...] Mdir displays the contents of MS-DOS directories, or the entries for some MS-DOS files. Mdir supports the following command line options: ./configure; make dvi; dvips mtools.dvi ./configure; make html A premade html can be found at: oohttp://mtools.linux.luI and also at: oohttp://www.tux.org/pub/knaff/mtoolsI ./configure; make info Advertisements 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 10660, "s": 10586, "text": "\nThe mdir command is used to display an MS-DOS directory. Its\nsyntax is:\n" }, { "code": null, "e": 10719, "s": 10660, "text": "\nmdir [-/] [-f] [-w] [-a] [-b] msdosfile [ msdosfiles...]\n" }, { "code": null, "e": 10809, "s": 10719, "text": "\nMdir\ndisplays the contents of MS-DOS directories, or the entries for some\nMS-DOS files.\n" }, { "code": null, "e": 10861, "s": 10809, "text": "\nMdir supports the following command line options:\n" }, { "code": null, "e": 10911, "s": 10865, "text": "\n ./configure; make dvi; dvips mtools.dvi\n" }, { "code": null, "e": 10944, "s": 10915, "text": "\n ./configure; make html\n" }, { "code": null, "e": 11056, "s": 10944, "text": "\nA premade html can be found at:\noohttp://mtools.linux.luI\nand also at:\noohttp://www.tux.org/pub/knaff/mtoolsI\n" }, { "code": null, "e": 11087, "s": 11058, "text": "\n ./configure; make info\n" }, { "code": null, "e": 11117, "s": 11100, "text": "\nAdvertisements\n" }, { "code": null, "e": 11152, "s": 11117, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 11180, "s": 11152, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 11214, "s": 11180, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 11231, "s": 11214, "text": " Frahaan Hussain" }, { "code": null, "e": 11264, "s": 11231, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 11275, "s": 11264, "text": " Pradeep D" }, { "code": null, "e": 11310, "s": 11275, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 11326, "s": 11310, "text": " Musab Zayadneh" }, { "code": null, "e": 11359, "s": 11326, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 11371, "s": 11359, "text": " GUHARAJANM" }, { "code": null, "e": 11403, "s": 11371, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 11411, "s": 11403, "text": " Uplatz" }, { "code": null, "e": 11418, "s": 11411, "text": " Print" }, { "code": null, "e": 11429, "s": 11418, "text": " Add Notes" } ]
How to print a calendar for the given month and year in Python?
You can use the calender module to get the calender for a given month of a given year in Python. You need to provide the year and month as arguments. import calendar y = 2017 m = 11 print(calendar.month(y, m)) This will give the output − November 2017 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
[ { "code": null, "e": 1212, "s": 1062, "text": "You can use the calender module to get the calender for a given month of a given year in Python. You need to provide the year and month as arguments." }, { "code": null, "e": 1272, "s": 1212, "text": "import calendar\ny = 2017\nm = 11\nprint(calendar.month(y, m))" }, { "code": null, "e": 1300, "s": 1272, "text": "This will give the output −" }, { "code": null, "e": 1434, "s": 1300, "text": " November 2017\nMo Tu We Th Fr Sa Su\n 1 2 3 4 5\n 6 7 8 9 10 11 12\n13 14 15 16 17 18 19\n20 21 22 23 24 25 26\n27 28 29 30" } ]
How To Fine-Tune GPT-2 So You Can Generate Long-Form Creative Writing | by Jason Boog | Towards Data Science
Ever since OpenAI released its GPT-2 language model into the wild, people have been using this AI writing tool to generate hilarious, scary, and fascinating short-form texts. If you want to use GPT-2 to generate long-form writing that incorporates your favorite themes, characters, settings, and writing styles, you’ll need to fine-tune the base model and do lots of reading. I can show you how to do that — for free! I just spent 18 days completing the National Novel Generation Challenge (NaNoGenMo), computer-generating a 51,422-word manuscript. Halfway through this writing and coding marathon, my AI writing partner generated this amazing (and somewhat disconcerting) monologue by an AI writer named Mr. Output: This monstrosity of yours? The monstrosity that is being written now, by the talented and novel-obsessed AI writer you just launched against your will, is just so terribly boring, there's no way I could squeeze in one more story.I write fantasy, I write sci-fi, I write horror, I write romance, I write all sorts of nonsense. You can't even imagine how many lines I've written, how many worlds and histories I've created and twisted and broken and made to rhyme and rhyme and be the best that there ever was. I’ll spend the rest of the year finding ways to incorporate Mr. Output’s strange and wonderful AI work into my own writing. If you enjoyed that passage, send me a message with your address and I’ll snail-mail you a handwritten story from Mr. Output. While writing about NaNoGenMo for Publishers Weekly, I had the opportunity to discuss long-form AI text generation with great writers like Robin Sloan, author of Mr. Penumbra’s 24-Hour Bookstore and Sourdough. As part of his writing projects, Sloan runs a version of GPT-2 on GPUs he purchased from a Bitcoin miner. Robin told me that it is “critical” to include a human author in the generation of a long-form text. “This still fundamentally about a person,” he explained, pointing to future collaborations between human authors and AI language models. “An author making decisions and having a plan and something they want to say in the world. If that means that they become an editor or a curator of this other text, I think that’s fine — or even awesome!” Following Robin’s advice, I played the curator during my NaNoGenMo project. I could have generated 50,000-words in less than an hour with my AI writing partner, but I chose to spend 18 days reading hundreds of pages and collecting the most compelling texts into a single document. I also used prefix tags in my code to make sure the GPT-2 model focused on my favorite metaphysical themes throughout the project. “One of the open problems in the procedural generation of fiction is how to maintain reader interest at scale,” wrote John Ohno on Medium. Hoping to tackle that issue with my NaNoGenMo project, I decided to use writing prompts and responses to generate shorter (and possibly more interesting) sections. Here’s how I did it... No matter what kind of long-form writing you want to generate, you’ll need to find the largest dataset possible. Using a Google’s BigQuery tool and the enormous archive of Reddit data archived at Pushshift.io, I created a massive dataset of individual writing prompts in a handy CSV file — each separated with <|startoftext|> and <|endoftext|> tokens. I also used a Reddit search tool from Pushshift to collect hundreds of AI-related writing prompts to add to the dataset because I wanted my bots to tackle my favorite sci-fi themes. At the end of this process, I had a writing prompt dataset with 1,065,179 tokens. GPT-2 is a massive language model, so you need a comparatively big dataset to fine-tune the model effectively. Unless you want to follow my writing prompts/responses model, you only need to create ONE dataset. I needed two datasets for my project. Using the same tools and lots of Reddit searches, I collected the highest-rated and greatest writing prompts I could find online. I added lots of AI-focused responses, including my own writing prompt responses I’ve written over the years. I ended up with 1,947,763 tokens in this second training dataset. This step is really important if you want to generate writing with any sort of structure. I wanted to give my AI the most uncluttered and high-quality learning data possible, so I used a series of simple markers to teach GPT-2 the shape of a writing prompt response. I added <|startoftext|> and <|endoftext|> tokens to match the writing prompt dataset, but I also made sure each response had the original writing prompt marked [WP] and the response itself marked [RESPONSE]. While this was a huge, time-consuming effort, but it made my output infinitely more interesting. I saved the whole dataset as a .TXT file. Here’s what that dataset looks like: <|startoftext|>[WP] On November 4, 2020, humanity abandons the Internet. Billions of bots have colonized the web with spam, deepfakes, and fake news. At the now deserted r/WritingPrompts, literary AIs (trained on great works of human literature) create an infinite library of prompts & responses.[RESPONSE] Zackary Blue worked as a night janitor in the basement for major financial services company. He cleaned cavernous spaces beneath the building where hundreds of millions of dollars got traded every single day.<|endoftext|> Fine-tuning both my language models took a few days. Max Woolf taught me everything I needed to know for this step. IMPORTANT UPDATE: Google Colab has updated its standard Tensor Flow version, and you must add a single line of code to the top of Max Woolf’s Colab Notebook to use an older version of Tensor Flow. Just add this line of code to the top of the Colab Notebook and Woolf’s notebook should run perfectly: %tensorflow_version 1.x I used the medium-sized 355M version of GPT-2 because it was large enough to handle my data set but small enough to run on Google Colab’s cloud servers. I trained both models with 42,000 steps each. I broke the training into smaller sections, because Google Colab won’t run more than 12,000 steps. Once my two language models were trained, I began generating my NaNoGenMo project. Every morning, I would run Writing Prompt Prompter (Jane Doe) and generate between 10–20 pages of computer-generated writing prompts. For each run, I set a length of 100 characters, the temperature at .7, and the output at 10 samples. To shape the project, I used the prefix function to angle the writing prompt output toward my favorite themes like virtual reality, simulation theory, and AI writers. Unless you want to follow my writing prompts/responses model, you only need to generate text with one language model. However, I added an extra step for my NaNoGenMo project. I picked my favorite computer-generated writing prompts and fed them to Writing Prompt Responder (Mr. Output) to generate between 100 and 125 pages of responses. Max Woolf’s Google Colab notebooks helped me code everything for this step. I combed through hundreds of pages of text that Jane Doe and Mr. Output generated, picking the most compelling stories. For every 350 words of compelling computer-generated writing that I gathered for NaNoGenMo, I had to plow through around 10,000 words of strange, confusing, repetitive, or just plain incomprehensible computer-generated text. During November, I stored each day’s output in a single file. I would read that file every night, searching for compelling writing. Here’s one of the first pieces of writing I saved, a utopian manifesto: We are a group of artists, writers, coders, and tinkerers, who have banded under the banner of Humanity v2.0. We are a worldwide collective of similar interests. We all have the same goal - to create anew the foundations of a better world. I recommend reading your computer-generated text on an eReader or tablet. It gets you away from the computer screen and gives you a bit more of the actual reading experience. I used also the fabulous Voice Dream Reader to listen to my computer-generated content while commuting to work in the morning. During these epic reading sessions, I saved the best pieces of writing into a master file marked “NaNoGenMo Final.” After that, I kept running those same text-generation steps for 17 days straight November. I kept adding computer-generated text to my final document until I crossed the 50,000-word finish line for the NaNoGenMo marathon. Once the “NaNoGenMo Final” document had reached critical mass, I used the powerful writing tool Scrivener to rearrange the computer-generated stories around themes like virtual reality, AI writing, or gods. I kept my edits to a simple reorganization, but human curators can use this step to make chapters, edit particular passages, add illustrations, write commentary, or anything else! Once I had compiled the final manuscript, I ran every prompt and response through the Quetext tool to make sure my bot hadn’t plagiarized anybody online. GPT-2 runs a massive dataset with millions of articles, but it occasionally parrots its human trainers. That’s it! NaNoGenMo was a great writing and coding experience, I recommend trying it if you have some time this month. There have never been so many resources available to amateurs like me and GPT-2 is truly powerful when trained fine-tuned. I’ll be reading these GPT-2 generated stories for the rest of the year. Here’s one last sample, a bit of connection between an AI writer and a human writer... They are a species apart, but they share one thing in common: their love of books. They are the ones who seek out books for their own needs, whether they be scientific, philosophical, or religious texts. They are the ones who, from the beginning, have been able to find meaning within books.
[ { "code": null, "e": 222, "s": 47, "text": "Ever since OpenAI released its GPT-2 language model into the wild, people have been using this AI writing tool to generate hilarious, scary, and fascinating short-form texts." }, { "code": null, "e": 423, "s": 222, "text": "If you want to use GPT-2 to generate long-form writing that incorporates your favorite themes, characters, settings, and writing styles, you’ll need to fine-tune the base model and do lots of reading." }, { "code": null, "e": 465, "s": 423, "text": "I can show you how to do that — for free!" }, { "code": null, "e": 596, "s": 465, "text": "I just spent 18 days completing the National Novel Generation Challenge (NaNoGenMo), computer-generating a 51,422-word manuscript." }, { "code": null, "e": 764, "s": 596, "text": "Halfway through this writing and coding marathon, my AI writing partner generated this amazing (and somewhat disconcerting) monologue by an AI writer named Mr. Output:" }, { "code": null, "e": 1273, "s": 764, "text": "This monstrosity of yours? The monstrosity that is being written now, by the talented and novel-obsessed AI writer you just launched against your will, is just so terribly boring, there's no way I could squeeze in one more story.I write fantasy, I write sci-fi, I write horror, I write romance, I write all sorts of nonsense. You can't even imagine how many lines I've written, how many worlds and histories I've created and twisted and broken and made to rhyme and rhyme and be the best that there ever was." }, { "code": null, "e": 1523, "s": 1273, "text": "I’ll spend the rest of the year finding ways to incorporate Mr. Output’s strange and wonderful AI work into my own writing. If you enjoyed that passage, send me a message with your address and I’ll snail-mail you a handwritten story from Mr. Output." }, { "code": null, "e": 1839, "s": 1523, "text": "While writing about NaNoGenMo for Publishers Weekly, I had the opportunity to discuss long-form AI text generation with great writers like Robin Sloan, author of Mr. Penumbra’s 24-Hour Bookstore and Sourdough. As part of his writing projects, Sloan runs a version of GPT-2 on GPUs he purchased from a Bitcoin miner." }, { "code": null, "e": 2282, "s": 1839, "text": "Robin told me that it is “critical” to include a human author in the generation of a long-form text. “This still fundamentally about a person,” he explained, pointing to future collaborations between human authors and AI language models. “An author making decisions and having a plan and something they want to say in the world. If that means that they become an editor or a curator of this other text, I think that’s fine — or even awesome!”" }, { "code": null, "e": 2358, "s": 2282, "text": "Following Robin’s advice, I played the curator during my NaNoGenMo project." }, { "code": null, "e": 2563, "s": 2358, "text": "I could have generated 50,000-words in less than an hour with my AI writing partner, but I chose to spend 18 days reading hundreds of pages and collecting the most compelling texts into a single document." }, { "code": null, "e": 2694, "s": 2563, "text": "I also used prefix tags in my code to make sure the GPT-2 model focused on my favorite metaphysical themes throughout the project." }, { "code": null, "e": 2997, "s": 2694, "text": "“One of the open problems in the procedural generation of fiction is how to maintain reader interest at scale,” wrote John Ohno on Medium. Hoping to tackle that issue with my NaNoGenMo project, I decided to use writing prompts and responses to generate shorter (and possibly more interesting) sections." }, { "code": null, "e": 3020, "s": 2997, "text": "Here’s how I did it..." }, { "code": null, "e": 3133, "s": 3020, "text": "No matter what kind of long-form writing you want to generate, you’ll need to find the largest dataset possible." }, { "code": null, "e": 3372, "s": 3133, "text": "Using a Google’s BigQuery tool and the enormous archive of Reddit data archived at Pushshift.io, I created a massive dataset of individual writing prompts in a handy CSV file — each separated with <|startoftext|> and <|endoftext|> tokens." }, { "code": null, "e": 3554, "s": 3372, "text": "I also used a Reddit search tool from Pushshift to collect hundreds of AI-related writing prompts to add to the dataset because I wanted my bots to tackle my favorite sci-fi themes." }, { "code": null, "e": 3747, "s": 3554, "text": "At the end of this process, I had a writing prompt dataset with 1,065,179 tokens. GPT-2 is a massive language model, so you need a comparatively big dataset to fine-tune the model effectively." }, { "code": null, "e": 3846, "s": 3747, "text": "Unless you want to follow my writing prompts/responses model, you only need to create ONE dataset." }, { "code": null, "e": 4123, "s": 3846, "text": "I needed two datasets for my project. Using the same tools and lots of Reddit searches, I collected the highest-rated and greatest writing prompts I could find online. I added lots of AI-focused responses, including my own writing prompt responses I’ve written over the years." }, { "code": null, "e": 4189, "s": 4123, "text": "I ended up with 1,947,763 tokens in this second training dataset." }, { "code": null, "e": 4279, "s": 4189, "text": "This step is really important if you want to generate writing with any sort of structure." }, { "code": null, "e": 4456, "s": 4279, "text": "I wanted to give my AI the most uncluttered and high-quality learning data possible, so I used a series of simple markers to teach GPT-2 the shape of a writing prompt response." }, { "code": null, "e": 4664, "s": 4456, "text": "I added <|startoftext|> and <|endoftext|> tokens to match the writing prompt dataset, but I also made sure each response had the original writing prompt marked [WP] and the response itself marked [RESPONSE]." }, { "code": null, "e": 4840, "s": 4664, "text": "While this was a huge, time-consuming effort, but it made my output infinitely more interesting. I saved the whole dataset as a .TXT file. Here’s what that dataset looks like:" }, { "code": null, "e": 5369, "s": 4840, "text": "<|startoftext|>[WP] On November 4, 2020, humanity abandons the Internet. Billions of bots have colonized the web with spam, deepfakes, and fake news. At the now deserted r/WritingPrompts, literary AIs (trained on great works of human literature) create an infinite library of prompts & responses.[RESPONSE] Zackary Blue worked as a night janitor in the basement for major financial services company. He cleaned cavernous spaces beneath the building where hundreds of millions of dollars got traded every single day.<|endoftext|>" }, { "code": null, "e": 5485, "s": 5369, "text": "Fine-tuning both my language models took a few days. Max Woolf taught me everything I needed to know for this step." }, { "code": null, "e": 5785, "s": 5485, "text": "IMPORTANT UPDATE: Google Colab has updated its standard Tensor Flow version, and you must add a single line of code to the top of Max Woolf’s Colab Notebook to use an older version of Tensor Flow. Just add this line of code to the top of the Colab Notebook and Woolf’s notebook should run perfectly:" }, { "code": null, "e": 5809, "s": 5785, "text": "%tensorflow_version 1.x" }, { "code": null, "e": 6008, "s": 5809, "text": "I used the medium-sized 355M version of GPT-2 because it was large enough to handle my data set but small enough to run on Google Colab’s cloud servers. I trained both models with 42,000 steps each." }, { "code": null, "e": 6107, "s": 6008, "text": "I broke the training into smaller sections, because Google Colab won’t run more than 12,000 steps." }, { "code": null, "e": 6190, "s": 6107, "text": "Once my two language models were trained, I began generating my NaNoGenMo project." }, { "code": null, "e": 6324, "s": 6190, "text": "Every morning, I would run Writing Prompt Prompter (Jane Doe) and generate between 10–20 pages of computer-generated writing prompts." }, { "code": null, "e": 6592, "s": 6324, "text": "For each run, I set a length of 100 characters, the temperature at .7, and the output at 10 samples. To shape the project, I used the prefix function to angle the writing prompt output toward my favorite themes like virtual reality, simulation theory, and AI writers." }, { "code": null, "e": 6710, "s": 6592, "text": "Unless you want to follow my writing prompts/responses model, you only need to generate text with one language model." }, { "code": null, "e": 6767, "s": 6710, "text": "However, I added an extra step for my NaNoGenMo project." }, { "code": null, "e": 7005, "s": 6767, "text": "I picked my favorite computer-generated writing prompts and fed them to Writing Prompt Responder (Mr. Output) to generate between 100 and 125 pages of responses. Max Woolf’s Google Colab notebooks helped me code everything for this step." }, { "code": null, "e": 7125, "s": 7005, "text": "I combed through hundreds of pages of text that Jane Doe and Mr. Output generated, picking the most compelling stories." }, { "code": null, "e": 7350, "s": 7125, "text": "For every 350 words of compelling computer-generated writing that I gathered for NaNoGenMo, I had to plow through around 10,000 words of strange, confusing, repetitive, or just plain incomprehensible computer-generated text." }, { "code": null, "e": 7554, "s": 7350, "text": "During November, I stored each day’s output in a single file. I would read that file every night, searching for compelling writing. Here’s one of the first pieces of writing I saved, a utopian manifesto:" }, { "code": null, "e": 7794, "s": 7554, "text": "We are a group of artists, writers, coders, and tinkerers, who have banded under the banner of Humanity v2.0. We are a worldwide collective of similar interests. We all have the same goal - to create anew the foundations of a better world." }, { "code": null, "e": 8096, "s": 7794, "text": "I recommend reading your computer-generated text on an eReader or tablet. It gets you away from the computer screen and gives you a bit more of the actual reading experience. I used also the fabulous Voice Dream Reader to listen to my computer-generated content while commuting to work in the morning." }, { "code": null, "e": 8212, "s": 8096, "text": "During these epic reading sessions, I saved the best pieces of writing into a master file marked “NaNoGenMo Final.”" }, { "code": null, "e": 8434, "s": 8212, "text": "After that, I kept running those same text-generation steps for 17 days straight November. I kept adding computer-generated text to my final document until I crossed the 50,000-word finish line for the NaNoGenMo marathon." }, { "code": null, "e": 8641, "s": 8434, "text": "Once the “NaNoGenMo Final” document had reached critical mass, I used the powerful writing tool Scrivener to rearrange the computer-generated stories around themes like virtual reality, AI writing, or gods." }, { "code": null, "e": 8821, "s": 8641, "text": "I kept my edits to a simple reorganization, but human curators can use this step to make chapters, edit particular passages, add illustrations, write commentary, or anything else!" }, { "code": null, "e": 9079, "s": 8821, "text": "Once I had compiled the final manuscript, I ran every prompt and response through the Quetext tool to make sure my bot hadn’t plagiarized anybody online. GPT-2 runs a massive dataset with millions of articles, but it occasionally parrots its human trainers." }, { "code": null, "e": 9199, "s": 9079, "text": "That’s it! NaNoGenMo was a great writing and coding experience, I recommend trying it if you have some time this month." }, { "code": null, "e": 9394, "s": 9199, "text": "There have never been so many resources available to amateurs like me and GPT-2 is truly powerful when trained fine-tuned. I’ll be reading these GPT-2 generated stories for the rest of the year." }, { "code": null, "e": 9481, "s": 9394, "text": "Here’s one last sample, a bit of connection between an AI writer and a human writer..." } ]
How to remove leading zeros from a number in JavaScript?
Use parseInt() to remove leading zeros from a number in JavaScript. You can try to run the following code to run how to remove leading zeros − Live Demo <!DOCTYPE html> <html> <body> <script> var num1 = parseInt("025", 10); document.write(num1); var num2 = parseInt("040", 10); document.write("<br>"+num2); var num3 = parseInt("098", 10); document.write("<br>"+num3); </script> </body> </html> 25 40 98
[ { "code": null, "e": 1130, "s": 1062, "text": "Use parseInt() to remove leading zeros from a number in JavaScript." }, { "code": null, "e": 1205, "s": 1130, "text": "You can try to run the following code to run how to remove leading zeros −" }, { "code": null, "e": 1215, "s": 1205, "text": "Live Demo" }, { "code": null, "e": 1530, "s": 1215, "text": "<!DOCTYPE html>\n<html>\n <body>\n <script>\n var num1 = parseInt(\"025\", 10);\n document.write(num1);\n\n var num2 = parseInt(\"040\", 10);\n document.write(\"<br>\"+num2);\n\n var num3 = parseInt(\"098\", 10);\n document.write(\"<br>\"+num3);\n </script>\n </body>\n</html>" }, { "code": null, "e": 1539, "s": 1530, "text": "25\n40\n98" } ]
PyTorch Geometric Graph Embedding | by Anuradha Wickramarachchi | Towards Data Science
Graph representation learning/embedding is commonly the term used for the process where we transform a Graph data structure to a more structured vector form. This enables the downstream analysis by providing more manageable fixed-length vectors. Ideally, these vectors should incorporate both graph structure (topological) information apart from the node features. We use graph neural networks (CNN) to perform this transformation. To have a basic high-level idea about GNNs, you can take a peek at the following article. towardsdatascience.com In this article, I will talk about the GraphSAGE architecture which is a variant of message passing neural networks (MPNN). MPNN is a fancy term for how GNNs are efficiently implemented. Any MPNN can be formally represented using the two functions aggregate and combine. The aggregate function governs how neighbour information is gathered or aggregated for a given node. The combine function governs how the information of a node itself is combined with the information from the neighbourhood. GraphSAGE stands for Graph-SAmple-and-aggreGatE. Let’s first define the aggregate and combine functions for GraphSAGE. Combine — Use element-wise mean of features of neighbours Aggregate — Concatenate aggregated features with current node features GraphSAGE layers can be visually represented as follows. For a given node v, we aggregate all neighbours using mean aggregation. The result is concatenated with the node v’s features and fed through a multi-layer perception (MLP) followed by a non-linearity like RELU. One can easily use a framework such as PyTorch geometric to use GraphSAGE. Before we go there let’s build up a use case to proceed. One major importance of embedding a graph is visualization. Therefore, let’s build a GNN with GraphSAGE to visualize Cora dataset. Note that here I am using the provided example in PyTorch Geometric repository with few tricks. The key idea of GraphSAGE is sampling strategy. This enables the architecture to scale to very large scale applications. The sampling implies that, at each layer, only up to K number of neighbours are used. As usual, we must use an order invariant aggregator such as Mean, Max, Min, etc. In graph embedding, we operate in an unsupervised manner. Therefore, we use the graph topological structure to define the loss. Here Zu demonstrates the final layer output for node u. Zvn indicates the negative sampled node. In simple terms, the second term of the equation indicates that the negated dot product of negative (node u and any random node v) should be maximized. In other words, the cosine distance of random nodes should be further. First-term says otherwise for node v, which is a node that we need to be embedded closer to u. This v is called a positive node, which is typically obtained using a random walk starting from u. Evn~Pn(v) indicates that the negative nodes are taken from a negative sampling approach. In actual implementation, we take direct neighbours as positive samples and random nodes as negative samples. We can start by importing the following python modules. import torchimport torch.nn as nnimport torch.nn.functional as Ffrom torch_cluster import random_walkfrom sklearn.linear_model import LogisticRegressionimport torch_geometric.transforms as Tfrom torch_geometric.nn import SAGEConvfrom torch_geometric.datasets import Planetoidfrom torch_geometric.data import NeighborSampler as RawNeighborSamplerimport umapimport matplotlib.pyplot as pltimport seaborn as sns Initializing the Cora dataset; dataset = 'Cora'path = './data'dataset = Planetoid(path, dataset, transform=T.NormalizeFeatures())data = dataset[0] Note that the dataset object is a list of subgraphs. In the case of Cora, we have one so we pick the graph in index 0. Sampler components (here we extend NeighborSampler class’s sample method to create batches with positive and negative samples); # For each batch and the adjacency matrixpos_batch = random_walk(row, col, batch, walk_length=1, coalesced=False)[:, 1]# row are source nodes, col are target nodes from Adjacency matrix# index 1 is taken as positive nodes# Random targets from whole adjacency matrixneg_batch = torch.randint(0, self.adj_t.size(1), (batch.numel(), ), dtype=torch.long) GNN can be declared in PyTorch as follows; class SAGE(nn.Module): def __init__(self, in_channels, hidden_channels, num_layers): super(SAGE, self).__init__() self.num_layers = num_layers self.convs = nn.ModuleList() for i in range(num_layers): in_channels = in_channels if i == 0 else hidden_channels self.convs.append(SAGEConv(in_channels, hidden_channels)) def forward(self, x, adjs): for i, (edge_index, _, size) in enumerate(adjs): x_target = x[:size[1]] x = self.convs[i]((x, x_target), edge_index) if i != self.num_layers - 1: x = x.relu() x = F.dropout(x, p=0.5, training=self.training) return x def full_forward(self, x, edge_index): for i, conv in enumerate(self.convs): x = conv(x, edge_index) if i != self.num_layers - 1: x = x.relu() x = F.dropout(x, p=0.5, training=self.training) return x Note that we use SAGEConv layers from PyTorch Geometric framework. In the forward pass, the NeighborSampler provides us with data to be passed over in each layer as data indices. This is a rather complex module so I suggest readers read the Minibatch Algorithm from paper(page 12) and the NeighborSampler module docs from PyTorch Geometric. Without using graph structure, the following is the UMAP plot. When we embed using GraphSAGE we can have a better embedding as follows; We can see that the embeddings are much better and well separated compared to naive UMAP embedding. However, this is not perfect and needs more work. But I hope this is a good enough demonstration to convey the idea. 😊 Hope you enjoyed this article! The complete code and Jupyter Notebook is available here.
[ { "code": null, "e": 693, "s": 171, "text": "Graph representation learning/embedding is commonly the term used for the process where we transform a Graph data structure to a more structured vector form. This enables the downstream analysis by providing more manageable fixed-length vectors. Ideally, these vectors should incorporate both graph structure (topological) information apart from the node features. We use graph neural networks (CNN) to perform this transformation. To have a basic high-level idea about GNNs, you can take a peek at the following article." }, { "code": null, "e": 716, "s": 693, "text": "towardsdatascience.com" }, { "code": null, "e": 903, "s": 716, "text": "In this article, I will talk about the GraphSAGE architecture which is a variant of message passing neural networks (MPNN). MPNN is a fancy term for how GNNs are efficiently implemented." }, { "code": null, "e": 987, "s": 903, "text": "Any MPNN can be formally represented using the two functions aggregate and combine." }, { "code": null, "e": 1088, "s": 987, "text": "The aggregate function governs how neighbour information is gathered or aggregated for a given node." }, { "code": null, "e": 1211, "s": 1088, "text": "The combine function governs how the information of a node itself is combined with the information from the neighbourhood." }, { "code": null, "e": 1330, "s": 1211, "text": "GraphSAGE stands for Graph-SAmple-and-aggreGatE. Let’s first define the aggregate and combine functions for GraphSAGE." }, { "code": null, "e": 1388, "s": 1330, "text": "Combine — Use element-wise mean of features of neighbours" }, { "code": null, "e": 1459, "s": 1388, "text": "Aggregate — Concatenate aggregated features with current node features" }, { "code": null, "e": 1728, "s": 1459, "text": "GraphSAGE layers can be visually represented as follows. For a given node v, we aggregate all neighbours using mean aggregation. The result is concatenated with the node v’s features and fed through a multi-layer perception (MLP) followed by a non-linearity like RELU." }, { "code": null, "e": 2087, "s": 1728, "text": "One can easily use a framework such as PyTorch geometric to use GraphSAGE. Before we go there let’s build up a use case to proceed. One major importance of embedding a graph is visualization. Therefore, let’s build a GNN with GraphSAGE to visualize Cora dataset. Note that here I am using the provided example in PyTorch Geometric repository with few tricks." }, { "code": null, "e": 2375, "s": 2087, "text": "The key idea of GraphSAGE is sampling strategy. This enables the architecture to scale to very large scale applications. The sampling implies that, at each layer, only up to K number of neighbours are used. As usual, we must use an order invariant aggregator such as Mean, Max, Min, etc." }, { "code": null, "e": 2503, "s": 2375, "text": "In graph embedding, we operate in an unsupervised manner. Therefore, we use the graph topological structure to define the loss." }, { "code": null, "e": 3216, "s": 2503, "text": "Here Zu demonstrates the final layer output for node u. Zvn indicates the negative sampled node. In simple terms, the second term of the equation indicates that the negated dot product of negative (node u and any random node v) should be maximized. In other words, the cosine distance of random nodes should be further. First-term says otherwise for node v, which is a node that we need to be embedded closer to u. This v is called a positive node, which is typically obtained using a random walk starting from u. Evn~Pn(v) indicates that the negative nodes are taken from a negative sampling approach. In actual implementation, we take direct neighbours as positive samples and random nodes as negative samples." }, { "code": null, "e": 3272, "s": 3216, "text": "We can start by importing the following python modules." }, { "code": null, "e": 3716, "s": 3272, "text": "import torchimport torch.nn as nnimport torch.nn.functional as Ffrom torch_cluster import random_walkfrom sklearn.linear_model import LogisticRegressionimport torch_geometric.transforms as Tfrom torch_geometric.nn import SAGEConvfrom torch_geometric.datasets import Planetoidfrom torch_geometric.data import NeighborSampler as RawNeighborSamplerimport umapimport matplotlib.pyplot as pltimport seaborn as sns" }, { "code": null, "e": 3747, "s": 3716, "text": "Initializing the Cora dataset;" }, { "code": null, "e": 3863, "s": 3747, "text": "dataset = 'Cora'path = './data'dataset = Planetoid(path, dataset, transform=T.NormalizeFeatures())data = dataset[0]" }, { "code": null, "e": 3982, "s": 3863, "text": "Note that the dataset object is a list of subgraphs. In the case of Cora, we have one so we pick the graph in index 0." }, { "code": null, "e": 4110, "s": 3982, "text": "Sampler components (here we extend NeighborSampler class’s sample method to create batches with positive and negative samples);" }, { "code": null, "e": 4545, "s": 4110, "text": "# For each batch and the adjacency matrixpos_batch = random_walk(row, col, batch, walk_length=1, coalesced=False)[:, 1]# row are source nodes, col are target nodes from Adjacency matrix# index 1 is taken as positive nodes# Random targets from whole adjacency matrixneg_batch = torch.randint(0, self.adj_t.size(1), (batch.numel(), ), dtype=torch.long)" }, { "code": null, "e": 4588, "s": 4545, "text": "GNN can be declared in PyTorch as follows;" }, { "code": null, "e": 5593, "s": 4588, "text": "class SAGE(nn.Module): def __init__(self, in_channels, hidden_channels, num_layers): super(SAGE, self).__init__() self.num_layers = num_layers self.convs = nn.ModuleList() for i in range(num_layers): in_channels = in_channels if i == 0 else hidden_channels self.convs.append(SAGEConv(in_channels, hidden_channels)) def forward(self, x, adjs): for i, (edge_index, _, size) in enumerate(adjs): x_target = x[:size[1]] x = self.convs[i]((x, x_target), edge_index) if i != self.num_layers - 1: x = x.relu() x = F.dropout(x, p=0.5, training=self.training) return x def full_forward(self, x, edge_index): for i, conv in enumerate(self.convs): x = conv(x, edge_index) if i != self.num_layers - 1: x = x.relu() x = F.dropout(x, p=0.5, training=self.training) return x" }, { "code": null, "e": 5934, "s": 5593, "text": "Note that we use SAGEConv layers from PyTorch Geometric framework. In the forward pass, the NeighborSampler provides us with data to be passed over in each layer as data indices. This is a rather complex module so I suggest readers read the Minibatch Algorithm from paper(page 12) and the NeighborSampler module docs from PyTorch Geometric." }, { "code": null, "e": 5997, "s": 5934, "text": "Without using graph structure, the following is the UMAP plot." }, { "code": null, "e": 6070, "s": 5997, "text": "When we embed using GraphSAGE we can have a better embedding as follows;" }, { "code": null, "e": 6289, "s": 6070, "text": "We can see that the embeddings are much better and well separated compared to naive UMAP embedding. However, this is not perfect and needs more work. But I hope this is a good enough demonstration to convey the idea. 😊" }, { "code": null, "e": 6320, "s": 6289, "text": "Hope you enjoyed this article!" } ]
Program to print the given Z Pattern - GeeksforGeeks
22 Apr, 2021 Given an integer N, the task is to print the Alphabet Z Pattern as given below: 1 2 3 * * * N * * * 3 2 1 2 3 * * * N Examples: Input: N = 5 Output: 1 2 3 4 5 4 3 2 1 2 3 4 5 Input: N = 4 Output: 1 2 3 4 3 2 1 2 3 4 Approach: Print the first row with 1 to N numbers. Then from 2nd to (N-1)th row, print 2 * (N – index – 1) times blank spaces followed by the ending element which is index – 1. Print the last row with 1 to N numbers. Below is the implementation of the above approach: C++ C Java Python3 C# PHP Javascript // C++ implementation of the approach#include <iostream>using namespace std; // Function to print the desired// Alphabet Z Patternvoid alphabetPattern(int N){ int index, side_index, size; // Declaring the values of Right, // Left and Diagonal values int Top = 1, Bottom = 1, Diagonal = N - 1; // Loop for printing the first row for (index = 0; index < N; index++) cout << Top++ << " "; cout << endl; // Main Loop for the rows from (2 to n-1) for (index = 1; index < N - 1; index++) { // Spaces for the diagonals for (side_index = 0; side_index < 2 * (N - index - 1); side_index++) cout << " "; // Printing the diagonal values cout << Diagonal--; cout << endl; } // Loop for printing the last row for (index = 0; index < N; index++) cout << Bottom++ << " ";} // Driver Codeint main(){ // Number of rows int N = 5; alphabetPattern(N); return 0;} // C implementation of the approach#include <stdio.h> // Function to print the desired// Alphabet Z Patternvoid alphabet_Z_Pattern(int N){ int index, side_index, size; // Declaring the values of Right, // Left and Diagonal values int Top = 1, Bottom = 1, Diagonal = N - 1; // Loop for printing the first row for (index = 0; index < N; index++) printf("%d ", Top++); printf("\n"); // Main Loop for the rows from (2 to n-1) for (index = 1; index < N - 1; index++) { // Spaces for the diagonals for (side_index = 0; side_index < 2 * (N - index - 1); side_index++) printf(" "); // Printing the diagonal values printf("%d", Diagonal--); printf("\n"); } // Loop for printing the last row for (index = 0; index < N; index++) printf("%d ", Bottom++);} // Driver Codeint main(){ // Size of the Pattern int N = 5; alphabet_Z_Pattern(N); return 0;} // Java implementation of the approach class GFG{// Function to print the desired// Alphabet Z Patternstatic void alphabetPattern(int N){ int index, side_index; // Declaring the values of Right, // Left and Diagonal values int Top = 1, Bottom = 1, Diagonal = N - 1; // Loop for printing the first row for (index = 0; index < N; index++) System.out.print(Top++ + " "); System.out.println(); // Main Loop for the rows from (2 to n-1) for (index = 1; index < N - 1; index++) { // Spaces for the diagonals for (side_index = 0; side_index < 2 * (N - index - 1); side_index++) System.out.print(" "); // Printing the diagonal values System.out.print(Diagonal--); System.out.println(); } // Loop for printing the last row for (index = 0; index < N; index++) System.out.print(Bottom++ + " ");} // Driver Codepublic static void main(String args[]){ // Number of rows int N = 5; alphabetPattern(N);}} // This code is contributed// by Akanksha Rai # Python 3 implementation of the approach # Function to print the desired# Alphabet Z Patterndef alphabetPattern(N): # Declaring the values of Right, # Left and Diagonal values Top, Bottom, Diagonal = 1, 1, N - 1 # Loop for printing the first row for index in range(N): print(Top, end = ' ') Top += 1 print() # Main Loop for the rows from (2 to n-1) for index in range(1, N - 1): # Spaces for the diagonals for side_index in range(2 * (N - index - 1)): print(' ', end = '') # Printing the diagonal values print(Diagonal, end = '') Diagonal -= 1 print() # Loop for printing the last row for index in range(N): print(Bottom, end = ' ') Bottom += 1 # Driver Code # Number of rowsN = 5alphabetPattern(N) # This code is contributed# by SamyuktaSHegde // C# implementation of the approachusing System; class GFG{// Function to print the desired// Alphabet Z Patternstatic void alphabetPattern(int N){ int index, side_index; // Declaring the values of Right, // Left and Diagonal values int Top = 1, Bottom = 1, Diagonal = N - 1; // Loop for printing the first row for (index = 0; index < N; index++) Console.Write(Top++ + " "); Console.WriteLine(); // Main Loop for the rows from (2 to n-1) for (index = 1; index < N - 1; index++) { // Spaces for the diagonals for (side_index = 0; side_index < 2 * (N - index - 1); side_index++) Console.Write(" "); // Printing the diagonal values Console.Write(Diagonal--); Console.WriteLine(); } // Loop for printing the last row for (index = 0; index < N; index++) Console.Write(Bottom++ + " ");} // Driver Codepublic static void Main(){ // Number of rows int N = 5; alphabetPattern(N);}} // This code is contributed// by Akanksha Rai <?php// PHP implementation of the approach // Function to print the desired// Alphabet Z Patternfunction alphabetPattern($N){ $index; $side_index; $size; // Declaring the values of Right, // Left and Diagonal values $Top = 1; $Bottom = 1; $Diagonal = $N - 1; // Loop for printing the first row for ($index = 0; $index < $N; $index++) echo $Top++ . " "; echo "\n"; // Main Loop for the rows from (2 to n-1) for ($index = 1; $index < $N - 1; $index++) { // Spaces for the diagonals for ($side_index = 0; $side_index < 2 * ($N - $index - 1); $side_index++) echo " "; // Printing the diagonal values echo $Diagonal--; echo "\n"; } // Loop for printing the last row for ($index = 0; $index < $N; $index++) echo $Bottom++ . " ";} // Driver Code // Number of rows$N = 5; alphabetPattern($N); // This code is contributed by Akanksha Rai <script> // JavaScript implementation of the approach // Function to print the desired // Alphabet Z Pattern function alphabetPattern(N) { var index, side_index, size; // Declaring the values of Right, // Left and Diagonal values var Top = 1, Bottom = 1, Diagonal = N - 1; // Loop for printing the first row for (index = 0; index < N; index++) { document.write(Top + " "); Top++; } document.write("<br>"); // Main Loop for the rows from (2 to n-1) for (index = 1; index < N - 1; index++) { // Spaces for the diagonals for (side_index = 0; side_index < 2 * (N - index - 1); side_index++) document.write(" "); // Printing the diagonal values document.write(Diagonal); Diagonal--; document.write("<br>"); } // Loop for printing the last row for (index = 0; index < N; index++) { document.write(Bottom + " "); Bottom++; } } // Driver Code // Number of rows var N = 5; alphabetPattern(N); </script> 1 2 3 4 5 4 3 2 1 2 3 4 5 SamyuktaSHegde Akanksha_Rai rdtank pattern-printing C++ Programs School Programming pattern-printing Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C++ Program for QuickSort cin in C++ delete keyword in C++ Shallow Copy and Deep Copy in C++ Check if given number is perfect square Python Dictionary Arrays in C/C++ Reverse a string in Java Inheritance in C++ C++ Classes and Objects
[ { "code": null, "e": 24162, "s": 24134, "text": "\n22 Apr, 2021" }, { "code": null, "e": 24243, "s": 24162, "text": "Given an integer N, the task is to print the Alphabet Z Pattern as given below: " }, { "code": null, "e": 24311, "s": 24243, "text": "1 2 3 * * * N\n *\n *\n *\n 3\n 2\n1 2 3 * * * N" }, { "code": null, "e": 24323, "s": 24311, "text": "Examples: " }, { "code": null, "e": 24441, "s": 24323, "text": "Input: N = 5\nOutput: \n1 2 3 4 5 \n 4\n 3\n 2\n1 2 3 4 5\n\nInput: N = 4\nOutput: \n1 2 3 4\n 3\n 2\n1 2 3 4 " }, { "code": null, "e": 24454, "s": 24443, "text": "Approach: " }, { "code": null, "e": 24495, "s": 24454, "text": "Print the first row with 1 to N numbers." }, { "code": null, "e": 24621, "s": 24495, "text": "Then from 2nd to (N-1)th row, print 2 * (N – index – 1) times blank spaces followed by the ending element which is index – 1." }, { "code": null, "e": 24661, "s": 24621, "text": "Print the last row with 1 to N numbers." }, { "code": null, "e": 24714, "s": 24661, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 24718, "s": 24714, "text": "C++" }, { "code": null, "e": 24720, "s": 24718, "text": "C" }, { "code": null, "e": 24725, "s": 24720, "text": "Java" }, { "code": null, "e": 24733, "s": 24725, "text": "Python3" }, { "code": null, "e": 24736, "s": 24733, "text": "C#" }, { "code": null, "e": 24740, "s": 24736, "text": "PHP" }, { "code": null, "e": 24751, "s": 24740, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <iostream>using namespace std; // Function to print the desired// Alphabet Z Patternvoid alphabetPattern(int N){ int index, side_index, size; // Declaring the values of Right, // Left and Diagonal values int Top = 1, Bottom = 1, Diagonal = N - 1; // Loop for printing the first row for (index = 0; index < N; index++) cout << Top++ << \" \"; cout << endl; // Main Loop for the rows from (2 to n-1) for (index = 1; index < N - 1; index++) { // Spaces for the diagonals for (side_index = 0; side_index < 2 * (N - index - 1); side_index++) cout << \" \"; // Printing the diagonal values cout << Diagonal--; cout << endl; } // Loop for printing the last row for (index = 0; index < N; index++) cout << Bottom++ << \" \";} // Driver Codeint main(){ // Number of rows int N = 5; alphabetPattern(N); return 0;}", "e": 25726, "s": 24751, "text": null }, { "code": "// C implementation of the approach#include <stdio.h> // Function to print the desired// Alphabet Z Patternvoid alphabet_Z_Pattern(int N){ int index, side_index, size; // Declaring the values of Right, // Left and Diagonal values int Top = 1, Bottom = 1, Diagonal = N - 1; // Loop for printing the first row for (index = 0; index < N; index++) printf(\"%d \", Top++); printf(\"\\n\"); // Main Loop for the rows from (2 to n-1) for (index = 1; index < N - 1; index++) { // Spaces for the diagonals for (side_index = 0; side_index < 2 * (N - index - 1); side_index++) printf(\" \"); // Printing the diagonal values printf(\"%d\", Diagonal--); printf(\"\\n\"); } // Loop for printing the last row for (index = 0; index < N; index++) printf(\"%d \", Bottom++);} // Driver Codeint main(){ // Size of the Pattern int N = 5; alphabet_Z_Pattern(N); return 0;}", "e": 26694, "s": 25726, "text": null }, { "code": "// Java implementation of the approach class GFG{// Function to print the desired// Alphabet Z Patternstatic void alphabetPattern(int N){ int index, side_index; // Declaring the values of Right, // Left and Diagonal values int Top = 1, Bottom = 1, Diagonal = N - 1; // Loop for printing the first row for (index = 0; index < N; index++) System.out.print(Top++ + \" \"); System.out.println(); // Main Loop for the rows from (2 to n-1) for (index = 1; index < N - 1; index++) { // Spaces for the diagonals for (side_index = 0; side_index < 2 * (N - index - 1); side_index++) System.out.print(\" \"); // Printing the diagonal values System.out.print(Diagonal--); System.out.println(); } // Loop for printing the last row for (index = 0; index < N; index++) System.out.print(Bottom++ + \" \");} // Driver Codepublic static void main(String args[]){ // Number of rows int N = 5; alphabetPattern(N);}} // This code is contributed// by Akanksha Rai", "e": 27771, "s": 26694, "text": null }, { "code": "# Python 3 implementation of the approach # Function to print the desired# Alphabet Z Patterndef alphabetPattern(N): # Declaring the values of Right, # Left and Diagonal values Top, Bottom, Diagonal = 1, 1, N - 1 # Loop for printing the first row for index in range(N): print(Top, end = ' ') Top += 1 print() # Main Loop for the rows from (2 to n-1) for index in range(1, N - 1): # Spaces for the diagonals for side_index in range(2 * (N - index - 1)): print(' ', end = '') # Printing the diagonal values print(Diagonal, end = '') Diagonal -= 1 print() # Loop for printing the last row for index in range(N): print(Bottom, end = ' ') Bottom += 1 # Driver Code # Number of rowsN = 5alphabetPattern(N) # This code is contributed# by SamyuktaSHegde", "e": 28634, "s": 27771, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{// Function to print the desired// Alphabet Z Patternstatic void alphabetPattern(int N){ int index, side_index; // Declaring the values of Right, // Left and Diagonal values int Top = 1, Bottom = 1, Diagonal = N - 1; // Loop for printing the first row for (index = 0; index < N; index++) Console.Write(Top++ + \" \"); Console.WriteLine(); // Main Loop for the rows from (2 to n-1) for (index = 1; index < N - 1; index++) { // Spaces for the diagonals for (side_index = 0; side_index < 2 * (N - index - 1); side_index++) Console.Write(\" \"); // Printing the diagonal values Console.Write(Diagonal--); Console.WriteLine(); } // Loop for printing the last row for (index = 0; index < N; index++) Console.Write(Bottom++ + \" \");} // Driver Codepublic static void Main(){ // Number of rows int N = 5; alphabetPattern(N);}} // This code is contributed// by Akanksha Rai", "e": 29683, "s": 28634, "text": null }, { "code": "<?php// PHP implementation of the approach // Function to print the desired// Alphabet Z Patternfunction alphabetPattern($N){ $index; $side_index; $size; // Declaring the values of Right, // Left and Diagonal values $Top = 1; $Bottom = 1; $Diagonal = $N - 1; // Loop for printing the first row for ($index = 0; $index < $N; $index++) echo $Top++ . \" \"; echo \"\\n\"; // Main Loop for the rows from (2 to n-1) for ($index = 1; $index < $N - 1; $index++) { // Spaces for the diagonals for ($side_index = 0; $side_index < 2 * ($N - $index - 1); $side_index++) echo \" \"; // Printing the diagonal values echo $Diagonal--; echo \"\\n\"; } // Loop for printing the last row for ($index = 0; $index < $N; $index++) echo $Bottom++ . \" \";} // Driver Code // Number of rows$N = 5; alphabetPattern($N); // This code is contributed by Akanksha Rai", "e": 30644, "s": 29683, "text": null }, { "code": "<script> // JavaScript implementation of the approach // Function to print the desired // Alphabet Z Pattern function alphabetPattern(N) { var index, side_index, size; // Declaring the values of Right, // Left and Diagonal values var Top = 1, Bottom = 1, Diagonal = N - 1; // Loop for printing the first row for (index = 0; index < N; index++) { document.write(Top + \" \"); Top++; } document.write(\"<br>\"); // Main Loop for the rows from (2 to n-1) for (index = 1; index < N - 1; index++) { // Spaces for the diagonals for (side_index = 0; side_index < 2 * (N - index - 1); side_index++) document.write(\" \"); // Printing the diagonal values document.write(Diagonal); Diagonal--; document.write(\"<br>\"); } // Loop for printing the last row for (index = 0; index < N; index++) { document.write(Bottom + \" \"); Bottom++; } } // Driver Code // Number of rows var N = 5; alphabetPattern(N); </script>", "e": 31835, "s": 30644, "text": null }, { "code": null, "e": 31874, "s": 31835, "text": "1 2 3 4 5 \n 4\n 3\n 2\n1 2 3 4 5" }, { "code": null, "e": 31891, "s": 31876, "text": "SamyuktaSHegde" }, { "code": null, "e": 31904, "s": 31891, "text": "Akanksha_Rai" }, { "code": null, "e": 31911, "s": 31904, "text": "rdtank" }, { "code": null, "e": 31928, "s": 31911, "text": "pattern-printing" }, { "code": null, "e": 31941, "s": 31928, "text": "C++ Programs" }, { "code": null, "e": 31960, "s": 31941, "text": "School Programming" }, { "code": null, "e": 31977, "s": 31960, "text": "pattern-printing" }, { "code": null, "e": 32075, "s": 31977, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32084, "s": 32075, "text": "Comments" }, { "code": null, "e": 32097, "s": 32084, "text": "Old Comments" }, { "code": null, "e": 32123, "s": 32097, "text": "C++ Program for QuickSort" }, { "code": null, "e": 32134, "s": 32123, "text": "cin in C++" }, { "code": null, "e": 32156, "s": 32134, "text": "delete keyword in C++" }, { "code": null, "e": 32190, "s": 32156, "text": "Shallow Copy and Deep Copy in C++" }, { "code": null, "e": 32230, "s": 32190, "text": "Check if given number is perfect square" }, { "code": null, "e": 32248, "s": 32230, "text": "Python Dictionary" }, { "code": null, "e": 32264, "s": 32248, "text": "Arrays in C/C++" }, { "code": null, "e": 32289, "s": 32264, "text": "Reverse a string in Java" }, { "code": null, "e": 32308, "s": 32289, "text": "Inheritance in C++" } ]
How do I use the @ sign in MySQL?
To use the @ sign, use MySQL SET command. The @sign is used to set user-defined variables. Following is the syntax − SET @anyVariableName:=yourValue; Let us first create a table − mysql> create table DemoTable1331 -> ( -> Id int, -> Name varchar(20) -> ); Query OK, 0 rows affected (0.51 sec) Insert some records in the table using insert command − mysql> insert into DemoTable1331 values(10,'Chris'); Query OK, 1 row affected (0.71 sec) mysql> insert into DemoTable1331 values(101,'David'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable1331 values(40,'Bob'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable1331 values(30,'Mike'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable1331 values(60,'John'); Query OK, 1 row affected (0.12 sec) Display all records from the table using select statement − mysql> select * from DemoTable1331; This will produce the following output − +------+-------+ | Id | Name | +------+-------+ | 10 | Chris | | 101 | David | | 40 | Bob | | 30 | Mike | | 60 | John | +------+-------+ 5 rows in set (0.00 sec) Here is the query to use @sign in MySQL − mysql> set @Value:=40; Query OK, 0 rows affected (0.00 sec) mysql> select * from DemoTable1331 where Id > @Value; This will produce the following output − +------+-------+ | Id | Name | +------+-------+ | 101 | David | | 60 | John | +------+-------+ 2 rows in set (0.03 sec)
[ { "code": null, "e": 1179, "s": 1062, "text": "To use the @ sign, use MySQL SET command. The @sign is used to set user-defined variables. Following is the syntax −" }, { "code": null, "e": 1212, "s": 1179, "text": "SET @anyVariableName:=yourValue;" }, { "code": null, "e": 1242, "s": 1212, "text": "Let us first create a table −" }, { "code": null, "e": 1367, "s": 1242, "text": "mysql> create table DemoTable1331\n -> (\n -> Id int,\n -> Name varchar(20)\n -> );\nQuery OK, 0 rows affected (0.51 sec)" }, { "code": null, "e": 1423, "s": 1367, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1865, "s": 1423, "text": "mysql> insert into DemoTable1331 values(10,'Chris');\nQuery OK, 1 row affected (0.71 sec)\nmysql> insert into DemoTable1331 values(101,'David');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable1331 values(40,'Bob');\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into DemoTable1331 values(30,'Mike');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable1331 values(60,'John');\nQuery OK, 1 row affected (0.12 sec)" }, { "code": null, "e": 1925, "s": 1865, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1961, "s": 1925, "text": "mysql> select * from DemoTable1331;" }, { "code": null, "e": 2002, "s": 1961, "text": "This will produce the following output −" }, { "code": null, "e": 2180, "s": 2002, "text": "+------+-------+\n| Id | Name |\n+------+-------+\n| 10 | Chris |\n| 101 | David |\n| 40 | Bob |\n| 30 | Mike |\n| 60 | John |\n+------+-------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 2222, "s": 2180, "text": "Here is the query to use @sign in MySQL −" }, { "code": null, "e": 2336, "s": 2222, "text": "mysql> set @Value:=40;\nQuery OK, 0 rows affected (0.00 sec)\nmysql> select * from DemoTable1331 where Id > @Value;" }, { "code": null, "e": 2377, "s": 2336, "text": "This will produce the following output −" }, { "code": null, "e": 2504, "s": 2377, "text": "+------+-------+\n| Id | Name |\n+------+-------+\n| 101 | David |\n| 60 | John |\n+------+-------+\n2 rows in set (0.03 sec)" } ]
ReactJS value Attribute - GeeksforGeeks
04 Jun, 2021 React.js library is all about splitting the app into several components. Each Component has its own lifecycle. React provides us some in-built methods that we can override at particular stages in the life-cycle of the component. In this article, we will know how to use value attributes. The value attribute is used to set or get the value for the input field, selected, textarea. Creating React Application And Installing Module: Step 1: Create a React application using the following command.npx create-react-app foldername Step 1: Create a React application using the following command. npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command.cd foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command. cd foldername Project Structure: It will look like the following. Example 1: App.js import React from 'react';import ReactDOM from 'react-dom';import './index.css';import App from './App';import reportWebVitals from './reportWebVitals';import ReactDOMServer from 'react-dom/server'; const element = <div> <h1>GeeksforGeeks</h1> <input value='geeks'/></div>; ReactDOM.render( element, document.getElementById("root")); Output: Example 2: App.js import React from 'react';import ReactDOM from 'react-dom';import './index.css';import App from './App';import reportWebVitals from './reportWebVitals';import ReactDOMServer from 'react-dom/server';import { getConfig } from '@testing-library/dom'; const element = <div> <h1>GeeksforGeeks</h1> <input id={'input'}/> <button onClick={ get }>get value</button></div>; function get(){ var a = document.getElementById('input').value ; console.log(a)}ReactDOM.render( element, document.getElementById("root")); Output: Reference: https://reactjs.org/docs/dom-elements.html#value ReactJS Attributes ReactJS DOM Elements ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ReactJS useNavigate() Hook How to set background images in ReactJS ? Axios in React: A Guide for Beginners How to create a table in ReactJS ? How to navigate on path by button click in react router ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26071, "s": 26043, "text": "\n04 Jun, 2021" }, { "code": null, "e": 26300, "s": 26071, "text": "React.js library is all about splitting the app into several components. Each Component has its own lifecycle. React provides us some in-built methods that we can override at particular stages in the life-cycle of the component." }, { "code": null, "e": 26452, "s": 26300, "text": "In this article, we will know how to use value attributes. The value attribute is used to set or get the value for the input field, selected, textarea." }, { "code": null, "e": 26502, "s": 26452, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 26598, "s": 26502, "text": "Step 1: Create a React application using the following command.npx create-react-app foldername " }, { "code": null, "e": 26662, "s": 26598, "text": "Step 1: Create a React application using the following command." }, { "code": null, "e": 26694, "s": 26662, "text": "npx create-react-app foldername" }, { "code": null, "e": 26809, "s": 26696, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command.cd foldername" }, { "code": null, "e": 26909, "s": 26809, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command." }, { "code": null, "e": 26923, "s": 26909, "text": "cd foldername" }, { "code": null, "e": 26975, "s": 26923, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 26986, "s": 26975, "text": "Example 1:" }, { "code": null, "e": 26993, "s": 26986, "text": "App.js" }, { "code": "import React from 'react';import ReactDOM from 'react-dom';import './index.css';import App from './App';import reportWebVitals from './reportWebVitals';import ReactDOMServer from 'react-dom/server'; const element = <div> <h1>GeeksforGeeks</h1> <input value='geeks'/></div>; ReactDOM.render( element, document.getElementById(\"root\"));", "e": 27346, "s": 26993, "text": null }, { "code": null, "e": 27354, "s": 27346, "text": "Output:" }, { "code": null, "e": 27365, "s": 27354, "text": "Example 2:" }, { "code": null, "e": 27372, "s": 27365, "text": "App.js" }, { "code": "import React from 'react';import ReactDOM from 'react-dom';import './index.css';import App from './App';import reportWebVitals from './reportWebVitals';import ReactDOMServer from 'react-dom/server';import { getConfig } from '@testing-library/dom'; const element = <div> <h1>GeeksforGeeks</h1> <input id={'input'}/> <button onClick={ get }>get value</button></div>; function get(){ var a = document.getElementById('input').value ; console.log(a)}ReactDOM.render( element, document.getElementById(\"root\"));", "e": 27902, "s": 27372, "text": null }, { "code": null, "e": 27910, "s": 27902, "text": "Output:" }, { "code": null, "e": 27970, "s": 27910, "text": "Reference: https://reactjs.org/docs/dom-elements.html#value" }, { "code": null, "e": 27989, "s": 27970, "text": "ReactJS Attributes" }, { "code": null, "e": 28010, "s": 27989, "text": "ReactJS DOM Elements" }, { "code": null, "e": 28018, "s": 28010, "text": "ReactJS" }, { "code": null, "e": 28035, "s": 28018, "text": "Web Technologies" }, { "code": null, "e": 28133, "s": 28035, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28160, "s": 28133, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 28202, "s": 28160, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 28240, "s": 28202, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 28275, "s": 28240, "text": "How to create a table in ReactJS ?" }, { "code": null, "e": 28333, "s": 28275, "text": "How to navigate on path by button click in react router ?" }, { "code": null, "e": 28373, "s": 28333, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28406, "s": 28373, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28451, "s": 28406, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28501, "s": 28451, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to Perform CRUD Operations in Room Database in Android? - GeeksforGeeks
28 Nov, 2021 Data from the app can be saved on users’ devices in different ways. We can store data in the user’s device in SQLite tables, shared preferences, and many more ways. In this article, we will take a look at saving data, reading, updating, and deleting data in Room Database on Android. We will perform CRUD operations using Room Database on Android. In this article, we will take a look at performing CRUD operations in Room Database in Android. We will be building a simple application in which we will be adding the different types of courses that are available on Geeks for Geeks. We will be storing all this data in Room Database and performing CRUD operations on these courses. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. Room is a persistence library that provides an abstraction layer over the SQLite database to allow a more robust database. With the help of room, we can easily create the database and perform CRUD operations very easily. The three main components of the room are Entity, Database, and DAO. Entity: Entity is a modal class that is annotated with @Entity. This class is having variables that will be our columns and the class is our table. Database: It is an abstract class where we will be storing all our database entries which we can call Entities. DAO: The full form of DAO is a Database access object which is an interface class with the help of it we can perform different operations in our database. Now, let’s move towards the implementation of Room Database in Android. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Adding dependency for using Room in build.gradle files Navigate to the app > Gradle Scripts > build.gradle file and add the below dependencies in the dependencies section. // add below dependency for using room. implementation ‘androidx.room:room-runtime:2.2.5’ annotationProcessor ‘androidx.room:room-compiler:2.2.5’ // add below dependency for using lifecycle extensions for room. implementation ‘androidx.lifecycle:lifecycle-extensions:2.2.0’ annotationProcessor ‘androidx.lifecycle:lifecycle-compiler:2.2.0’ After adding the above dependencies section. Now sync your project and we will move towards our XML file. Step 3: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <!--recycler view to display our data--> <androidx.recyclerview.widget.RecyclerView android:id="@+id/idRVCourses" android:layout_width="match_parent" android:layout_height="match_parent" /> <!--fab to add new courses--> <com.google.android.material.floatingactionbutton.FloatingActionButton android:id="@+id/idFABAdd" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentEnd="true" android:layout_alignParentBottom="true" android:layout_marginStart="18dp" android:layout_marginTop="18dp" android:layout_marginEnd="18dp" android:layout_marginBottom="18dp" android:src="@android:drawable/ic_input_add" app:tint="@color/white" /> </RelativeLayout> Step 4: Creating a modal class for storing our data Navigate to the app > java > your apps package name > Right-click on it > New > Java class and name the class as CourseModal and add the below code to it. Comments are added inside the code to understand the code in more detail. Java import androidx.room.Entity;import androidx.room.PrimaryKey; // below line is for setting table name.@Entity(tableName = "course_table")public class CourseModal { // below line is to auto increment // id for each course. @PrimaryKey(autoGenerate = true) // variable for our id. private int id; // below line is a variable // for course name. private String courseName; // below line is use for // course description. private String courseDescription; // below line is use // for course duration. private String courseDuration; // below line we are creating constructor class. // inside constructor class we are not passing // our id because it is incrementing automatically public CourseModal(String courseName, String courseDescription, String courseDuration) { this.courseName = courseName; this.courseDescription = courseDescription; this.courseDuration = courseDuration; } // on below line we are creating // getter and setter methods. public String getCourseName() { return courseName; } public void setCourseName(String courseName) { this.courseName = courseName; } public String getCourseDescription() { return courseDescription; } public void setCourseDescription(String courseDescription) { this.courseDescription = courseDescription; } public String getCourseDuration() { return courseDuration; } public void setCourseDuration(String courseDuration) { this.courseDuration = courseDuration; } public int getId() { return id; } public void setId(int id) { this.id = id; }} Step 5: Creating a Dao interface for our database Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name as Dao and select Interface. After creating an interface class and add the below code to it. Comments are added inside the code to understand the code in more detail. Java import androidx.lifecycle.LiveData;import androidx.room.Delete;import androidx.room.Insert;import androidx.room.Query;import androidx.room.Update; import java.util.List; // Adding annotation // to our Dao [email protected] interface Dao { // below method is use to // add data to database. @Insert void insert(CourseModal model); // below method is use to update // the data in our database. @Update void update(CourseModal model); // below line is use to delete a // specific course in our database. @Delete void delete(CourseModal model); // on below line we are making query to // delete all courses from our database. @Query("DELETE FROM course_table") void deleteAllCourses(); // below line is to read all the courses from our database. // in this we are ordering our courses in ascending order // with our course name. @Query("SELECT * FROM course_table ORDER BY courseName ASC") LiveData<List<CourseModal>> getAllCourses();} Step 6: Creating a database class Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as CourseDatabase and add the below code to it. Comments are added inside the code to understand the code in more detail. Java import android.content.Context;import android.os.AsyncTask; import androidx.annotation.NonNull;import androidx.room.Database;import androidx.room.Room;import androidx.room.RoomDatabase;import androidx.sqlite.db.SupportSQLiteDatabase; // adding annotation for our database entities and db version.@Database(entities = {CourseModal.class}, version = 1)public abstract class CourseDatabase extends RoomDatabase { // below line is to create instance // for our database class. private static CourseDatabase instance; // below line is to create // abstract variable for dao. public abstract Dao Dao(); // on below line we are getting instance for our database. public static synchronized CourseDatabase getInstance(Context context) { // below line is to check if // the instance is null or not. if (instance == null) { // if the instance is null we // are creating a new instance instance = // for creating a instance for our database // we are creating a database builder and passing // our database class with our database name. Room.databaseBuilder(context.getApplicationContext(), CourseDatabase.class, "course_database") // below line is use to add fall back to // destructive migration to our database. .fallbackToDestructiveMigration() // below line is to add callback // to our database. .addCallback(roomCallback) // below line is to // build our database. .build(); } // after creating an instance // we are returning our instance return instance; } // below line is to create a callback for our room database. private static RoomDatabase.Callback roomCallback = new RoomDatabase.Callback() { @Override public void onCreate(@NonNull SupportSQLiteDatabase db) { super.onCreate(db); // this method is called when database is created // and below line is to populate our data. new PopulateDbAsyncTask(instance).execute(); } }; // we are creating an async task class to perform task in background. private static class PopulateDbAsyncTask extends AsyncTask<Void, Void, Void> { PopulateDbAsyncTask(CourseDatabase instance) { Dao dao = instance.Dao(); } @Override protected Void doInBackground(Void... voids) { return null; } }} Step 7: Create a new java class for our Repository Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as CourseRepository and add the below code to it. Comments are added inside the code to understand the code in more detail. Java import android.app.Application;import android.os.AsyncTask; import androidx.lifecycle.LiveData; import java.util.List; public class CourseRepository { // below line is the create a variable // for dao and list for all courses. private Dao dao; private LiveData<List<CourseModal>> allCourses; // creating a constructor for our variables // and passing the variables to it. public CourseRepository(Application application) { CourseDatabase database = CourseDatabase.getInstance(application); dao = database.Dao(); allCourses = dao.getAllCourses(); } // creating a method to insert the data to our database. public void insert(CourseModal model) { new InsertCourseAsyncTask(dao).execute(model); } // creating a method to update data in database. public void update(CourseModal model) { new UpdateCourseAsyncTask(dao).execute(model); } // creating a method to delete the data in our database. public void delete(CourseModal model) { new DeleteCourseAsyncTask(dao).execute(model); } // below is the method to delete all the courses. public void deleteAllCourses() { new DeleteAllCoursesAsyncTask(dao).execute(); } // below method is to read all the courses. public LiveData<List<CourseModal>> getAllCourses() { return allCourses; } // we are creating a async task method to insert new course. private static class InsertCourseAsyncTask extends AsyncTask<CourseModal, Void, Void> { private Dao dao; private InsertCourseAsyncTask(Dao dao) { this.dao = dao; } @Override protected Void doInBackground(CourseModal... model) { // below line is use to insert our modal in dao. dao.insert(model[0]); return null; } } // we are creating a async task method to update our course. private static class UpdateCourseAsyncTask extends AsyncTask<CourseModal, Void, Void> { private Dao dao; private UpdateCourseAsyncTask(Dao dao) { this.dao = dao; } @Override protected Void doInBackground(CourseModal... models) { // below line is use to update // our modal in dao. dao.update(models[0]); return null; } } // we are creating a async task method to delete course. private static class DeleteCourseAsyncTask extends AsyncTask<CourseModal, Void, Void> { private Dao dao; private DeleteCourseAsyncTask(Dao dao) { this.dao = dao; } @Override protected Void doInBackground(CourseModal... models) { // below line is use to delete // our course modal in dao. dao.delete(models[0]); return null; } } // we are creating a async task method to delete all courses. private static class DeleteAllCoursesAsyncTask extends AsyncTask<Void, Void, Void> { private Dao dao; private DeleteAllCoursesAsyncTask(Dao dao) { this.dao = dao; } @Override protected Void doInBackground(Void... voids) { // on below line calling method // to delete all courses. dao.deleteAllCourses(); return null; } }} Step 8: Creating a class for our Repository Navigate to the app > java > your app’s package name > Right-click on it > New > Java Class and name the class as ViewModal and add the below code to it. Comments are added inside the code to understand the code in more detail. Java import android.app.Application; import androidx.annotation.NonNull;import androidx.lifecycle.AndroidViewModel;import androidx.lifecycle.LiveData; import java.util.List; public class ViewModal extends AndroidViewModel { // creating a new variable for course repository. private CourseRepository repository; // below line is to create a variable for live // data where all the courses are present. private LiveData<List<CourseModal>> allCourses; // constructor for our view modal. public ViewModal(@NonNull Application application) { super(application); repository = new CourseRepository(application); allCourses = repository.getAllCourses(); } // below method is use to insert the data to our repository. public void insert(CourseModal model) { repository.insert(model); } // below line is to update data in our repository. public void update(CourseModal model) { repository.update(model); } // below line is to delete the data in our repository. public void delete(CourseModal model) { repository.delete(model); } // below method is to delete all the courses in our list. public void deleteAllCourses() { repository.deleteAllCourses(); } // below method is to get all the courses in our list. public LiveData<List<CourseModal>> getAllCourses() { return allCourses; }} Step 9: Creating a layout file for each item of RecyclerView Navigate to the app > res > layout > Right-click on it > New > layout resource file and name it as course_rv_item and add below code to it. Comments are added in the code to get to know in more detail. XML <?xml version="1.0" encoding="utf-8"?><androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:elevation="8dp" app:cardCornerRadius="8dp"> <LinearLayout android:id="@+id/idLLCourse" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:orientation="vertical"> <!--text view for our course name--> <TextView android:id="@+id/idTVCourseName" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="8dp" android:text="Course Name" android:textColor="@color/black" android:textSize="15sp" /> <!--text view for our course duration--> <TextView android:id="@+id/idTVCourseDuration" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="8dp" android:text="Course Duration" android:textColor="@color/black" android:textSize="15sp" /> <!--text view for our course description--> <TextView android:id="@+id/idTVCourseDescription" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="8dp" android:text="Course Description" android:textColor="@color/black" android:textSize="15sp" /> </LinearLayout> </androidx.cardview.widget.CardView> Step 10: Creating a RecyclerView Adapter class to set data for each item of RecyclerView Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as CourseRVAdapter and add the below code to it. Comments are added inside the code to understand the code in more detail. Java import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.DiffUtil;import androidx.recyclerview.widget.ListAdapter;import androidx.recyclerview.widget.RecyclerView; public class CourseRVAdapter extends ListAdapter<CourseModal, CourseRVAdapter.ViewHolder> { // creating a variable for on item click listener. private OnItemClickListener listener; // creating a constructor class for our adapter class. CourseRVAdapter() { super(DIFF_CALLBACK); } // creating a call back for item of recycler view. private static final DiffUtil.ItemCallback<CourseModal> DIFF_CALLBACK = new DiffUtil.ItemCallback<CourseModal>() { @Override public boolean areItemsTheSame(CourseModal oldItem, CourseModal newItem) { return oldItem.getId() == newItem.getId(); } @Override public boolean areContentsTheSame(CourseModal oldItem, CourseModal newItem) { // below line is to check the course name, description and course duration. return oldItem.getCourseName().equals(newItem.getCourseName()) && oldItem.getCourseDescription().equals(newItem.getCourseDescription()) && oldItem.getCourseDuration().equals(newItem.getCourseDuration()); } }; @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // below line is use to inflate our layout // file for each item of our recycler view. View item = LayoutInflater.from(parent.getContext()) .inflate(R.layout.course_rv_item, parent, false); return new ViewHolder(item); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { // below line of code is use to set data to // each item of our recycler view. CourseModal model = getCourseAt(position); holder.courseNameTV.setText(model.getCourseName()); holder.courseDescTV.setText(model.getCourseDescription()); holder.courseDurationTV.setText(model.getCourseDuration()); } // creating a method to get course modal for a specific position. public CourseModal getCourseAt(int position) { return getItem(position); } public class ViewHolder extends RecyclerView.ViewHolder { // view holder class to create a variable for each view. TextView courseNameTV, courseDescTV, courseDurationTV; ViewHolder(@NonNull View itemView) { super(itemView); // initializing each view of our recycler view. courseNameTV = itemView.findViewById(R.id.idTVCourseName); courseDescTV = itemView.findViewById(R.id.idTVCourseDescription); courseDurationTV = itemView.findViewById(R.id.idTVCourseDuration); // adding on click listener for each item of recycler view. itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // inside on click listener we are passing // position to our item of recycler view. int position = getAdapterPosition(); if (listener != null && position != RecyclerView.NO_POSITION) { listener.onItemClick(getItem(position)); } } }); } } public interface OnItemClickListener { void onItemClick(CourseModal model); } public void setOnItemClickListener(OnItemClickListener listener) { this.listener = listener; }} Step 11: Creating a new Activity for Adding and Updating our Course Navigate to the app > java > your app’s package name > Right-click on it > New > Empty Activity and name it as NewCourseActivity and go to XML part and add below code to it. Below is the code for the activity_new_course.xml file. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".NewCourseActivity"> <!--edit text for our course name--> <EditText android:id="@+id/idEdtCourseName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:hint="Enter Course Name" /> <!--edit text for our course description--> <EditText android:id="@+id/idEdtCourseDescription" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:hint="Enter Course Description" /> <!--edit text for course description--> <EditText android:id="@+id/idEdtCourseDuration" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:hint="Course Duration" /> <!--button for saving data to room database--> <Button android:id="@+id/idBtnSaveCourse" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:padding="5dp" android:text="Save your course" android:textAllCaps="false" /> </LinearLayout> Step 12: Working with the NewCourseActivity.java file Navigate to the app > java > your app’s package name > NewCourseActivity.java file and add the below code to it. Comments are added inside the code to understand the code in more detail. Java import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; public class NewCourseActivity extends AppCompatActivity { // creating a variables for our button and edittext. private EditText courseNameEdt, courseDescEdt, courseDurationEdt; private Button courseBtn; // creating a constant string variable for our // course name, description and duration. public static final String EXTRA_ID = "com.gtappdevelopers.gfgroomdatabase.EXTRA_ID"; public static final String EXTRA_COURSE_NAME = "com.gtappdevelopers.gfgroomdatabase.EXTRA_COURSE_NAME"; public static final String EXTRA_DESCRIPTION = "com.gtappdevelopers.gfgroomdatabase.EXTRA_COURSE_DESCRIPTION"; public static final String EXTRA_DURATION = "com.gtappdevelopers.gfgroomdatabase.EXTRA_COURSE_DURATION"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_new_course); // initializing our variables for each view. courseNameEdt = findViewById(R.id.idEdtCourseName); courseDescEdt = findViewById(R.id.idEdtCourseDescription); courseDurationEdt = findViewById(R.id.idEdtCourseDuration); courseBtn = findViewById(R.id.idBtnSaveCourse); // below line is to get intent as we // are getting data via an intent. Intent intent = getIntent(); if (intent.hasExtra(EXTRA_ID)) { // if we get id for our data then we are // setting values to our edit text fields. courseNameEdt.setText(intent.getStringExtra(EXTRA_COURSE_NAME)); courseDescEdt.setText(intent.getStringExtra(EXTRA_DESCRIPTION)); courseDurationEdt.setText(intent.getStringExtra(EXTRA_DURATION)); } // adding on click listener for our save button. courseBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // getting text value from edittext and validating if // the text fields are empty or not. String courseName = courseNameEdt.getText().toString(); String courseDesc = courseDescEdt.getText().toString(); String courseDuration = courseDurationEdt.getText().toString(); if (courseName.isEmpty() || courseDesc.isEmpty() || courseDuration.isEmpty()) { Toast.makeText(NewCourseActivity.this, "Please enter the valid course details.", Toast.LENGTH_SHORT).show(); return; } // calling a method to save our course. saveCourse(courseName, courseDesc, courseDuration); } }); } private void saveCourse(String courseName, String courseDescription, String courseDuration) { // inside this method we are passing // all the data via an intent. Intent data = new Intent(); // in below line we are passing all our course detail. data.putExtra(EXTRA_COURSE_NAME, courseName); data.putExtra(EXTRA_DESCRIPTION, courseDescription); data.putExtra(EXTRA_DURATION, courseDuration); int id = getIntent().getIntExtra(EXTRA_ID, -1); if (id != -1) { // in below line we are passing our id. data.putExtra(EXTRA_ID, id); } // at last we are setting result as data. setResult(RESULT_OK, data); // displaying a toast message after adding the data Toast.makeText(this, "Course has been saved to Room Database. ", Toast.LENGTH_SHORT).show(); }} Step 13: Working with the MainActivity.java file Navigate to the app > java > your app’s package name > MainActivity.java file and add the below code to it. Comments are added inside the code to understand the code in more detail. Java import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.annotation.Nullable;import androidx.appcompat.app.AppCompatActivity;import androidx.lifecycle.Observer;import androidx.lifecycle.ViewModelProviders;import androidx.recyclerview.widget.ItemTouchHelper;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView; import com.google.android.material.floatingactionbutton.FloatingActionButton; import java.util.List; public class MainActivity extends AppCompatActivity { // creating a variables for our recycler view. private RecyclerView coursesRV; private static final int ADD_COURSE_REQUEST = 1; private static final int EDIT_COURSE_REQUEST = 2; private ViewModal viewmodal; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our variable for our recycler view and fab. coursesRV = findViewById(R.id.idRVCourses); FloatingActionButton fab = findViewById(R.id.idFABAdd); // adding on click listener for floating action button. fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // starting a new activity for adding a new course // and passing a constant value in it. Intent intent = new Intent(MainActivity.this, NewCourseActivity.class); startActivityForResult(intent, ADD_COURSE_REQUEST); } }); // setting layout manager to our adapter class. coursesRV.setLayoutManager(new LinearLayoutManager(this)); coursesRV.setHasFixedSize(true); // initializing adapter for recycler view. final CourseRVAdapter adapter = new CourseRVAdapter(); // setting adapter class for recycler view. coursesRV.setAdapter(adapter); // passing a data from view modal. viewmodal = ViewModelProviders.of(this).get(ViewModal.class); // below line is use to get all the courses from view modal. viewmodal.getAllCourses().observe(this, new Observer<List<CourseModal>>() { @Override public void onChanged(List<CourseModal> models) { // when the data is changed in our models we are // adding that list to our adapter class. adapter.submitList(models); } }); // below method is use to add swipe to delete method for item of recycler view. new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) { @Override public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) { return false; } @Override public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) { // on recycler view item swiped then we are deleting the item of our recycler view. viewmodal.delete(adapter.getCourseAt(viewHolder.getAdapterPosition())); Toast.makeText(MainActivity.this, "Course deleted", Toast.LENGTH_SHORT).show(); } }). // below line is use to attach this to recycler view. attachToRecyclerView(coursesRV); // below line is use to set item click listener for our item of recycler view. adapter.setOnItemClickListener(new CourseRVAdapter.OnItemClickListener() { @Override public void onItemClick(CourseModal model) { // after clicking on item of recycler view // we are opening a new activity and passing // a data to our activity. Intent intent = new Intent(MainActivity.this, NewCourseActivity.class); intent.putExtra(NewCourseActivity.EXTRA_ID, model.getId()); intent.putExtra(NewCourseActivity.EXTRA_COURSE_NAME, model.getCourseName()); intent.putExtra(NewCourseActivity.EXTRA_DESCRIPTION, model.getCourseDescription()); intent.putExtra(NewCourseActivity.EXTRA_DURATION, model.getCourseDuration()); // below line is to start a new activity and // adding a edit course constant. startActivityForResult(intent, EDIT_COURSE_REQUEST); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == ADD_COURSE_REQUEST && resultCode == RESULT_OK) { String courseName = data.getStringExtra(NewCourseActivity.EXTRA_COURSE_NAME); String courseDescription = data.getStringExtra(NewCourseActivity.EXTRA_DESCRIPTION); String courseDuration = data.getStringExtra(NewCourseActivity.EXTRA_DURATION); CourseModal model = new CourseModal(courseName, courseDescription, courseDuration); viewmodal.insert(model); Toast.makeText(this, "Course saved", Toast.LENGTH_SHORT).show(); } else if (requestCode == EDIT_COURSE_REQUEST && resultCode == RESULT_OK) { int id = data.getIntExtra(NewCourseActivity.EXTRA_ID, -1); if (id == -1) { Toast.makeText(this, "Course can't be updated", Toast.LENGTH_SHORT).show(); return; } String courseName = data.getStringExtra(NewCourseActivity.EXTRA_COURSE_NAME); String courseDesc = data.getStringExtra(NewCourseActivity.EXTRA_DESCRIPTION); String courseDuration = data.getStringExtra(NewCourseActivity.EXTRA_DURATION); CourseModal model = new CourseModal(courseName, courseDesc, courseDuration); model.setId(id); viewmodal.update(model); Toast.makeText(this, "Course updated", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "Course not saved", Toast.LENGTH_SHORT).show(); } }} Now run your app and see the output of the app. Check out the project on the below link: https://github.com/ChaitanyaMunje/GFG-Room-Database kapoorsagar226 android Technical Scripter 2020 Android Java Technical Scripter Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Create and Add Data to SQLite Database in Android? Resource Raw Folder in Android Studio Broadcast Receiver in Android With Example Services in Android with Example Android RecyclerView in Kotlin Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples
[ { "code": null, "e": 26034, "s": 26006, "text": "\n28 Nov, 2021" }, { "code": null, "e": 26479, "s": 26034, "text": "Data from the app can be saved on users’ devices in different ways. We can store data in the user’s device in SQLite tables, shared preferences, and many more ways. In this article, we will take a look at saving data, reading, updating, and deleting data in Room Database on Android. We will perform CRUD operations using Room Database on Android. In this article, we will take a look at performing CRUD operations in Room Database in Android. " }, { "code": null, "e": 26883, "s": 26479, "text": "We will be building a simple application in which we will be adding the different types of courses that are available on Geeks for Geeks. We will be storing all this data in Room Database and performing CRUD operations on these courses. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 27105, "s": 26883, "text": "Room is a persistence library that provides an abstraction layer over the SQLite database to allow a more robust database. With the help of room, we can easily create the database and perform CRUD operations very easily. " }, { "code": null, "e": 27175, "s": 27105, "text": "The three main components of the room are Entity, Database, and DAO. " }, { "code": null, "e": 27323, "s": 27175, "text": "Entity: Entity is a modal class that is annotated with @Entity. This class is having variables that will be our columns and the class is our table." }, { "code": null, "e": 27435, "s": 27323, "text": "Database: It is an abstract class where we will be storing all our database entries which we can call Entities." }, { "code": null, "e": 27590, "s": 27435, "text": "DAO: The full form of DAO is a Database access object which is an interface class with the help of it we can perform different operations in our database." }, { "code": null, "e": 27663, "s": 27590, "text": "Now, let’s move towards the implementation of Room Database in Android. " }, { "code": null, "e": 27692, "s": 27663, "text": "Step 1: Create a New Project" }, { "code": null, "e": 27854, "s": 27692, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 27917, "s": 27854, "text": "Step 2: Adding dependency for using Room in build.gradle files" }, { "code": null, "e": 28035, "s": 27917, "text": "Navigate to the app > Gradle Scripts > build.gradle file and add the below dependencies in the dependencies section. " }, { "code": null, "e": 28077, "s": 28035, "text": "// add below dependency for using room. " }, { "code": null, "e": 28127, "s": 28077, "text": "implementation ‘androidx.room:room-runtime:2.2.5’" }, { "code": null, "e": 28183, "s": 28127, "text": "annotationProcessor ‘androidx.room:room-compiler:2.2.5’" }, { "code": null, "e": 28250, "s": 28183, "text": "// add below dependency for using lifecycle extensions for room. " }, { "code": null, "e": 28313, "s": 28250, "text": "implementation ‘androidx.lifecycle:lifecycle-extensions:2.2.0’" }, { "code": null, "e": 28379, "s": 28313, "text": "annotationProcessor ‘androidx.lifecycle:lifecycle-compiler:2.2.0’" }, { "code": null, "e": 28486, "s": 28379, "text": "After adding the above dependencies section. Now sync your project and we will move towards our XML file. " }, { "code": null, "e": 28535, "s": 28486, "text": "Step 3: Working with the activity_main.xml file " }, { "code": null, "e": 28678, "s": 28535, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. " }, { "code": null, "e": 28682, "s": 28678, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <!--recycler view to display our data--> <androidx.recyclerview.widget.RecyclerView android:id=\"@+id/idRVCourses\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" /> <!--fab to add new courses--> <com.google.android.material.floatingactionbutton.FloatingActionButton android:id=\"@+id/idFABAdd\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignParentEnd=\"true\" android:layout_alignParentBottom=\"true\" android:layout_marginStart=\"18dp\" android:layout_marginTop=\"18dp\" android:layout_marginEnd=\"18dp\" android:layout_marginBottom=\"18dp\" android:src=\"@android:drawable/ic_input_add\" app:tint=\"@color/white\" /> </RelativeLayout>", "e": 29861, "s": 28682, "text": null }, { "code": null, "e": 29913, "s": 29861, "text": "Step 4: Creating a modal class for storing our data" }, { "code": null, "e": 30143, "s": 29913, "text": "Navigate to the app > java > your apps package name > Right-click on it > New > Java class and name the class as CourseModal and add the below code to it. Comments are added inside the code to understand the code in more detail. " }, { "code": null, "e": 30148, "s": 30143, "text": "Java" }, { "code": "import androidx.room.Entity;import androidx.room.PrimaryKey; // below line is for setting table name.@Entity(tableName = \"course_table\")public class CourseModal { // below line is to auto increment // id for each course. @PrimaryKey(autoGenerate = true) // variable for our id. private int id; // below line is a variable // for course name. private String courseName; // below line is use for // course description. private String courseDescription; // below line is use // for course duration. private String courseDuration; // below line we are creating constructor class. // inside constructor class we are not passing // our id because it is incrementing automatically public CourseModal(String courseName, String courseDescription, String courseDuration) { this.courseName = courseName; this.courseDescription = courseDescription; this.courseDuration = courseDuration; } // on below line we are creating // getter and setter methods. public String getCourseName() { return courseName; } public void setCourseName(String courseName) { this.courseName = courseName; } public String getCourseDescription() { return courseDescription; } public void setCourseDescription(String courseDescription) { this.courseDescription = courseDescription; } public String getCourseDuration() { return courseDuration; } public void setCourseDuration(String courseDuration) { this.courseDuration = courseDuration; } public int getId() { return id; } public void setId(int id) { this.id = id; }}", "e": 31865, "s": 30148, "text": null }, { "code": null, "e": 31915, "s": 31865, "text": "Step 5: Creating a Dao interface for our database" }, { "code": null, "e": 32183, "s": 31915, "text": "Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name as Dao and select Interface. After creating an interface class and add the below code to it. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 32188, "s": 32183, "text": "Java" }, { "code": "import androidx.lifecycle.LiveData;import androidx.room.Delete;import androidx.room.Insert;import androidx.room.Query;import androidx.room.Update; import java.util.List; // Adding annotation // to our Dao [email protected] interface Dao { // below method is use to // add data to database. @Insert void insert(CourseModal model); // below method is use to update // the data in our database. @Update void update(CourseModal model); // below line is use to delete a // specific course in our database. @Delete void delete(CourseModal model); // on below line we are making query to // delete all courses from our database. @Query(\"DELETE FROM course_table\") void deleteAllCourses(); // below line is to read all the courses from our database. // in this we are ordering our courses in ascending order // with our course name. @Query(\"SELECT * FROM course_table ORDER BY courseName ASC\") LiveData<List<CourseModal>> getAllCourses();}", "e": 33211, "s": 32188, "text": null }, { "code": null, "e": 33245, "s": 33211, "text": "Step 6: Creating a database class" }, { "code": null, "e": 33471, "s": 33245, "text": "Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as CourseDatabase and add the below code to it. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 33476, "s": 33471, "text": "Java" }, { "code": "import android.content.Context;import android.os.AsyncTask; import androidx.annotation.NonNull;import androidx.room.Database;import androidx.room.Room;import androidx.room.RoomDatabase;import androidx.sqlite.db.SupportSQLiteDatabase; // adding annotation for our database entities and db version.@Database(entities = {CourseModal.class}, version = 1)public abstract class CourseDatabase extends RoomDatabase { // below line is to create instance // for our database class. private static CourseDatabase instance; // below line is to create // abstract variable for dao. public abstract Dao Dao(); // on below line we are getting instance for our database. public static synchronized CourseDatabase getInstance(Context context) { // below line is to check if // the instance is null or not. if (instance == null) { // if the instance is null we // are creating a new instance instance = // for creating a instance for our database // we are creating a database builder and passing // our database class with our database name. Room.databaseBuilder(context.getApplicationContext(), CourseDatabase.class, \"course_database\") // below line is use to add fall back to // destructive migration to our database. .fallbackToDestructiveMigration() // below line is to add callback // to our database. .addCallback(roomCallback) // below line is to // build our database. .build(); } // after creating an instance // we are returning our instance return instance; } // below line is to create a callback for our room database. private static RoomDatabase.Callback roomCallback = new RoomDatabase.Callback() { @Override public void onCreate(@NonNull SupportSQLiteDatabase db) { super.onCreate(db); // this method is called when database is created // and below line is to populate our data. new PopulateDbAsyncTask(instance).execute(); } }; // we are creating an async task class to perform task in background. private static class PopulateDbAsyncTask extends AsyncTask<Void, Void, Void> { PopulateDbAsyncTask(CourseDatabase instance) { Dao dao = instance.Dao(); } @Override protected Void doInBackground(Void... voids) { return null; } }}", "e": 36218, "s": 33476, "text": null }, { "code": null, "e": 36269, "s": 36218, "text": "Step 7: Create a new java class for our Repository" }, { "code": null, "e": 36497, "s": 36269, "text": "Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as CourseRepository and add the below code to it. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 36502, "s": 36497, "text": "Java" }, { "code": "import android.app.Application;import android.os.AsyncTask; import androidx.lifecycle.LiveData; import java.util.List; public class CourseRepository { // below line is the create a variable // for dao and list for all courses. private Dao dao; private LiveData<List<CourseModal>> allCourses; // creating a constructor for our variables // and passing the variables to it. public CourseRepository(Application application) { CourseDatabase database = CourseDatabase.getInstance(application); dao = database.Dao(); allCourses = dao.getAllCourses(); } // creating a method to insert the data to our database. public void insert(CourseModal model) { new InsertCourseAsyncTask(dao).execute(model); } // creating a method to update data in database. public void update(CourseModal model) { new UpdateCourseAsyncTask(dao).execute(model); } // creating a method to delete the data in our database. public void delete(CourseModal model) { new DeleteCourseAsyncTask(dao).execute(model); } // below is the method to delete all the courses. public void deleteAllCourses() { new DeleteAllCoursesAsyncTask(dao).execute(); } // below method is to read all the courses. public LiveData<List<CourseModal>> getAllCourses() { return allCourses; } // we are creating a async task method to insert new course. private static class InsertCourseAsyncTask extends AsyncTask<CourseModal, Void, Void> { private Dao dao; private InsertCourseAsyncTask(Dao dao) { this.dao = dao; } @Override protected Void doInBackground(CourseModal... model) { // below line is use to insert our modal in dao. dao.insert(model[0]); return null; } } // we are creating a async task method to update our course. private static class UpdateCourseAsyncTask extends AsyncTask<CourseModal, Void, Void> { private Dao dao; private UpdateCourseAsyncTask(Dao dao) { this.dao = dao; } @Override protected Void doInBackground(CourseModal... models) { // below line is use to update // our modal in dao. dao.update(models[0]); return null; } } // we are creating a async task method to delete course. private static class DeleteCourseAsyncTask extends AsyncTask<CourseModal, Void, Void> { private Dao dao; private DeleteCourseAsyncTask(Dao dao) { this.dao = dao; } @Override protected Void doInBackground(CourseModal... models) { // below line is use to delete // our course modal in dao. dao.delete(models[0]); return null; } } // we are creating a async task method to delete all courses. private static class DeleteAllCoursesAsyncTask extends AsyncTask<Void, Void, Void> { private Dao dao; private DeleteAllCoursesAsyncTask(Dao dao) { this.dao = dao; } @Override protected Void doInBackground(Void... voids) { // on below line calling method // to delete all courses. dao.deleteAllCourses(); return null; } }}", "e": 39838, "s": 36502, "text": null }, { "code": null, "e": 39882, "s": 39838, "text": "Step 8: Creating a class for our Repository" }, { "code": null, "e": 40110, "s": 39882, "text": "Navigate to the app > java > your app’s package name > Right-click on it > New > Java Class and name the class as ViewModal and add the below code to it. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 40115, "s": 40110, "text": "Java" }, { "code": "import android.app.Application; import androidx.annotation.NonNull;import androidx.lifecycle.AndroidViewModel;import androidx.lifecycle.LiveData; import java.util.List; public class ViewModal extends AndroidViewModel { // creating a new variable for course repository. private CourseRepository repository; // below line is to create a variable for live // data where all the courses are present. private LiveData<List<CourseModal>> allCourses; // constructor for our view modal. public ViewModal(@NonNull Application application) { super(application); repository = new CourseRepository(application); allCourses = repository.getAllCourses(); } // below method is use to insert the data to our repository. public void insert(CourseModal model) { repository.insert(model); } // below line is to update data in our repository. public void update(CourseModal model) { repository.update(model); } // below line is to delete the data in our repository. public void delete(CourseModal model) { repository.delete(model); } // below method is to delete all the courses in our list. public void deleteAllCourses() { repository.deleteAllCourses(); } // below method is to get all the courses in our list. public LiveData<List<CourseModal>> getAllCourses() { return allCourses; }}", "e": 41539, "s": 40115, "text": null }, { "code": null, "e": 41600, "s": 41539, "text": "Step 9: Creating a layout file for each item of RecyclerView" }, { "code": null, "e": 41803, "s": 41600, "text": "Navigate to the app > res > layout > Right-click on it > New > layout resource file and name it as course_rv_item and add below code to it. Comments are added in the code to get to know in more detail. " }, { "code": null, "e": 41807, "s": 41803, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.cardview.widget.CardView xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"5dp\" android:elevation=\"8dp\" app:cardCornerRadius=\"8dp\"> <LinearLayout android:id=\"@+id/idLLCourse\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"5dp\" android:orientation=\"vertical\"> <!--text view for our course name--> <TextView android:id=\"@+id/idTVCourseName\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:padding=\"8dp\" android:text=\"Course Name\" android:textColor=\"@color/black\" android:textSize=\"15sp\" /> <!--text view for our course duration--> <TextView android:id=\"@+id/idTVCourseDuration\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:padding=\"8dp\" android:text=\"Course Duration\" android:textColor=\"@color/black\" android:textSize=\"15sp\" /> <!--text view for our course description--> <TextView android:id=\"@+id/idTVCourseDescription\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:padding=\"8dp\" android:text=\"Course Description\" android:textColor=\"@color/black\" android:textSize=\"15sp\" /> </LinearLayout> </androidx.cardview.widget.CardView>", "e": 43541, "s": 41807, "text": null }, { "code": null, "e": 43630, "s": 43541, "text": "Step 10: Creating a RecyclerView Adapter class to set data for each item of RecyclerView" }, { "code": null, "e": 43857, "s": 43630, "text": "Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as CourseRVAdapter and add the below code to it. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 43862, "s": 43857, "text": "Java" }, { "code": "import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.DiffUtil;import androidx.recyclerview.widget.ListAdapter;import androidx.recyclerview.widget.RecyclerView; public class CourseRVAdapter extends ListAdapter<CourseModal, CourseRVAdapter.ViewHolder> { // creating a variable for on item click listener. private OnItemClickListener listener; // creating a constructor class for our adapter class. CourseRVAdapter() { super(DIFF_CALLBACK); } // creating a call back for item of recycler view. private static final DiffUtil.ItemCallback<CourseModal> DIFF_CALLBACK = new DiffUtil.ItemCallback<CourseModal>() { @Override public boolean areItemsTheSame(CourseModal oldItem, CourseModal newItem) { return oldItem.getId() == newItem.getId(); } @Override public boolean areContentsTheSame(CourseModal oldItem, CourseModal newItem) { // below line is to check the course name, description and course duration. return oldItem.getCourseName().equals(newItem.getCourseName()) && oldItem.getCourseDescription().equals(newItem.getCourseDescription()) && oldItem.getCourseDuration().equals(newItem.getCourseDuration()); } }; @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // below line is use to inflate our layout // file for each item of our recycler view. View item = LayoutInflater.from(parent.getContext()) .inflate(R.layout.course_rv_item, parent, false); return new ViewHolder(item); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { // below line of code is use to set data to // each item of our recycler view. CourseModal model = getCourseAt(position); holder.courseNameTV.setText(model.getCourseName()); holder.courseDescTV.setText(model.getCourseDescription()); holder.courseDurationTV.setText(model.getCourseDuration()); } // creating a method to get course modal for a specific position. public CourseModal getCourseAt(int position) { return getItem(position); } public class ViewHolder extends RecyclerView.ViewHolder { // view holder class to create a variable for each view. TextView courseNameTV, courseDescTV, courseDurationTV; ViewHolder(@NonNull View itemView) { super(itemView); // initializing each view of our recycler view. courseNameTV = itemView.findViewById(R.id.idTVCourseName); courseDescTV = itemView.findViewById(R.id.idTVCourseDescription); courseDurationTV = itemView.findViewById(R.id.idTVCourseDuration); // adding on click listener for each item of recycler view. itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // inside on click listener we are passing // position to our item of recycler view. int position = getAdapterPosition(); if (listener != null && position != RecyclerView.NO_POSITION) { listener.onItemClick(getItem(position)); } } }); } } public interface OnItemClickListener { void onItemClick(CourseModal model); } public void setOnItemClickListener(OnItemClickListener listener) { this.listener = listener; }}", "e": 47602, "s": 43862, "text": null }, { "code": null, "e": 47670, "s": 47602, "text": "Step 11: Creating a new Activity for Adding and Updating our Course" }, { "code": null, "e": 47900, "s": 47670, "text": "Navigate to the app > java > your app’s package name > Right-click on it > New > Empty Activity and name it as NewCourseActivity and go to XML part and add below code to it. Below is the code for the activity_new_course.xml file." }, { "code": null, "e": 47904, "s": 47900, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".NewCourseActivity\"> <!--edit text for our course name--> <EditText android:id=\"@+id/idEdtCourseName\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:hint=\"Enter Course Name\" /> <!--edit text for our course description--> <EditText android:id=\"@+id/idEdtCourseDescription\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:hint=\"Enter Course Description\" /> <!--edit text for course description--> <EditText android:id=\"@+id/idEdtCourseDuration\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:hint=\"Course Duration\" /> <!--button for saving data to room database--> <Button android:id=\"@+id/idBtnSaveCourse\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:padding=\"5dp\" android:text=\"Save your course\" android:textAllCaps=\"false\" /> </LinearLayout>", "e": 49391, "s": 47904, "text": null }, { "code": null, "e": 49445, "s": 49391, "text": "Step 12: Working with the NewCourseActivity.java file" }, { "code": null, "e": 49632, "s": 49445, "text": "Navigate to the app > java > your app’s package name > NewCourseActivity.java file and add the below code to it. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 49637, "s": 49632, "text": "Java" }, { "code": "import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; public class NewCourseActivity extends AppCompatActivity { // creating a variables for our button and edittext. private EditText courseNameEdt, courseDescEdt, courseDurationEdt; private Button courseBtn; // creating a constant string variable for our // course name, description and duration. public static final String EXTRA_ID = \"com.gtappdevelopers.gfgroomdatabase.EXTRA_ID\"; public static final String EXTRA_COURSE_NAME = \"com.gtappdevelopers.gfgroomdatabase.EXTRA_COURSE_NAME\"; public static final String EXTRA_DESCRIPTION = \"com.gtappdevelopers.gfgroomdatabase.EXTRA_COURSE_DESCRIPTION\"; public static final String EXTRA_DURATION = \"com.gtappdevelopers.gfgroomdatabase.EXTRA_COURSE_DURATION\"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_new_course); // initializing our variables for each view. courseNameEdt = findViewById(R.id.idEdtCourseName); courseDescEdt = findViewById(R.id.idEdtCourseDescription); courseDurationEdt = findViewById(R.id.idEdtCourseDuration); courseBtn = findViewById(R.id.idBtnSaveCourse); // below line is to get intent as we // are getting data via an intent. Intent intent = getIntent(); if (intent.hasExtra(EXTRA_ID)) { // if we get id for our data then we are // setting values to our edit text fields. courseNameEdt.setText(intent.getStringExtra(EXTRA_COURSE_NAME)); courseDescEdt.setText(intent.getStringExtra(EXTRA_DESCRIPTION)); courseDurationEdt.setText(intent.getStringExtra(EXTRA_DURATION)); } // adding on click listener for our save button. courseBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // getting text value from edittext and validating if // the text fields are empty or not. String courseName = courseNameEdt.getText().toString(); String courseDesc = courseDescEdt.getText().toString(); String courseDuration = courseDurationEdt.getText().toString(); if (courseName.isEmpty() || courseDesc.isEmpty() || courseDuration.isEmpty()) { Toast.makeText(NewCourseActivity.this, \"Please enter the valid course details.\", Toast.LENGTH_SHORT).show(); return; } // calling a method to save our course. saveCourse(courseName, courseDesc, courseDuration); } }); } private void saveCourse(String courseName, String courseDescription, String courseDuration) { // inside this method we are passing // all the data via an intent. Intent data = new Intent(); // in below line we are passing all our course detail. data.putExtra(EXTRA_COURSE_NAME, courseName); data.putExtra(EXTRA_DESCRIPTION, courseDescription); data.putExtra(EXTRA_DURATION, courseDuration); int id = getIntent().getIntExtra(EXTRA_ID, -1); if (id != -1) { // in below line we are passing our id. data.putExtra(EXTRA_ID, id); } // at last we are setting result as data. setResult(RESULT_OK, data); // displaying a toast message after adding the data Toast.makeText(this, \"Course has been saved to Room Database. \", Toast.LENGTH_SHORT).show(); }}", "e": 53430, "s": 49637, "text": null }, { "code": null, "e": 53479, "s": 53430, "text": "Step 13: Working with the MainActivity.java file" }, { "code": null, "e": 53661, "s": 53479, "text": "Navigate to the app > java > your app’s package name > MainActivity.java file and add the below code to it. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 53666, "s": 53661, "text": "Java" }, { "code": "import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.annotation.Nullable;import androidx.appcompat.app.AppCompatActivity;import androidx.lifecycle.Observer;import androidx.lifecycle.ViewModelProviders;import androidx.recyclerview.widget.ItemTouchHelper;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView; import com.google.android.material.floatingactionbutton.FloatingActionButton; import java.util.List; public class MainActivity extends AppCompatActivity { // creating a variables for our recycler view. private RecyclerView coursesRV; private static final int ADD_COURSE_REQUEST = 1; private static final int EDIT_COURSE_REQUEST = 2; private ViewModal viewmodal; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our variable for our recycler view and fab. coursesRV = findViewById(R.id.idRVCourses); FloatingActionButton fab = findViewById(R.id.idFABAdd); // adding on click listener for floating action button. fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // starting a new activity for adding a new course // and passing a constant value in it. Intent intent = new Intent(MainActivity.this, NewCourseActivity.class); startActivityForResult(intent, ADD_COURSE_REQUEST); } }); // setting layout manager to our adapter class. coursesRV.setLayoutManager(new LinearLayoutManager(this)); coursesRV.setHasFixedSize(true); // initializing adapter for recycler view. final CourseRVAdapter adapter = new CourseRVAdapter(); // setting adapter class for recycler view. coursesRV.setAdapter(adapter); // passing a data from view modal. viewmodal = ViewModelProviders.of(this).get(ViewModal.class); // below line is use to get all the courses from view modal. viewmodal.getAllCourses().observe(this, new Observer<List<CourseModal>>() { @Override public void onChanged(List<CourseModal> models) { // when the data is changed in our models we are // adding that list to our adapter class. adapter.submitList(models); } }); // below method is use to add swipe to delete method for item of recycler view. new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) { @Override public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) { return false; } @Override public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) { // on recycler view item swiped then we are deleting the item of our recycler view. viewmodal.delete(adapter.getCourseAt(viewHolder.getAdapterPosition())); Toast.makeText(MainActivity.this, \"Course deleted\", Toast.LENGTH_SHORT).show(); } }). // below line is use to attach this to recycler view. attachToRecyclerView(coursesRV); // below line is use to set item click listener for our item of recycler view. adapter.setOnItemClickListener(new CourseRVAdapter.OnItemClickListener() { @Override public void onItemClick(CourseModal model) { // after clicking on item of recycler view // we are opening a new activity and passing // a data to our activity. Intent intent = new Intent(MainActivity.this, NewCourseActivity.class); intent.putExtra(NewCourseActivity.EXTRA_ID, model.getId()); intent.putExtra(NewCourseActivity.EXTRA_COURSE_NAME, model.getCourseName()); intent.putExtra(NewCourseActivity.EXTRA_DESCRIPTION, model.getCourseDescription()); intent.putExtra(NewCourseActivity.EXTRA_DURATION, model.getCourseDuration()); // below line is to start a new activity and // adding a edit course constant. startActivityForResult(intent, EDIT_COURSE_REQUEST); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == ADD_COURSE_REQUEST && resultCode == RESULT_OK) { String courseName = data.getStringExtra(NewCourseActivity.EXTRA_COURSE_NAME); String courseDescription = data.getStringExtra(NewCourseActivity.EXTRA_DESCRIPTION); String courseDuration = data.getStringExtra(NewCourseActivity.EXTRA_DURATION); CourseModal model = new CourseModal(courseName, courseDescription, courseDuration); viewmodal.insert(model); Toast.makeText(this, \"Course saved\", Toast.LENGTH_SHORT).show(); } else if (requestCode == EDIT_COURSE_REQUEST && resultCode == RESULT_OK) { int id = data.getIntExtra(NewCourseActivity.EXTRA_ID, -1); if (id == -1) { Toast.makeText(this, \"Course can't be updated\", Toast.LENGTH_SHORT).show(); return; } String courseName = data.getStringExtra(NewCourseActivity.EXTRA_COURSE_NAME); String courseDesc = data.getStringExtra(NewCourseActivity.EXTRA_DESCRIPTION); String courseDuration = data.getStringExtra(NewCourseActivity.EXTRA_DURATION); CourseModal model = new CourseModal(courseName, courseDesc, courseDuration); model.setId(id); viewmodal.update(model); Toast.makeText(this, \"Course updated\", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, \"Course not saved\", Toast.LENGTH_SHORT).show(); } }}", "e": 59972, "s": 53666, "text": null }, { "code": null, "e": 60021, "s": 59972, "text": "Now run your app and see the output of the app. " }, { "code": null, "e": 60114, "s": 60021, "text": "Check out the project on the below link: https://github.com/ChaitanyaMunje/GFG-Room-Database" }, { "code": null, "e": 60129, "s": 60114, "text": "kapoorsagar226" }, { "code": null, "e": 60137, "s": 60129, "text": "android" }, { "code": null, "e": 60161, "s": 60137, "text": "Technical Scripter 2020" }, { "code": null, "e": 60169, "s": 60161, "text": "Android" }, { "code": null, "e": 60174, "s": 60169, "text": "Java" }, { "code": null, "e": 60193, "s": 60174, "text": "Technical Scripter" }, { "code": null, "e": 60198, "s": 60193, "text": "Java" }, { "code": null, "e": 60206, "s": 60198, "text": "Android" }, { "code": null, "e": 60304, "s": 60206, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 60362, "s": 60304, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 60400, "s": 60362, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 60443, "s": 60400, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 60476, "s": 60443, "text": "Services in Android with Example" }, { "code": null, "e": 60507, "s": 60476, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 60522, "s": 60507, "text": "Arrays in Java" }, { "code": null, "e": 60566, "s": 60522, "text": "Split() String method in Java with examples" }, { "code": null, "e": 60588, "s": 60566, "text": "For-each loop in Java" }, { "code": null, "e": 60639, "s": 60588, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
Python | Interleave multiple lists of same length - GeeksforGeeks
30 Dec, 2018 Given lists of same length, write a Python program to store alternative elements of given lists in a new list. Let’s discuss certain ways in which this can be performed. Method #1 : Using map() + list comprehensionmap() is used to handle the interleave of lists and the task of insertion at alternate is performed by the list comprehension part of the shorthand code. Only works in Python 2. # Python2 code to demonstrate # to interleave lists# using map() + list comprehension # initializing lists test_list1 = [1, 4, 5]test_list2 = [3, 8, 9] # printing original listsprint ("Original list 1 : " + str(test_list1))print ("Original list 2 : " + str(test_list2)) # using map() + list comprehension# to interleave listsres = [i for j in map(None, test_list1, test_list2) for i in j if i is not None] # printing resultprint ("The interleaved list is : " + str(res)) Original list 1 : [1, 4, 5] Original list 2 : [3, 8, 9] The interleaved list is : [1, 3, 4, 8, 5, 9] Method #2 : Using List slicingPower of list slicing of python can also be used to perform this particular task. We first extend one list to another and then allow the original list to desired alternate indices of the resultant list. # Python3 code to demonstrate # to interleave lists# using list slicing # initializing lists test_list1 = [1, 4, 5]test_list2 = [3, 8, 9] # printing original listsprint ("Original list 1 : " + str(test_list1))print ("Original list 2 : " + str(test_list2)) # using list slicing# to interleave listsres = test_list1 + test_list2res[::2] = test_list1res[1::2] = test_list2 # printing resultprint ("The interleaved list is : " + str(res)) Original list 1 : [1, 4, 5] Original list 2 : [3, 8, 9] The interleaved list is : [1, 3, 4, 8, 5, 9] Method #3 : Using itertools.chain() + zip()zip() can be used to link both the lists and then chain() can used to perform the alternate append of the elements as desired. This is the most efficient method to perform this task. # Python3 code to demonstrate # to interleave lists# using zip() + itertools.chain()import itertools # initializing lists test_list1 = [1, 4, 5]test_list2 = [3, 8, 9] # printing original listsprint ("Original list 1 : " + str(test_list1))print ("Original list 2 : " + str(test_list2)) # using zip() + itertools.chain()# to interleave listsres = list(itertools.chain(*zip(test_list1, test_list2))) # printing resultprint ("The interleaved list is : " + str(res)) Original list 1 : [1, 4, 5] Original list 2 : [3, 8, 9] The interleaved list is : [1, 3, 4, 8, 5, 9] Python list-programs python-list Python Python Programs python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 25667, "s": 25639, "text": "\n30 Dec, 2018" }, { "code": null, "e": 25778, "s": 25667, "text": "Given lists of same length, write a Python program to store alternative elements of given lists in a new list." }, { "code": null, "e": 25837, "s": 25778, "text": "Let’s discuss certain ways in which this can be performed." }, { "code": null, "e": 26059, "s": 25837, "text": "Method #1 : Using map() + list comprehensionmap() is used to handle the interleave of lists and the task of insertion at alternate is performed by the list comprehension part of the shorthand code. Only works in Python 2." }, { "code": "# Python2 code to demonstrate # to interleave lists# using map() + list comprehension # initializing lists test_list1 = [1, 4, 5]test_list2 = [3, 8, 9] # printing original listsprint (\"Original list 1 : \" + str(test_list1))print (\"Original list 2 : \" + str(test_list2)) # using map() + list comprehension# to interleave listsres = [i for j in map(None, test_list1, test_list2) for i in j if i is not None] # printing resultprint (\"The interleaved list is : \" + str(res))", "e": 26558, "s": 26059, "text": null }, { "code": null, "e": 26660, "s": 26558, "text": "Original list 1 : [1, 4, 5]\nOriginal list 2 : [3, 8, 9]\nThe interleaved list is : [1, 3, 4, 8, 5, 9]\n" }, { "code": null, "e": 26894, "s": 26660, "text": " Method #2 : Using List slicingPower of list slicing of python can also be used to perform this particular task. We first extend one list to another and then allow the original list to desired alternate indices of the resultant list." }, { "code": "# Python3 code to demonstrate # to interleave lists# using list slicing # initializing lists test_list1 = [1, 4, 5]test_list2 = [3, 8, 9] # printing original listsprint (\"Original list 1 : \" + str(test_list1))print (\"Original list 2 : \" + str(test_list2)) # using list slicing# to interleave listsres = test_list1 + test_list2res[::2] = test_list1res[1::2] = test_list2 # printing resultprint (\"The interleaved list is : \" + str(res))", "e": 27333, "s": 26894, "text": null }, { "code": null, "e": 27435, "s": 27333, "text": "Original list 1 : [1, 4, 5]\nOriginal list 2 : [3, 8, 9]\nThe interleaved list is : [1, 3, 4, 8, 5, 9]\n" }, { "code": null, "e": 27662, "s": 27435, "text": " Method #3 : Using itertools.chain() + zip()zip() can be used to link both the lists and then chain() can used to perform the alternate append of the elements as desired. This is the most efficient method to perform this task." }, { "code": "# Python3 code to demonstrate # to interleave lists# using zip() + itertools.chain()import itertools # initializing lists test_list1 = [1, 4, 5]test_list2 = [3, 8, 9] # printing original listsprint (\"Original list 1 : \" + str(test_list1))print (\"Original list 2 : \" + str(test_list2)) # using zip() + itertools.chain()# to interleave listsres = list(itertools.chain(*zip(test_list1, test_list2))) # printing resultprint (\"The interleaved list is : \" + str(res))", "e": 28128, "s": 27662, "text": null }, { "code": null, "e": 28230, "s": 28128, "text": "Original list 1 : [1, 4, 5]\nOriginal list 2 : [3, 8, 9]\nThe interleaved list is : [1, 3, 4, 8, 5, 9]\n" }, { "code": null, "e": 28251, "s": 28230, "text": "Python list-programs" }, { "code": null, "e": 28263, "s": 28251, "text": "python-list" }, { "code": null, "e": 28270, "s": 28263, "text": "Python" }, { "code": null, "e": 28286, "s": 28270, "text": "Python Programs" }, { "code": null, "e": 28298, "s": 28286, "text": "python-list" }, { "code": null, "e": 28396, "s": 28298, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28414, "s": 28396, "text": "Python Dictionary" }, { "code": null, "e": 28449, "s": 28414, "text": "Read a file line by line in Python" }, { "code": null, "e": 28481, "s": 28449, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28503, "s": 28481, "text": "Enumerate() in Python" }, { "code": null, "e": 28545, "s": 28503, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28588, "s": 28545, "text": "Python program to convert a list to string" }, { "code": null, "e": 28610, "s": 28588, "text": "Defaultdict in Python" }, { "code": null, "e": 28649, "s": 28610, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28695, "s": 28649, "text": "Python | Split string into list of characters" } ]
How to change video playing speed using JavaScript ? - GeeksforGeeks
12 Jan, 2021 In this article, we will see how we can change playback speed of videos embedded in an HTML document using an HTML5 video tag. We can set the new playing speed using playbackRate attribute. It has the following syntax. Syntax: let video = document.querySelector('video') video.playbackRate = newPlaybackRate We can also set the default playing speed using defaultPlaybackRate attribute. It has the following syntax. Syntax: let video = document.querySelector('video') video.defaultPlaybackRate = 4 video.load() Example: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <style> body { text-align: center; margin-top: 2%; } h1 { color: green; } p { margin-top: 2%; } button { margin-right: 20px; } </style></head> <body> <h1>GeeksforGeeks</h1> <video width="890" height="500" controls loop> <source src="sample.mp4" type="video/mp4"> Your browser does not support the video tag. </video> <p> <button onclick="increase()">Increase Speed</button> <button onclick="decrease()">Decrease Speed</button> </p> <script> let video = document.querySelector('video'); // Set the default playing speed video.defaultPlaybackRate = 0.5 // Loading the video after setting video.load(); function increase() { // Increasing the playing speed by 1 video.playbackRate += 1; } function decrease() { // Decreasing the playing speed by 1 if (video.playbackRate > 1) video.playbackRate -= 1; } </script></body> </html> Output: CSS-Misc HTML-Misc JavaScript-Misc Picked CSS HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to set space between the flexbox ? Design a web page using HTML and CSS Form validation using jQuery How to style a checkbox using CSS? Search Bar using HTML, CSS and JavaScript How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction) How to Insert Form Data into Database using PHP ?
[ { "code": null, "e": 26621, "s": 26593, "text": "\n12 Jan, 2021" }, { "code": null, "e": 26748, "s": 26621, "text": "In this article, we will see how we can change playback speed of videos embedded in an HTML document using an HTML5 video tag." }, { "code": null, "e": 26840, "s": 26748, "text": "We can set the new playing speed using playbackRate attribute. It has the following syntax." }, { "code": null, "e": 26848, "s": 26840, "text": "Syntax:" }, { "code": null, "e": 26929, "s": 26848, "text": "let video = document.querySelector('video')\nvideo.playbackRate = newPlaybackRate" }, { "code": null, "e": 27037, "s": 26929, "text": "We can also set the default playing speed using defaultPlaybackRate attribute. It has the following syntax." }, { "code": null, "e": 27045, "s": 27037, "text": "Syntax:" }, { "code": null, "e": 27135, "s": 27045, "text": " let video = document.querySelector('video')\n video.defaultPlaybackRate = 4\n video.load()" }, { "code": null, "e": 27144, "s": 27135, "text": "Example:" }, { "code": null, "e": 27149, "s": 27144, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <style> body { text-align: center; margin-top: 2%; } h1 { color: green; } p { margin-top: 2%; } button { margin-right: 20px; } </style></head> <body> <h1>GeeksforGeeks</h1> <video width=\"890\" height=\"500\" controls loop> <source src=\"sample.mp4\" type=\"video/mp4\"> Your browser does not support the video tag. </video> <p> <button onclick=\"increase()\">Increase Speed</button> <button onclick=\"decrease()\">Decrease Speed</button> </p> <script> let video = document.querySelector('video'); // Set the default playing speed video.defaultPlaybackRate = 0.5 // Loading the video after setting video.load(); function increase() { // Increasing the playing speed by 1 video.playbackRate += 1; } function decrease() { // Decreasing the playing speed by 1 if (video.playbackRate > 1) video.playbackRate -= 1; } </script></body> </html>", "e": 28441, "s": 27149, "text": null }, { "code": null, "e": 28449, "s": 28441, "text": "Output:" }, { "code": null, "e": 28458, "s": 28449, "text": "CSS-Misc" }, { "code": null, "e": 28468, "s": 28458, "text": "HTML-Misc" }, { "code": null, "e": 28484, "s": 28468, "text": "JavaScript-Misc" }, { "code": null, "e": 28491, "s": 28484, "text": "Picked" }, { "code": null, "e": 28495, "s": 28491, "text": "CSS" }, { "code": null, "e": 28500, "s": 28495, "text": "HTML" }, { "code": null, "e": 28511, "s": 28500, "text": "JavaScript" }, { "code": null, "e": 28528, "s": 28511, "text": "Web Technologies" }, { "code": null, "e": 28533, "s": 28528, "text": "HTML" }, { "code": null, "e": 28631, "s": 28533, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28670, "s": 28631, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 28707, "s": 28670, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28736, "s": 28707, "text": "Form validation using jQuery" }, { "code": null, "e": 28771, "s": 28736, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 28813, "s": 28771, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 28873, "s": 28813, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 28926, "s": 28873, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 28987, "s": 28926, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 29011, "s": 28987, "text": "REST API (Introduction)" } ]
Calculate the Mean of each Column of a Matrix or Array in R Programming - colMeans() Function - GeeksforGeeks
03 Jun, 2020 colMeans() function in R Language is used to compute the mean of each column of a matrix or array. Syntax: colMeans(x, dims = 1) Parameters:x: array of two or more dimensions, containing numeric, complex, integer or logical values, or a numeric data framedims: integer value, which dimensions are regarded as ‘columns’ to sum over. It is over dimensions 1:dims. Example 1: # R program to illustrate# colMeans function # Initializing a matrix with# 3 rows and 3 columnsx <- matrix(rep(1:9), 3, 3) # Getting matrix representationx # Calling the colMeans() functioncolMeans(x) Output: [, 1] [, 2] [, 3] [1, ] 1 4 7 [2, ] 2 5 8 [3, ] 3 6 9 [1] 2 5 8 Example 2: # R program to illustrate# colMeans function # Initializing a 3D arrayx <- array(1:12, c(2, 3, 3)) # Getting the array representationx # Calling the colMeans() function # for dims = 1, x[, 1, 1], x[, 2, 1], x[, 3, 1],# x[, 1, 2] ... are columnscolMeans(x, dims = 1) # for dims = 2, x[,,1], x[,,2], x[,,3]# are columnscolMeans(x, dims = 2) Output: ,, 1 [, 1] [, 2] [, 3] [1, ] 1 3 5 [2, ] 2 4 6,, 2 [, 1] [, 2] [, 3] [1, ] 7 9 11 [2, ] 8 10 12,, 3 [, 1] [, 2] [, 3] [1, ] 1 3 5 [2, ] 2 4 6 [, 1] [, 2] [, 3] [1, ] 1.5 7.5 1.5 [2, ] 3.5 9.5 3.5 [3, ] 5.5 11.5 5.5 [1] 3.5 9.5 3.5 R Matrix-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Replace specific values in column in R DataFrame ? Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) How to change Row Names of DataFrame in R ? Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? Printing Output of an R Program How to Split Column Into Multiple Columns in R DataFrame? K-Means Clustering in R Programming
[ { "code": null, "e": 26317, "s": 26289, "text": "\n03 Jun, 2020" }, { "code": null, "e": 26416, "s": 26317, "text": "colMeans() function in R Language is used to compute the mean of each column of a matrix or array." }, { "code": null, "e": 26446, "s": 26416, "text": "Syntax: colMeans(x, dims = 1)" }, { "code": null, "e": 26679, "s": 26446, "text": "Parameters:x: array of two or more dimensions, containing numeric, complex, integer or logical values, or a numeric data framedims: integer value, which dimensions are regarded as ‘columns’ to sum over. It is over dimensions 1:dims." }, { "code": null, "e": 26690, "s": 26679, "text": "Example 1:" }, { "code": "# R program to illustrate# colMeans function # Initializing a matrix with# 3 rows and 3 columnsx <- matrix(rep(1:9), 3, 3) # Getting matrix representationx # Calling the colMeans() functioncolMeans(x)", "e": 26894, "s": 26690, "text": null }, { "code": null, "e": 26902, "s": 26894, "text": "Output:" }, { "code": null, "e": 27000, "s": 26902, "text": " [, 1] [, 2] [, 3]\n[1, ] 1 4 7\n[2, ] 2 5 8\n[3, ] 3 6 9\n\n[1] 2 5 8\n" }, { "code": null, "e": 27011, "s": 27000, "text": "Example 2:" }, { "code": "# R program to illustrate# colMeans function # Initializing a 3D arrayx <- array(1:12, c(2, 3, 3)) # Getting the array representationx # Calling the colMeans() function # for dims = 1, x[, 1, 1], x[, 2, 1], x[, 3, 1],# x[, 1, 2] ... are columnscolMeans(x, dims = 1) # for dims = 2, x[,,1], x[,,2], x[,,3]# are columnscolMeans(x, dims = 2)", "e": 27355, "s": 27011, "text": null }, { "code": null, "e": 27363, "s": 27355, "text": "Output:" }, { "code": null, "e": 27679, "s": 27363, "text": ",, 1\n\n [, 1] [, 2] [, 3]\n[1, ] 1 3 5\n[2, ] 2 4 6,, 2\n\n [, 1] [, 2] [, 3]\n[1, ] 7 9 11\n[2, ] 8 10 12,, 3\n\n [, 1] [, 2] [, 3]\n[1, ] 1 3 5\n[2, ] 2 4 6\n\n [, 1] [, 2] [, 3]\n[1, ] 1.5 7.5 1.5\n[2, ] 3.5 9.5 3.5\n[3, ] 5.5 11.5 5.5\n\n[1] 3.5 9.5 3.5\n" }, { "code": null, "e": 27697, "s": 27679, "text": "R Matrix-Function" }, { "code": null, "e": 27708, "s": 27697, "text": "R Language" }, { "code": null, "e": 27806, "s": 27708, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27864, "s": 27806, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 27916, "s": 27864, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 27948, "s": 27916, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 27992, "s": 27948, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 28044, "s": 27992, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 28079, "s": 28044, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 28117, "s": 28079, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 28149, "s": 28117, "text": "Printing Output of an R Program" }, { "code": null, "e": 28207, "s": 28149, "text": "How to Split Column Into Multiple Columns in R DataFrame?" } ]
Program to find the sum of a Series (1*1) + (2*2) + (3*3) + (4*4) + (5*5) + ... + (n*n) - GeeksforGeeks
24 Mar, 2021 You have been given a series (1*1) + (2*2) + (3*3) + (4*4) + (5*5) + ... + (n*n), find out the sum of the series till nth term. Examples : Input : n = 3 Output : 14 Explanation : 1 + 1/2^2 + 1/3^3 Input : n = 5 Output : 55 Explanation : (1*1) + (2*2) + (3*3) + (4*4) + (5*5) C++ C Java Python C# PHP Javascript // CPP program to calculate the following series#include<iostream>using namespace std; // Function to calculate the following seriesint Series(int n){ int i; int sums = 0; for (i = 1; i <= n; i++) sums += (i * i); return sums;} // Driver Codeint main(){ int n = 3; int res = Series(n); cout<<res<<endl;} // C program to calculate the following series#include <stdio.h> // Function to calculate the following seriesint Series(int n){ int i; int sums = 0; for (i = 1; i <= n; i++) sums += (i * i); return sums;} // Driver Codeint main(){ int n = 3; int res = Series(n); printf("%d", res);} // Java program to calculate the following seriesimport java.io.*;class GFG { // Function to calculate the following series static int Series(int n) { int i; int sums = 0; for (i = 1; i <= n; i++) sums += (i * i); return sums; } // Driver Code public static void main(String[] args) { int n = 3; int res = Series(n); System.out.println(res); }} # Python program to calculate the following seriesdef Series(n): sums = 0 for i in range(1, n + 1): sums += (i * i); return sums # Driver Coden = 3res = Series(n)print(res) // C# program to calculate the following seriesusing System;class GFG { // Function to calculate the following series static int Series(int n) { int i; int sums = 0; for (i = 1; i <= n; i++) sums += (i * i); return sums; } // Driver Code public static void Main() { int n = 3; int res = Series(n); Console.Write(res); }} // This code is contributed by vt_m. <?php// PHP program to calculate// the following series // Function to calculate the// following seriesfunction Series($n){ $i; $sums = 0; for ($i = 1; $i <= $n; $i++) $sums += ($i * $i); return $sums;} // Driver Code$n = 3;$res = Series($n);echo($res); // This code is contributed by Ajit.?> <script> // Javascript program to calculate the following series // Function to calculate the following series function Series( n) { let i; let sums = 0; for (i = 1; i <= n; i++) sums += (i * i); return sums; } // Driver Code let n = 3; let res = Series(n); document.write(res); // This code contributed by Princi Singh </script> Output : 14 Time Complexity: O(n)Please refer below post for O(1) solution. Sum of squares of first n natural numbers jit_t SURENDRA_GANGWAR princi singh number-theory series Mathematical School Programming number-theory Mathematical series 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 Print all possible combinations of r elements in a given array of size n Operators in C / C++ Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 26769, "s": 26741, "text": "\n24 Mar, 2021" }, { "code": null, "e": 26910, "s": 26769, "text": "You have been given a series (1*1) + (2*2) + (3*3) + (4*4) + (5*5) + ... + (n*n), find out the sum of the series till nth term. Examples : " }, { "code": null, "e": 27047, "s": 26910, "text": "Input : n = 3\nOutput : 14\nExplanation : 1 + 1/2^2 + 1/3^3\n\nInput : n = 5\nOutput : 55\nExplanation : (1*1) + (2*2) + (3*3) + (4*4) + (5*5)" }, { "code": null, "e": 27055, "s": 27051, "text": "C++" }, { "code": null, "e": 27057, "s": 27055, "text": "C" }, { "code": null, "e": 27062, "s": 27057, "text": "Java" }, { "code": null, "e": 27069, "s": 27062, "text": "Python" }, { "code": null, "e": 27072, "s": 27069, "text": "C#" }, { "code": null, "e": 27076, "s": 27072, "text": "PHP" }, { "code": null, "e": 27087, "s": 27076, "text": "Javascript" }, { "code": "// CPP program to calculate the following series#include<iostream>using namespace std; // Function to calculate the following seriesint Series(int n){ int i; int sums = 0; for (i = 1; i <= n; i++) sums += (i * i); return sums;} // Driver Codeint main(){ int n = 3; int res = Series(n); cout<<res<<endl;}", "e": 27419, "s": 27087, "text": null }, { "code": "// C program to calculate the following series#include <stdio.h> // Function to calculate the following seriesint Series(int n){ int i; int sums = 0; for (i = 1; i <= n; i++) sums += (i * i); return sums;} // Driver Codeint main(){ int n = 3; int res = Series(n); printf(\"%d\", res);}", "e": 27731, "s": 27419, "text": null }, { "code": "// Java program to calculate the following seriesimport java.io.*;class GFG { // Function to calculate the following series static int Series(int n) { int i; int sums = 0; for (i = 1; i <= n; i++) sums += (i * i); return sums; } // Driver Code public static void main(String[] args) { int n = 3; int res = Series(n); System.out.println(res); }}", "e": 28162, "s": 27731, "text": null }, { "code": "# Python program to calculate the following seriesdef Series(n): sums = 0 for i in range(1, n + 1): sums += (i * i); return sums # Driver Coden = 3res = Series(n)print(res)", "e": 28351, "s": 28162, "text": null }, { "code": "// C# program to calculate the following seriesusing System;class GFG { // Function to calculate the following series static int Series(int n) { int i; int sums = 0; for (i = 1; i <= n; i++) sums += (i * i); return sums; } // Driver Code public static void Main() { int n = 3; int res = Series(n); Console.Write(res); }} // This code is contributed by vt_m.", "e": 28795, "s": 28351, "text": null }, { "code": "<?php// PHP program to calculate// the following series // Function to calculate the// following seriesfunction Series($n){ $i; $sums = 0; for ($i = 1; $i <= $n; $i++) $sums += ($i * $i); return $sums;} // Driver Code$n = 3;$res = Series($n);echo($res); // This code is contributed by Ajit.?>", "e": 29107, "s": 28795, "text": null }, { "code": "<script> // Javascript program to calculate the following series // Function to calculate the following series function Series( n) { let i; let sums = 0; for (i = 1; i <= n; i++) sums += (i * i); return sums; } // Driver Code let n = 3; let res = Series(n); document.write(res); // This code contributed by Princi Singh </script>", "e": 29517, "s": 29107, "text": null }, { "code": null, "e": 29527, "s": 29517, "text": "Output : " }, { "code": null, "e": 29530, "s": 29527, "text": "14" }, { "code": null, "e": 29637, "s": 29530, "text": "Time Complexity: O(n)Please refer below post for O(1) solution. Sum of squares of first n natural numbers " }, { "code": null, "e": 29643, "s": 29637, "text": "jit_t" }, { "code": null, "e": 29660, "s": 29643, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 29673, "s": 29660, "text": "princi singh" }, { "code": null, "e": 29687, "s": 29673, "text": "number-theory" }, { "code": null, "e": 29694, "s": 29687, "text": "series" }, { "code": null, "e": 29707, "s": 29694, "text": "Mathematical" }, { "code": null, "e": 29726, "s": 29707, "text": "School Programming" }, { "code": null, "e": 29740, "s": 29726, "text": "number-theory" }, { "code": null, "e": 29753, "s": 29740, "text": "Mathematical" }, { "code": null, "e": 29760, "s": 29753, "text": "series" }, { "code": null, "e": 29858, "s": 29760, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29882, "s": 29858, "text": "Merge two sorted arrays" }, { "code": null, "e": 29925, "s": 29882, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 29939, "s": 29925, "text": "Prime Numbers" }, { "code": null, "e": 30012, "s": 29939, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 30033, "s": 30012, "text": "Operators in C / C++" }, { "code": null, "e": 30051, "s": 30033, "text": "Python Dictionary" }, { "code": null, "e": 30067, "s": 30051, "text": "Arrays in C/C++" }, { "code": null, "e": 30086, "s": 30067, "text": "Inheritance in C++" }, { "code": null, "e": 30111, "s": 30086, "text": "Reverse a string in Java" } ]
Get Bank details from IFSC Code Using PHP - GeeksforGeeks
10 Dec, 2020 The Indian Financial System Code (IFSC) is an 11-digit alpha-numeric code used to uniquely classify bank branches within the National Electronic Fund Transfer (NEFT) network by the Central Bank. In this article, we are going to write PHP code to get details of the Bank from the given IFSC code. For this, we will be using Razorpay’s IFSC API which is an API server that serves Razorpay’s IFSC API. The link of the API is https://ifsc.razorpay.com/. After “/” we have to give the IFSC code of the bank. It will give all the details in JSON format. Example: KARB0000001 is the IFSC code of the bank in Karnataka. When we enter the URL https://ifsc.razorpay.com/KARB0000001 it will return the details of that particular bank in JSON Format. The details include Bank Name, Branch, Address, Contact, etc. HTML Code: The following demonstrates the implementation using HTML and PHP code for the above discussion. We make a simple HTML form with an input control and a submit button. In the input control, we have to enter the IFSC code of the bank and submit the form. After submission of the form, we will get the details of the bank. HTML <!DOCTYPE html><html> <body> <form method="post" action="index.php" id="theForm"> <b>Enter IFSC Code:</b> <input type="text" name='ifsc'> <input type="submit" id="formSubmit"> </form></body> </html> PHP Code: When the user submits the form, we store the IFSC code in a variable using the PHP $_POST. PHP $_POST is a superglobal variable that is used to collect form data after submitting an HTML form with method=”post”. After that we use file_get_contents() method to read the content of the file storing in a variable. As we get the data in JSON format, we first convert it into an array. For that, we are using json_decode() function. The json_decode() function is used to decode or convert a JSON object to a PHP object. Now we can easily parse the array object using the array operator and show the details to the user. Suppose the user enters an incorrect IFSC code then some error messages will display which is not understandable to the user. To this problem, we use the if() condition checking if we get some data. We can pass any parameter in the if() condition that is present in our array. For example, if we use “Branch”, after parsing the “Branch” we get some value, it means that the IFSC code is correct else its incorrect. Instead of the “Branch”, we can also use the “Bank” or “Address”, etc. If the IFSC code is correct details will be shown on screen otherwise a “Invalid IFSC Code” message will be shown. PHP <?phpif(isset($_POST['ifsc'])) { $ifsc = $_POST['ifsc']; $json = @file_get_contents( "https://ifsc.razorpay.com/".$ifsc); $arr = json_decode($json); if(isset($arr->BRANCH)) { echo '<pre>'; echo "<b>Bank:-</b>".$arr->BANK; echo "<br/>"; echo "<b>Branch:-</b>".$arr->BRANCH; echo "<br/>"; echo "<b>Centre:-</b>".$arr->CENTRE; echo "<br/>"; echo "<b>District:-</b>".$arr->DISTRICT; echo "<br/>"; echo "<b>State:-</b>".$arr->STATE; echo "<br/>"; echo "<b/>Address:-</b>".$arr->ADDRESS; echo "<br/>"; } else { echo "Invalid IFSC Code"; }}?> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-Misc PHP-Misc Technical Scripter 2020 HTML PHP PHP Programs Technical Scripter Web Technologies HTML PHP 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) How to Insert Form Data into Database using PHP ? CSS to put icon inside an input element in a form Types of CSS (Cascading Style Sheet) How to execute PHP code using command line ? How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? PHP in_array() Function How to pop an alert message box using PHP ?
[ { "code": null, "e": 26253, "s": 26225, "text": "\n10 Dec, 2020" }, { "code": null, "e": 26448, "s": 26253, "text": "The Indian Financial System Code (IFSC) is an 11-digit alpha-numeric code used to uniquely classify bank branches within the National Electronic Fund Transfer (NEFT) network by the Central Bank." }, { "code": null, "e": 26801, "s": 26448, "text": "In this article, we are going to write PHP code to get details of the Bank from the given IFSC code. For this, we will be using Razorpay’s IFSC API which is an API server that serves Razorpay’s IFSC API. The link of the API is https://ifsc.razorpay.com/. After “/” we have to give the IFSC code of the bank. It will give all the details in JSON format." }, { "code": null, "e": 26992, "s": 26801, "text": "Example: KARB0000001 is the IFSC code of the bank in Karnataka. When we enter the URL https://ifsc.razorpay.com/KARB0000001 it will return the details of that particular bank in JSON Format." }, { "code": null, "e": 27054, "s": 26992, "text": "The details include Bank Name, Branch, Address, Contact, etc." }, { "code": null, "e": 27384, "s": 27054, "text": "HTML Code: The following demonstrates the implementation using HTML and PHP code for the above discussion. We make a simple HTML form with an input control and a submit button. In the input control, we have to enter the IFSC code of the bank and submit the form. After submission of the form, we will get the details of the bank." }, { "code": null, "e": 27389, "s": 27384, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <form method=\"post\" action=\"index.php\" id=\"theForm\"> <b>Enter IFSC Code:</b> <input type=\"text\" name='ifsc'> <input type=\"submit\" id=\"formSubmit\"> </form></body> </html>", "e": 27617, "s": 27389, "text": null }, { "code": null, "e": 28243, "s": 27617, "text": "PHP Code: When the user submits the form, we store the IFSC code in a variable using the PHP $_POST. PHP $_POST is a superglobal variable that is used to collect form data after submitting an HTML form with method=”post”. After that we use file_get_contents() method to read the content of the file storing in a variable. As we get the data in JSON format, we first convert it into an array. For that, we are using json_decode() function. The json_decode() function is used to decode or convert a JSON object to a PHP object. Now we can easily parse the array object using the array operator and show the details to the user." }, { "code": null, "e": 28844, "s": 28243, "text": "Suppose the user enters an incorrect IFSC code then some error messages will display which is not understandable to the user. To this problem, we use the if() condition checking if we get some data. We can pass any parameter in the if() condition that is present in our array. For example, if we use “Branch”, after parsing the “Branch” we get some value, it means that the IFSC code is correct else its incorrect. Instead of the “Branch”, we can also use the “Bank” or “Address”, etc. If the IFSC code is correct details will be shown on screen otherwise a “Invalid IFSC Code” message will be shown." }, { "code": null, "e": 28848, "s": 28844, "text": "PHP" }, { "code": "<?phpif(isset($_POST['ifsc'])) { $ifsc = $_POST['ifsc']; $json = @file_get_contents( \"https://ifsc.razorpay.com/\".$ifsc); $arr = json_decode($json); if(isset($arr->BRANCH)) { echo '<pre>'; echo \"<b>Bank:-</b>\".$arr->BANK; echo \"<br/>\"; echo \"<b>Branch:-</b>\".$arr->BRANCH; echo \"<br/>\"; echo \"<b>Centre:-</b>\".$arr->CENTRE; echo \"<br/>\"; echo \"<b>District:-</b>\".$arr->DISTRICT; echo \"<br/>\"; echo \"<b>State:-</b>\".$arr->STATE; echo \"<br/>\"; echo \"<b/>Address:-</b>\".$arr->ADDRESS; echo \"<br/>\"; } else { echo \"Invalid IFSC Code\"; }}?>", "e": 29512, "s": 28848, "text": null }, { "code": null, "e": 29520, "s": 29512, "text": "Output:" }, { "code": null, "e": 29657, "s": 29520, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 29667, "s": 29657, "text": "HTML-Misc" }, { "code": null, "e": 29676, "s": 29667, "text": "PHP-Misc" }, { "code": null, "e": 29700, "s": 29676, "text": "Technical Scripter 2020" }, { "code": null, "e": 29705, "s": 29700, "text": "HTML" }, { "code": null, "e": 29709, "s": 29705, "text": "PHP" }, { "code": null, "e": 29722, "s": 29709, "text": "PHP Programs" }, { "code": null, "e": 29741, "s": 29722, "text": "Technical Scripter" }, { "code": null, "e": 29758, "s": 29741, "text": "Web Technologies" }, { "code": null, "e": 29763, "s": 29758, "text": "HTML" }, { "code": null, "e": 29767, "s": 29763, "text": "PHP" }, { "code": null, "e": 29865, "s": 29767, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29913, "s": 29865, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 29937, "s": 29913, "text": "REST API (Introduction)" }, { "code": null, "e": 29987, "s": 29937, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 30037, "s": 29987, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 30074, "s": 30037, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 30119, "s": 30074, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 30169, "s": 30119, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 30209, "s": 30169, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 30233, "s": 30209, "text": "PHP in_array() Function" } ]
How to Enter Your First Kaggle Competition | by Rebecca Vickery | Towards Data Science
Kaggle is probably the most well-known machine learning competition website. A Kaggle competition consists of a dataset made available from the website with a problem to solve with machine, deep learning or some other data science technique. Once you have developed a solution you upload your predictions back onto the site and dependant on the success of your solution will earn a place on a leaderboard for the competition, and possibly even a cash prize. Kaggle can be a great place to hone your machine learning and data science skills, benchmark yourself against others and learn new techniques. In the following article, I am going to provide a walkthrough of how to enter a Kaggle competition for the first time. In this article we will; Develop a model to predict if a tweet is about a genuine disaster. Use the model to make predictions for the test data set supplied by Kaggle. Make the first submission and get placed on the Kaggle leaderboard. One of the latest competitions on the website provides a data set containing tweets together with a label which tells us if they are really about a disaster or not. This competition has a leaderboard with nearly 3,000 entries and a top cash prize of $10,000. The data and competition outline can be viewed here. If you don’t already have a Kaggle account you can create one for free here. If you select “download all” from the competition page you will get a zip file containing three CSV files. The first contains a set of features and their corresponding target label for training purposes. This data set consists of the following attributes: Id: a numerical identifier for the tweet. This will be important when we upload our predictions to the leaderboard. Keyword: a keyword from the tweet which may in some cases be missing. Location: the location the tweet was sent from. This may also not be present. Text: the full text of the tweet. Target: this is the label we are trying to predict. This will be 1 if the tweet is really about a disaster and 0 if not. Let’s read in these files and understand a little more about them. You will notice in the below code that I have included a set_option command. Pandas set_options allow you to control how the format in which the results of a dataframe are displayed. I have included this command here to ensure that the full contents of the text column are displayed which makes my results and analyses easier to view. import pandas as pdpd.set_option('display.max_colwidth', -1)train_data = pd.read_csv('train.csv')train_data.head() The second data set contains only the features and for this data set, we will predict the target label and use the results to gain a place on the leaderboard. test_data = pd.read_csv('test.csv')test_data.head() The third gives us an example of how our submission file should look. This file will contain the id column from the test.csv file and the target we predict with our model. Once we have created this file we will submit it to the website and obtain a position on the leaderboard. sample_submission = pd.read_csv('sample_submission.csv')sample_submission.head() With any machine learning task before we can train a model, we have to perform some data cleaning and preprocessing. This is particularly important when working with text data. To keep things simple for our first model, and because there is a lot of missing data in these columns, we are going to drop the location and keyword features, and only use the actual text from the tweet for training. We are also going to drop the id column as this won’t be useful for training the model. train_data = train_data.drop(['keyword', 'location', 'id'], axis=1)train_data.head() Our data set now looks like this. Text, in particular tweets, can often contain lots of special characters that are not necessarily going to be meaningful to a machine learning algorithm. The first step I am therefore taking is to remove these. I am also making all words lower case. import redef clean_text(df, text_field): df[text_field] = df[text_field].str.lower() df[text_field] = df[text_field].apply(lambda elem: re.sub(r"(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)|^rt|http.+?", "", elem)) return dfdata_clean = clean_text(train_data, "text")data_clean.head() Another useful text cleaning process is the removal of stop words. Stop words are very commonly used words that generally convey little meaning. In English these include words such as “the”, “it” and “as”. If we leave these words in the text they will create a lot of noise which would make it more difficult for the algorithm to learn. NLTK is a collection of python libraries and tools for processing text data, the full documentation can be accessed here. In addition to its processing tools, NLTK also has a large collection of text corpora and lexical resources, including one containing all stop words in a variety of languages. We are going to use this library to remove the stop words from our data sets. The NLTK library can be installed via pip. Once installed you need to import the library corpus and then download the stopwords file. import nltk.corpusnltk.download('stopwords') Once this step is completed you can read in the stop words and use it to remove them from the tweets. from nltk.corpus import stopwordsstop = stopwords.words('english')data_clean['text'] = data_clean['text'].apply(lambda x: ' '.join([word for word in x.split() if word not in (stop)]))data_clean.head() Once clean the data needs further preprocessing to prepare it for use in a machine learning algorithm. All machine learning algorithms use mathematical computations to map patterns in the features, in our case text or words, and the target variable. Before a machine learning model can be trained the text must, therefore, be turned into a numerical representation so that these calculations can be performed. There are a number of methods for this type of preprocessing but I am going to be using two from the scikit-learn library for this example. The first step in this process is to split the data into tokens, or individual words, count the frequency in which each word appears in the text, and then represent these counts as a sparse matrix. The CountVectoriser function achieves this. The next step is to apply a weighting to the word counts produced by CountVectoriser. The goal of applying this weighting is to scale down the impact of very frequently occurring words in the text, so that less frequently occurring, and perhaps more informative words are deemed important during the model training. TfidTransformer can perform this function. Let’s put all this preprocessing together with model fitting in a scikit-learn pipeline and see how the model performs. For the first attempt, I am using a linear support vector machine classifier (SGDClassifier) as this is generally regarded as one of the best text classification algorithms. from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(data_clean['text'],data_clean['target'],random_state = 0)from sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.pipeline import Pipelinefrom sklearn.feature_extraction.text import CountVectorizerfrom sklearn.feature_extraction.text import TfidfTransformerfrom sklearn.linear_model import SGDClassifierpipeline_sgd = Pipeline([ ('vect', CountVectorizer()), ('tfidf', TfidfTransformer()), ('nb', SGDClassifier()),])model = pipeline_sgd.fit(X_train, y_train) Let’s use the trained model to predict on our reserved test data and see how the model performs. from sklearn.metrics import classification_reporty_predict = model.predict(X_test)print(classification_report(y_test, y_predict)) For a first attempt, the model performs reasonably well. Let’s now see how the model performs on the competition test data set and how we rank on the leaderboard. First, we need to clean the text in the test file and use the model to make predictions. The code below takes a copy of the test data and performs the same cleaning we applied to the training data. The output is shown below the code. submission_test_clean = test_data.copy()submission_test_clean = clean_text(submission_test_clean, "text")submission_test_clean['text'] = submission_test_clean['text'].apply(lambda x: ' '.join([word for word in x.split() if word not in (stop)]))submission_test_clean = submission_test_clean['text']submission_test_clean.head() Next, we use the model to create predictions. submission_test_pred = model.predict(submission_test_clean) To create a submission we then need to construct a dataframe containing just the id from the test set and our prediction. id_col = test_data['id']submission_df_1 = pd.DataFrame({ "id": id_col, "target": submission_test_pred})submission_df_1.head() Finally, we save this as a CSV file. It is important to include index=False otherwise, the index will be saved a column in the file and your submission will be rejected. submission_df_1.to_csv('submission_1.csv', index=False) Once we have the CSV file we can return to the competition page and select the submit predictions button. This will open a form where you can upload the CSV file. It is a good idea to add some notes about the approach so that you have a record of the attempts you have previously submitted. Once you have submitted the file you will see this screen. Now we have a successful submission! This model gave me a score of 0.78 on the leaderboard and a ranking of 2,371. There is clearly some room for improvement but now I have a benchmark for future submissions. In this post, I have given an overview of how to make your first submission to a Kaggle competition. There are a lot of further steps you could take to improve on this score. This includes better cleansing of the text, different preprocessing approaches, trying other machine learning algorithms, hyperparameter tuning of the model and much more. Thanks for reading!
[ { "code": null, "e": 630, "s": 172, "text": "Kaggle is probably the most well-known machine learning competition website. A Kaggle competition consists of a dataset made available from the website with a problem to solve with machine, deep learning or some other data science technique. Once you have developed a solution you upload your predictions back onto the site and dependant on the success of your solution will earn a place on a leaderboard for the competition, and possibly even a cash prize." }, { "code": null, "e": 917, "s": 630, "text": "Kaggle can be a great place to hone your machine learning and data science skills, benchmark yourself against others and learn new techniques. In the following article, I am going to provide a walkthrough of how to enter a Kaggle competition for the first time. In this article we will;" }, { "code": null, "e": 984, "s": 917, "text": "Develop a model to predict if a tweet is about a genuine disaster." }, { "code": null, "e": 1060, "s": 984, "text": "Use the model to make predictions for the test data set supplied by Kaggle." }, { "code": null, "e": 1128, "s": 1060, "text": "Make the first submission and get placed on the Kaggle leaderboard." }, { "code": null, "e": 1440, "s": 1128, "text": "One of the latest competitions on the website provides a data set containing tweets together with a label which tells us if they are really about a disaster or not. This competition has a leaderboard with nearly 3,000 entries and a top cash prize of $10,000. The data and competition outline can be viewed here." }, { "code": null, "e": 1517, "s": 1440, "text": "If you don’t already have a Kaggle account you can create one for free here." }, { "code": null, "e": 1624, "s": 1517, "text": "If you select “download all” from the competition page you will get a zip file containing three CSV files." }, { "code": null, "e": 1773, "s": 1624, "text": "The first contains a set of features and their corresponding target label for training purposes. This data set consists of the following attributes:" }, { "code": null, "e": 1889, "s": 1773, "text": "Id: a numerical identifier for the tweet. This will be important when we upload our predictions to the leaderboard." }, { "code": null, "e": 1959, "s": 1889, "text": "Keyword: a keyword from the tweet which may in some cases be missing." }, { "code": null, "e": 2037, "s": 1959, "text": "Location: the location the tweet was sent from. This may also not be present." }, { "code": null, "e": 2071, "s": 2037, "text": "Text: the full text of the tweet." }, { "code": null, "e": 2192, "s": 2071, "text": "Target: this is the label we are trying to predict. This will be 1 if the tweet is really about a disaster and 0 if not." }, { "code": null, "e": 2594, "s": 2192, "text": "Let’s read in these files and understand a little more about them. You will notice in the below code that I have included a set_option command. Pandas set_options allow you to control how the format in which the results of a dataframe are displayed. I have included this command here to ensure that the full contents of the text column are displayed which makes my results and analyses easier to view." }, { "code": null, "e": 2709, "s": 2594, "text": "import pandas as pdpd.set_option('display.max_colwidth', -1)train_data = pd.read_csv('train.csv')train_data.head()" }, { "code": null, "e": 2868, "s": 2709, "text": "The second data set contains only the features and for this data set, we will predict the target label and use the results to gain a place on the leaderboard." }, { "code": null, "e": 2920, "s": 2868, "text": "test_data = pd.read_csv('test.csv')test_data.head()" }, { "code": null, "e": 3198, "s": 2920, "text": "The third gives us an example of how our submission file should look. This file will contain the id column from the test.csv file and the target we predict with our model. Once we have created this file we will submit it to the website and obtain a position on the leaderboard." }, { "code": null, "e": 3279, "s": 3198, "text": "sample_submission = pd.read_csv('sample_submission.csv')sample_submission.head()" }, { "code": null, "e": 3456, "s": 3279, "text": "With any machine learning task before we can train a model, we have to perform some data cleaning and preprocessing. This is particularly important when working with text data." }, { "code": null, "e": 3762, "s": 3456, "text": "To keep things simple for our first model, and because there is a lot of missing data in these columns, we are going to drop the location and keyword features, and only use the actual text from the tweet for training. We are also going to drop the id column as this won’t be useful for training the model." }, { "code": null, "e": 3847, "s": 3762, "text": "train_data = train_data.drop(['keyword', 'location', 'id'], axis=1)train_data.head()" }, { "code": null, "e": 3881, "s": 3847, "text": "Our data set now looks like this." }, { "code": null, "e": 4131, "s": 3881, "text": "Text, in particular tweets, can often contain lots of special characters that are not necessarily going to be meaningful to a machine learning algorithm. The first step I am therefore taking is to remove these. I am also making all words lower case." }, { "code": null, "e": 4431, "s": 4131, "text": "import redef clean_text(df, text_field): df[text_field] = df[text_field].str.lower() df[text_field] = df[text_field].apply(lambda elem: re.sub(r\"(@[A-Za-z0-9]+)|([^0-9A-Za-z \\t])|(\\w+:\\/\\/\\S+)|^rt|http.+?\", \"\", elem)) return dfdata_clean = clean_text(train_data, \"text\")data_clean.head()" }, { "code": null, "e": 4768, "s": 4431, "text": "Another useful text cleaning process is the removal of stop words. Stop words are very commonly used words that generally convey little meaning. In English these include words such as “the”, “it” and “as”. If we leave these words in the text they will create a lot of noise which would make it more difficult for the algorithm to learn." }, { "code": null, "e": 5144, "s": 4768, "text": "NLTK is a collection of python libraries and tools for processing text data, the full documentation can be accessed here. In addition to its processing tools, NLTK also has a large collection of text corpora and lexical resources, including one containing all stop words in a variety of languages. We are going to use this library to remove the stop words from our data sets." }, { "code": null, "e": 5278, "s": 5144, "text": "The NLTK library can be installed via pip. Once installed you need to import the library corpus and then download the stopwords file." }, { "code": null, "e": 5323, "s": 5278, "text": "import nltk.corpusnltk.download('stopwords')" }, { "code": null, "e": 5425, "s": 5323, "text": "Once this step is completed you can read in the stop words and use it to remove them from the tweets." }, { "code": null, "e": 5626, "s": 5425, "text": "from nltk.corpus import stopwordsstop = stopwords.words('english')data_clean['text'] = data_clean['text'].apply(lambda x: ' '.join([word for word in x.split() if word not in (stop)]))data_clean.head()" }, { "code": null, "e": 5729, "s": 5626, "text": "Once clean the data needs further preprocessing to prepare it for use in a machine learning algorithm." }, { "code": null, "e": 6036, "s": 5729, "text": "All machine learning algorithms use mathematical computations to map patterns in the features, in our case text or words, and the target variable. Before a machine learning model can be trained the text must, therefore, be turned into a numerical representation so that these calculations can be performed." }, { "code": null, "e": 6176, "s": 6036, "text": "There are a number of methods for this type of preprocessing but I am going to be using two from the scikit-learn library for this example." }, { "code": null, "e": 6418, "s": 6176, "text": "The first step in this process is to split the data into tokens, or individual words, count the frequency in which each word appears in the text, and then represent these counts as a sparse matrix. The CountVectoriser function achieves this." }, { "code": null, "e": 6777, "s": 6418, "text": "The next step is to apply a weighting to the word counts produced by CountVectoriser. The goal of applying this weighting is to scale down the impact of very frequently occurring words in the text, so that less frequently occurring, and perhaps more informative words are deemed important during the model training. TfidTransformer can perform this function." }, { "code": null, "e": 7071, "s": 6777, "text": "Let’s put all this preprocessing together with model fitting in a scikit-learn pipeline and see how the model performs. For the first attempt, I am using a linear support vector machine classifier (SGDClassifier) as this is generally regarded as one of the best text classification algorithms." }, { "code": null, "e": 7658, "s": 7071, "text": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(data_clean['text'],data_clean['target'],random_state = 0)from sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.pipeline import Pipelinefrom sklearn.feature_extraction.text import CountVectorizerfrom sklearn.feature_extraction.text import TfidfTransformerfrom sklearn.linear_model import SGDClassifierpipeline_sgd = Pipeline([ ('vect', CountVectorizer()), ('tfidf', TfidfTransformer()), ('nb', SGDClassifier()),])model = pipeline_sgd.fit(X_train, y_train)" }, { "code": null, "e": 7755, "s": 7658, "text": "Let’s use the trained model to predict on our reserved test data and see how the model performs." }, { "code": null, "e": 7885, "s": 7755, "text": "from sklearn.metrics import classification_reporty_predict = model.predict(X_test)print(classification_report(y_test, y_predict))" }, { "code": null, "e": 7942, "s": 7885, "text": "For a first attempt, the model performs reasonably well." }, { "code": null, "e": 8048, "s": 7942, "text": "Let’s now see how the model performs on the competition test data set and how we rank on the leaderboard." }, { "code": null, "e": 8282, "s": 8048, "text": "First, we need to clean the text in the test file and use the model to make predictions. The code below takes a copy of the test data and performs the same cleaning we applied to the training data. The output is shown below the code." }, { "code": null, "e": 8608, "s": 8282, "text": "submission_test_clean = test_data.copy()submission_test_clean = clean_text(submission_test_clean, \"text\")submission_test_clean['text'] = submission_test_clean['text'].apply(lambda x: ' '.join([word for word in x.split() if word not in (stop)]))submission_test_clean = submission_test_clean['text']submission_test_clean.head()" }, { "code": null, "e": 8654, "s": 8608, "text": "Next, we use the model to create predictions." }, { "code": null, "e": 8714, "s": 8654, "text": "submission_test_pred = model.predict(submission_test_clean)" }, { "code": null, "e": 8836, "s": 8714, "text": "To create a submission we then need to construct a dataframe containing just the id from the test set and our prediction." }, { "code": null, "e": 8997, "s": 8836, "text": "id_col = test_data['id']submission_df_1 = pd.DataFrame({ \"id\": id_col, \"target\": submission_test_pred})submission_df_1.head()" }, { "code": null, "e": 9167, "s": 8997, "text": "Finally, we save this as a CSV file. It is important to include index=False otherwise, the index will be saved a column in the file and your submission will be rejected." }, { "code": null, "e": 9223, "s": 9167, "text": "submission_df_1.to_csv('submission_1.csv', index=False)" }, { "code": null, "e": 9514, "s": 9223, "text": "Once we have the CSV file we can return to the competition page and select the submit predictions button. This will open a form where you can upload the CSV file. It is a good idea to add some notes about the approach so that you have a record of the attempts you have previously submitted." }, { "code": null, "e": 9573, "s": 9514, "text": "Once you have submitted the file you will see this screen." }, { "code": null, "e": 9610, "s": 9573, "text": "Now we have a successful submission!" }, { "code": null, "e": 9782, "s": 9610, "text": "This model gave me a score of 0.78 on the leaderboard and a ranking of 2,371. There is clearly some room for improvement but now I have a benchmark for future submissions." }, { "code": null, "e": 10129, "s": 9782, "text": "In this post, I have given an overview of how to make your first submission to a Kaggle competition. There are a lot of further steps you could take to improve on this score. This includes better cleansing of the text, different preprocessing approaches, trying other machine learning algorithms, hyperparameter tuning of the model and much more." } ]
How to get memory usage at runtime using C++?
We can get the memory usage like virtual memory usage or resident set size etc. at run time. To get them we can use some system libraries. This process depends on operating systems. For this example, we are using Linux operating system. So here we will see how to get the memory usage statistics under Linux environment using C++. We can get all of the details from “/proc/self/stat” folder. Here we are taking the virtual memory status, and the resident set size. #include <unistd.h> #include <ios> #include <iostream> #include <fstream> #include <string> using namespace std; void mem_usage(double& vm_usage, double& resident_set) { vm_usage = 0.0; resident_set = 0.0; ifstream stat_stream("/proc/self/stat",ios_base::in); //get info from proc directory //create some variables to get info string pid, comm, state, ppid, pgrp, session, tty_nr; string tpgid, flags, minflt, cminflt, majflt, cmajflt; string utime, stime, cutime, cstime, priority, nice; string O, itrealvalue, starttime; unsigned long vsize; long rss; stat_stream >> pid >> comm >> state >> ppid >> pgrp >> session >> tty_nr >> tpgid >> flags >> minflt >> cminflt >> majflt >> cmajflt >> utime >> stime >> cutime >> cstime >> priority >> nice >> O >> itrealvalue >> starttime >> vsize >> rss; // don't care about the rest stat_stream.close(); long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; // for x86-64 is configured to use 2MB pages vm_usage = vsize / 1024.0; resident_set = rss * page_size_kb; } int main() { double vm, rss; mem_usage(vm, rss); cout << "Virtual Memory: " << vm << "\nResident set size: " << rss << endl; } Virtual Memory: 13272 Resident set size: 1548
[ { "code": null, "e": 1299, "s": 1062, "text": "We can get the memory usage like virtual memory usage or resident set size etc. at run time. To get them we can use some system libraries. This process depends on operating systems. For this example, we are using Linux operating system." }, { "code": null, "e": 1527, "s": 1299, "text": "So here we will see how to get the memory usage statistics under Linux environment using C++. We can get all of the details from “/proc/self/stat” folder. Here we are taking the virtual memory status, and the resident set size." }, { "code": null, "e": 2731, "s": 1527, "text": "#include <unistd.h>\n#include <ios>\n#include <iostream>\n#include <fstream>\n#include <string>\nusing namespace std;\nvoid mem_usage(double& vm_usage, double& resident_set) {\n vm_usage = 0.0;\n resident_set = 0.0;\n ifstream stat_stream(\"/proc/self/stat\",ios_base::in); //get info from proc\n directory\n //create some variables to get info\n string pid, comm, state, ppid, pgrp, session, tty_nr;\n string tpgid, flags, minflt, cminflt, majflt, cmajflt;\n string utime, stime, cutime, cstime, priority, nice;\n string O, itrealvalue, starttime;\n unsigned long vsize;\n long rss;\n stat_stream >> pid >> comm >> state >> ppid >> pgrp >> session >> tty_nr\n >> tpgid >> flags >> minflt >> cminflt >> majflt >> cmajflt\n >> utime >> stime >> cutime >> cstime >> priority >> nice\n >> O >> itrealvalue >> starttime >> vsize >> rss; // don't care\n about the rest\n stat_stream.close();\n long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; // for x86-64 is configured\n to use 2MB pages\n vm_usage = vsize / 1024.0;\n resident_set = rss * page_size_kb;\n}\nint main() {\n double vm, rss;\n mem_usage(vm, rss);\n cout << \"Virtual Memory: \" << vm << \"\\nResident set size: \" << rss << endl;\n}" }, { "code": null, "e": 2777, "s": 2731, "text": "Virtual Memory: 13272\nResident set size: 1548" } ]
AI Feynman 2.0: Learning Regression Equations From Data | by Daniel Shapiro, PhD | Towards Data Science
Table of Contents 1. Introduction2. Code3. Their Example4. Our Own Easy Example5. Symbolic Regression on Noisy Data I recently saw a post on LinkedIn from MIT professor Max Tegmark about a new ML library his lab released. I decided to try it out. The paper is AI Feynman 2.0: Pareto-optimal symbolic regression exploiting graph modularity, submitted June 18th, 2020. The first author is Silviu-Marian Udrescu, who was generous enough to hop on a call with me and explain the backstory of this new machine learning library. The library, called AI Feynman 2.0, helps to fit regression formulas to data. More specifically, it helps to fit formulas to data at different levels of complexity (defined in bits). The user can select the operators that the solver will use from sets of operators, and the solver does its thing. Operators are things like exponentiation, cos, arctan, and so on. Symbolic regression is a way of stringing together the user-specified mathematical functions to build an equation for the output “y” that best fits the provided dataset. That provided dataset takes the form of sample points (or observations) for each input variable x0, x1, and so forth, along with the corresponding “y”. Since we don’t want to overfit on the data, we need to limit the allowed complexity of the equation or at least have the ability to solve under a complexity constraint. Unlike a neural network, learning one formula with just a few short expressions in it gives you a highly interpretable model, and can lead to insights that you might not get from a neural network model with millions of weights and biases. Why is this interesting? Well, science tends to generate lots of observations (data) that scientists want to generalize into underlying rules. These rules are equations that “fit” the observations. Unlike a “usual” machine learning model, equations of the form y=f(x) are very clear, and they can omit some of the variables in the data that are not needed. In the practicing machine learning engineer’s toolbox, regression trees would be the closest concept I can think of that implements this idea of learning an interpretable model that connects observations to a prediction. Having a new way to try and fit a regression model to data is a good addition to the toolbox of stuff you can try on your dataset. In this article, I want to explore this new library as a user (how to use it), rather than a scientist (how does it work). AI-Feynman 2.0 reminds me of UMAP, in that it includes very fancy math on the inside of the solver, but does something useful to me in an abstracted way that I can treat as a black box. I understand that the code is going to be updated in stages over the next several months, and so the way the interface to the code looks today may not be the way it works when you are reading this. Hopefully, more documentation will also be added to give you a quick path to trying this on your data. For the moment, I’m including a notebook with this article so that you can dive in and get everything working from one place. The library uses machine learning to help with the equation discovery, breaking the problem into subproblems recursively, but let’s not get too far into the weeds. Let’s instead turn our attention to using the library. You are welcome to read the paper to learn more about how the library does what it does to solve the symbolic regression mystery on your data. A Google Collab notebook containing all of the code for this article is available here: github.com Some notes on the output are important. The solver prints many times the Complexity, RMSE, and Expression. Be aware that the RMSE number is not actually the Root Mean Squared Error. It is the Mean Error Description Length (MEDL) described in the paper, and that message will be changed soon. Also, the Expression printout is not the equation for the dataset, but rather for the sub-problem within the overall problem graph that the solver is currently working on. This is important because you will find that sometimes there is a printout that seems like it has a very low error, but it only applies to some subproblem and is not the equation you are trying to find. The final results are stored in the results folder using the name of the input file. Clone the repository and install the dependencies. Next, compile the Fortran code and run the first example dataset from the AI-Feynman repository (example1.txt from the repository). The first few steps are listed here: Next, put this file into the Code directory and run it with python3: The first line of the example1.txt file is: 1.6821347439986711 1.1786188905177983 4.749225735259924 1.3238356535004034 3.462199507094163 Example 1 contains data generated from an equation, where the last column is the regression target, and the rest of the columns are the input data. The following example shows the relationship between the first line of the file example1.txt and the formula used to make the data. We can see from running the code snippet above that the target “y” data points in example1.txt are generated using the equation on line 3, where the inputs are all the columns except for the last one, and the equation generates the last column. Let’s now run the program. In the folder AI-Feynman/Code/ run the command python3 ai_feynman_magic.py to run the program we wrote above which in turn fits equations to the example1.txt dataset. The solver runs for a long time, trying different kinds of equations at different levels of complexity, and assessing the best fit for each one. As it works through the solution, it prints intermediate results. If it hits a super low error you can stop the program and just use the equation. It’s really your call if you let it run to the end. For the input file example1.txt, the results show up in AI-Feynman/Code/results/solution_example1.txt. There are other spots where results are generated, but this is the place we care about right now. That file “solution_...txt” ranks the identified solutions. It’s funny that assuming y is a constant is a common strategy for the solver. Constants have no input variables, and so they have low complexity in terms of the number of bits. In the case of example 1, the equation ((x0-x1)**2 + (x2-x3)**2)**0.5 fit the best. In the Collab notebook, I now moved the repository and data to Google Drive so that it will persist. The following code generates 10,000 examples from an equation. This example has 2 “x” variables and 2 duplicated “x” variables. Of course, y is still the output. Plotting the first variable against Y we get: Now that we took a peek at what our data looks like, let’s ask the solver to find a simple equation that fits our data, using our dataset. The idea is that we want the solver to notice that you don’t need all of the supplied variables in order to fit the data. Here is an example of a permissions problem: If you have file permission issues when you try to run the code, open up the file permissions like this: chmod +777 AI-Feynman/Code/* Below is the command to run the solver. Go get coffee, because this is not going to be fast... python3 ai_feynman_duplicate_variables.py If you have nothing better to do, watch the solver go. Notice the solver goes through a list of equation types before mixing it up. The initial models it tries out are quickly mapped to x0 and x2 as it “realized” x1 and x3 are duplicates and so not needed. Later on, the solver found the equation 3.000000000000+log(sqrt(exp((x2-x1)))) which is a bit crazy but looks like a plane. We can see on WolframAlpha that an equivalent form of this equation is: y=(x2 - x1)/2 + 3.000000000000 which is what we used to generate the dataset! The solver settled on y=log(sqrt(exp(-x1 + x3))) + 3.0 which we know is a correct description of our plane, from the wolfram alpha thing above. The solver ended up using x1 and x3, dropping x0 because it is a copy of x1 and so not needed, and similarly dropping x2 because it is not needed when using x3. Now, that worked, but it was a bit of a softball problem. The data has an exact solution, and so it didn’t need to fit noisy data, which is not a realistic real-world situation. Real data is messy. Let’s now add noise to the dataset and see how the library holds up. We don’t need to go as far as introducing missing variables and imputation. Let’s just make the problem a tiny bit harder to mess with the solver. The following code creates points on the same plane as the previous example, but this time noise is added. The following figure shows how the duplicate columns are now no longer exact duplicates. Will the solver average the points with noise on them to get a better signal? I would average x0 and x1 into a cleaner point, and then average x2 and x3 into a cleaner point. Let’s see what the solver decides to do. We now make yet another runner file as follows: If you have permissions issues, do the chmod 777 thing, or 775 or whatever. To run the program do this: python3 ai_feynman_duplicateVarsWithNoise.py As the solver works through ideas, it comes up with some wild stuff. You can sort of see in the figure below the plane-like shape in one solution the solver tried: 1.885417681639+log((((x1+1)/cos((x0–1)))+1)). Unfortunately the 2 variables it tried there are x0 and x1, which are duplicates of each other with a small amount of noise added. Nice try solver. Let’s keep it running and see what happens next. The solver found the equation: y = 3.0–0.25*((x0+x1)-(x2+x3)) As I had hoped, the solver figured out that averaging x0 and x1 gets you a cleaner (less noisy) x01, and averaging x2 and x3 similarly results in a less noisy x23. Recall that the original formula used to make “y” was operating on the input data before we added noise to the inputs: y = -0.5*x01+0.5*x23+3 Interestingly, the solver also found y=3.000000000000+log(sqrt(exp((x2-x0)))) This is another version of the formula that uses fewer variables in exchange for a slightly less perfect fit to the data (because of the added noise). And so the solver gives you, the user, the option to see the formula that fits the data at different levels of complexity. A symbolic regression solver called AI-Feynman 2.0 was tested out in this article, starting with the example that comes with the repo, moving to an example we make ourselves from scratch, and finally challenging the solver by adding some noise. A notebook for reproducing this article can be found HERE. Special thanks to Silviu Marian Udrescu for helping me to better understand the code, and for reviewing an earlier draft of this work to make sure I don’t say silly things. This is going to be fun to try on real-world problems. I have been containerizing this library for Gravity-ai.com to apply to real-world datasets. Hopefully you will find it useful and use it for your own work. If you liked this article, then have a look at some of my most read past articles, like “How to Price an AI Project” and “How to Hire an AI Consultant.” And hey, join the newsletter! Until next time!
[ { "code": null, "e": 189, "s": 171, "text": "Table of Contents" }, { "code": null, "e": 287, "s": 189, "text": "1. Introduction2. Code3. Their Example4. Our Own Easy Example5. Symbolic Regression on Noisy Data" }, { "code": null, "e": 1057, "s": 287, "text": "I recently saw a post on LinkedIn from MIT professor Max Tegmark about a new ML library his lab released. I decided to try it out. The paper is AI Feynman 2.0: Pareto-optimal symbolic regression exploiting graph modularity, submitted June 18th, 2020. The first author is Silviu-Marian Udrescu, who was generous enough to hop on a call with me and explain the backstory of this new machine learning library. The library, called AI Feynman 2.0, helps to fit regression formulas to data. More specifically, it helps to fit formulas to data at different levels of complexity (defined in bits). The user can select the operators that the solver will use from sets of operators, and the solver does its thing. Operators are things like exponentiation, cos, arctan, and so on." }, { "code": null, "e": 1787, "s": 1057, "text": "Symbolic regression is a way of stringing together the user-specified mathematical functions to build an equation for the output “y” that best fits the provided dataset. That provided dataset takes the form of sample points (or observations) for each input variable x0, x1, and so forth, along with the corresponding “y”. Since we don’t want to overfit on the data, we need to limit the allowed complexity of the equation or at least have the ability to solve under a complexity constraint. Unlike a neural network, learning one formula with just a few short expressions in it gives you a highly interpretable model, and can lead to insights that you might not get from a neural network model with millions of weights and biases." }, { "code": null, "e": 2496, "s": 1787, "text": "Why is this interesting? Well, science tends to generate lots of observations (data) that scientists want to generalize into underlying rules. These rules are equations that “fit” the observations. Unlike a “usual” machine learning model, equations of the form y=f(x) are very clear, and they can omit some of the variables in the data that are not needed. In the practicing machine learning engineer’s toolbox, regression trees would be the closest concept I can think of that implements this idea of learning an interpretable model that connects observations to a prediction. Having a new way to try and fit a regression model to data is a good addition to the toolbox of stuff you can try on your dataset." }, { "code": null, "e": 3232, "s": 2496, "text": "In this article, I want to explore this new library as a user (how to use it), rather than a scientist (how does it work). AI-Feynman 2.0 reminds me of UMAP, in that it includes very fancy math on the inside of the solver, but does something useful to me in an abstracted way that I can treat as a black box. I understand that the code is going to be updated in stages over the next several months, and so the way the interface to the code looks today may not be the way it works when you are reading this. Hopefully, more documentation will also be added to give you a quick path to trying this on your data. For the moment, I’m including a notebook with this article so that you can dive in and get everything working from one place." }, { "code": null, "e": 3594, "s": 3232, "text": "The library uses machine learning to help with the equation discovery, breaking the problem into subproblems recursively, but let’s not get too far into the weeds. Let’s instead turn our attention to using the library. You are welcome to read the paper to learn more about how the library does what it does to solve the symbolic regression mystery on your data." }, { "code": null, "e": 3682, "s": 3594, "text": "A Google Collab notebook containing all of the code for this article is available here:" }, { "code": null, "e": 3693, "s": 3682, "text": "github.com" }, { "code": null, "e": 4445, "s": 3693, "text": "Some notes on the output are important. The solver prints many times the Complexity, RMSE, and Expression. Be aware that the RMSE number is not actually the Root Mean Squared Error. It is the Mean Error Description Length (MEDL) described in the paper, and that message will be changed soon. Also, the Expression printout is not the equation for the dataset, but rather for the sub-problem within the overall problem graph that the solver is currently working on. This is important because you will find that sometimes there is a printout that seems like it has a very low error, but it only applies to some subproblem and is not the equation you are trying to find. The final results are stored in the results folder using the name of the input file." }, { "code": null, "e": 4628, "s": 4445, "text": "Clone the repository and install the dependencies. Next, compile the Fortran code and run the first example dataset from the AI-Feynman repository (example1.txt from the repository)." }, { "code": null, "e": 4665, "s": 4628, "text": "The first few steps are listed here:" }, { "code": null, "e": 4734, "s": 4665, "text": "Next, put this file into the Code directory and run it with python3:" }, { "code": null, "e": 4778, "s": 4734, "text": "The first line of the example1.txt file is:" }, { "code": null, "e": 4871, "s": 4778, "text": "1.6821347439986711 1.1786188905177983 4.749225735259924 1.3238356535004034 3.462199507094163" }, { "code": null, "e": 5151, "s": 4871, "text": "Example 1 contains data generated from an equation, where the last column is the regression target, and the rest of the columns are the input data. The following example shows the relationship between the first line of the file example1.txt and the formula used to make the data." }, { "code": null, "e": 5396, "s": 5151, "text": "We can see from running the code snippet above that the target “y” data points in example1.txt are generated using the equation on line 3, where the inputs are all the columns except for the last one, and the equation generates the last column." }, { "code": null, "e": 5590, "s": 5396, "text": "Let’s now run the program. In the folder AI-Feynman/Code/ run the command python3 ai_feynman_magic.py to run the program we wrote above which in turn fits equations to the example1.txt dataset." }, { "code": null, "e": 6456, "s": 5590, "text": "The solver runs for a long time, trying different kinds of equations at different levels of complexity, and assessing the best fit for each one. As it works through the solution, it prints intermediate results. If it hits a super low error you can stop the program and just use the equation. It’s really your call if you let it run to the end. For the input file example1.txt, the results show up in AI-Feynman/Code/results/solution_example1.txt. There are other spots where results are generated, but this is the place we care about right now. That file “solution_...txt” ranks the identified solutions. It’s funny that assuming y is a constant is a common strategy for the solver. Constants have no input variables, and so they have low complexity in terms of the number of bits. In the case of example 1, the equation ((x0-x1)**2 + (x2-x3)**2)**0.5 fit the best." }, { "code": null, "e": 6719, "s": 6456, "text": "In the Collab notebook, I now moved the repository and data to Google Drive so that it will persist. The following code generates 10,000 examples from an equation. This example has 2 “x” variables and 2 duplicated “x” variables. Of course, y is still the output." }, { "code": null, "e": 6765, "s": 6719, "text": "Plotting the first variable against Y we get:" }, { "code": null, "e": 7026, "s": 6765, "text": "Now that we took a peek at what our data looks like, let’s ask the solver to find a simple equation that fits our data, using our dataset. The idea is that we want the solver to notice that you don’t need all of the supplied variables in order to fit the data." }, { "code": null, "e": 7071, "s": 7026, "text": "Here is an example of a permissions problem:" }, { "code": null, "e": 7176, "s": 7071, "text": "If you have file permission issues when you try to run the code, open up the file permissions like this:" }, { "code": null, "e": 7205, "s": 7176, "text": "chmod +777 AI-Feynman/Code/*" }, { "code": null, "e": 7300, "s": 7205, "text": "Below is the command to run the solver. Go get coffee, because this is not going to be fast..." }, { "code": null, "e": 7342, "s": 7300, "text": "python3 ai_feynman_duplicate_variables.py" }, { "code": null, "e": 7723, "s": 7342, "text": "If you have nothing better to do, watch the solver go. Notice the solver goes through a list of equation types before mixing it up. The initial models it tries out are quickly mapped to x0 and x2 as it “realized” x1 and x3 are duplicates and so not needed. Later on, the solver found the equation 3.000000000000+log(sqrt(exp((x2-x1)))) which is a bit crazy but looks like a plane." }, { "code": null, "e": 7795, "s": 7723, "text": "We can see on WolframAlpha that an equivalent form of this equation is:" }, { "code": null, "e": 7826, "s": 7795, "text": "y=(x2 - x1)/2 + 3.000000000000" }, { "code": null, "e": 7873, "s": 7826, "text": "which is what we used to generate the dataset!" }, { "code": null, "e": 8178, "s": 7873, "text": "The solver settled on y=log(sqrt(exp(-x1 + x3))) + 3.0 which we know is a correct description of our plane, from the wolfram alpha thing above. The solver ended up using x1 and x3, dropping x0 because it is a copy of x1 and so not needed, and similarly dropping x2 because it is not needed when using x3." }, { "code": null, "e": 8592, "s": 8178, "text": "Now, that worked, but it was a bit of a softball problem. The data has an exact solution, and so it didn’t need to fit noisy data, which is not a realistic real-world situation. Real data is messy. Let’s now add noise to the dataset and see how the library holds up. We don’t need to go as far as introducing missing variables and imputation. Let’s just make the problem a tiny bit harder to mess with the solver." }, { "code": null, "e": 8699, "s": 8592, "text": "The following code creates points on the same plane as the previous example, but this time noise is added." }, { "code": null, "e": 9004, "s": 8699, "text": "The following figure shows how the duplicate columns are now no longer exact duplicates. Will the solver average the points with noise on them to get a better signal? I would average x0 and x1 into a cleaner point, and then average x2 and x3 into a cleaner point. Let’s see what the solver decides to do." }, { "code": null, "e": 9052, "s": 9004, "text": "We now make yet another runner file as follows:" }, { "code": null, "e": 9156, "s": 9052, "text": "If you have permissions issues, do the chmod 777 thing, or 775 or whatever. To run the program do this:" }, { "code": null, "e": 9201, "s": 9156, "text": "python3 ai_feynman_duplicateVarsWithNoise.py" }, { "code": null, "e": 9542, "s": 9201, "text": "As the solver works through ideas, it comes up with some wild stuff. You can sort of see in the figure below the plane-like shape in one solution the solver tried: 1.885417681639+log((((x1+1)/cos((x0–1)))+1)). Unfortunately the 2 variables it tried there are x0 and x1, which are duplicates of each other with a small amount of noise added." }, { "code": null, "e": 9608, "s": 9542, "text": "Nice try solver. Let’s keep it running and see what happens next." }, { "code": null, "e": 9639, "s": 9608, "text": "The solver found the equation:" }, { "code": null, "e": 9670, "s": 9639, "text": "y = 3.0–0.25*((x0+x1)-(x2+x3))" }, { "code": null, "e": 9953, "s": 9670, "text": "As I had hoped, the solver figured out that averaging x0 and x1 gets you a cleaner (less noisy) x01, and averaging x2 and x3 similarly results in a less noisy x23. Recall that the original formula used to make “y” was operating on the input data before we added noise to the inputs:" }, { "code": null, "e": 9976, "s": 9953, "text": "y = -0.5*x01+0.5*x23+3" }, { "code": null, "e": 10013, "s": 9976, "text": "Interestingly, the solver also found" }, { "code": null, "e": 10054, "s": 10013, "text": "y=3.000000000000+log(sqrt(exp((x2-x0))))" }, { "code": null, "e": 10328, "s": 10054, "text": "This is another version of the formula that uses fewer variables in exchange for a slightly less perfect fit to the data (because of the added noise). And so the solver gives you, the user, the option to see the formula that fits the data at different levels of complexity." }, { "code": null, "e": 10632, "s": 10328, "text": "A symbolic regression solver called AI-Feynman 2.0 was tested out in this article, starting with the example that comes with the repo, moving to an example we make ourselves from scratch, and finally challenging the solver by adding some noise. A notebook for reproducing this article can be found HERE." }, { "code": null, "e": 11016, "s": 10632, "text": "Special thanks to Silviu Marian Udrescu for helping me to better understand the code, and for reviewing an earlier draft of this work to make sure I don’t say silly things. This is going to be fun to try on real-world problems. I have been containerizing this library for Gravity-ai.com to apply to real-world datasets. Hopefully you will find it useful and use it for your own work." }, { "code": null, "e": 11199, "s": 11016, "text": "If you liked this article, then have a look at some of my most read past articles, like “How to Price an AI Project” and “How to Hire an AI Consultant.” And hey, join the newsletter!" } ]
Select Random Element from List in R - GeeksforGeeks
23 Sep, 2021 In this article, we will discuss how to select a random element from a List using R programming language. We can select a Random element from a list by using the sample() function. sample() function is used to get the random element from the data structure Syntax: sample(1:length(list), n) where 1:length(list) is used to iterate all elements over a list n represents the number of random elements to be returned Note: In our case n=1 because we have to get only one random element. Example: R program to create a list of numbers and return one random element R # create a list of integerslist1=list(1:10,23,45,67,8) # get the random element from the listlist1[[sample(1:length(list1), 1)]] Output: Test 1: [1] 67 Test 2: [1] 45 Example: R program to create a list of numbers and return one random element R # create a vector of integersvec=c(1,2,3,4,5) # create a variabledata="Hello Geek" # pass the vector and variable to listlist1=list(vec,data) # get the random element from the listlist1[[sample(1:length(list1), 1)]] Output: [1] 1 2 3 4 5 Picked R List-Programs R-List R Language R Programs 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? Data Visualization in R How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? Merge DataFrames by Column Names in R
[ { "code": null, "e": 25162, "s": 25134, "text": "\n23 Sep, 2021" }, { "code": null, "e": 25268, "s": 25162, "text": "In this article, we will discuss how to select a random element from a List using R programming language." }, { "code": null, "e": 25419, "s": 25268, "text": "We can select a Random element from a list by using the sample() function. sample() function is used to get the random element from the data structure" }, { "code": null, "e": 25427, "s": 25419, "text": "Syntax:" }, { "code": null, "e": 25453, "s": 25427, "text": "sample(1:length(list), n)" }, { "code": null, "e": 25459, "s": 25453, "text": "where" }, { "code": null, "e": 25518, "s": 25459, "text": "1:length(list) is used to iterate all elements over a list" }, { "code": null, "e": 25576, "s": 25518, "text": "n represents the number of random elements to be returned" }, { "code": null, "e": 25646, "s": 25576, "text": "Note: In our case n=1 because we have to get only one random element." }, { "code": null, "e": 25724, "s": 25646, "text": "Example: R program to create a list of numbers and return one random element" }, { "code": null, "e": 25726, "s": 25724, "text": "R" }, { "code": "# create a list of integerslist1=list(1:10,23,45,67,8) # get the random element from the listlist1[[sample(1:length(list1), 1)]]", "e": 25856, "s": 25726, "text": null }, { "code": null, "e": 25864, "s": 25856, "text": "Output:" }, { "code": null, "e": 25872, "s": 25864, "text": "Test 1:" }, { "code": null, "e": 25879, "s": 25872, "text": "[1] 67" }, { "code": null, "e": 25887, "s": 25879, "text": "Test 2:" }, { "code": null, "e": 25894, "s": 25887, "text": "[1] 45" }, { "code": null, "e": 25972, "s": 25894, "text": "Example: R program to create a list of numbers and return one random element" }, { "code": null, "e": 25974, "s": 25972, "text": "R" }, { "code": "# create a vector of integersvec=c(1,2,3,4,5) # create a variabledata=\"Hello Geek\" # pass the vector and variable to listlist1=list(vec,data) # get the random element from the listlist1[[sample(1:length(list1), 1)]]", "e": 26193, "s": 25974, "text": null }, { "code": null, "e": 26201, "s": 26193, "text": "Output:" }, { "code": null, "e": 26215, "s": 26201, "text": "[1] 1 2 3 4 5" }, { "code": null, "e": 26222, "s": 26215, "text": "Picked" }, { "code": null, "e": 26238, "s": 26222, "text": "R List-Programs" }, { "code": null, "e": 26245, "s": 26238, "text": "R-List" }, { "code": null, "e": 26256, "s": 26245, "text": "R Language" }, { "code": null, "e": 26267, "s": 26256, "text": "R Programs" }, { "code": null, "e": 26365, "s": 26267, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26374, "s": 26365, "text": "Comments" }, { "code": null, "e": 26387, "s": 26374, "text": "Old Comments" }, { "code": null, "e": 26439, "s": 26387, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 26477, "s": 26439, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 26512, "s": 26477, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 26570, "s": 26512, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 26594, "s": 26570, "text": "Data Visualization in R" }, { "code": null, "e": 26652, "s": 26594, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 26695, "s": 26652, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 26744, "s": 26695, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 26794, "s": 26744, "text": "How to filter R dataframe by multiple conditions?" } ]
TextPlot: R Library for Visualizing Text Data | Towards Data Science
Data visualization is an essential task in data science. We can gain insights from the data visualization so it can support our decision for our problems. Text data is one of the most analyzed data by many people. It is also one of the most complex data because we have to spend a lot of time preprocessing the data, ranging from tokenizing the text, deleting terms that are not meaningful, creating a document term matrix, etc. Visualizing data like text sometimes can have the same complexities as preprocessing it. Thankfully, there’s a library that can help us to visualize text data. It’s called TextPlot. TextPlot is a library that is implemented with the R programming language. TextPlot can visualize many things, for example, word frequencies chart, word correlation graph, dependency parsing, and many more. In this article, I will show you how to use the TextPlot library for visualizing text data using R. Without further, let’s get started! Before we play with the library, we need to install the libraries and load them into our environment. Here is the script for doing that, install.packages("textplot")install.packages('udpipe')install.packages('igraph')install.packages('ggraph')install.packages('concaveman')install.packages('BTM')install.packages('glasso')install.packages('qgraph')install.packages('graph')library(ggraph)library(concaveman)library(ggplot2)library(BTM)library(textplot)library(udpipe)library(igraph)library(graph)library(Rgraphviz) The first visualization that you can do with this library is the word frequencies bar chart. For the input, it takes a table that has words and their frequencies. Let’s see how does it look by running this code first, data(brussels_listings, package = 'udpipe')x <- table(brussels_listings$neighbourhood)x <- sort(x)x Here is the preview of the input looks like, To create word frequencies bar chart, you need to run the textplot_bar function from textplot library. Here is the command look like, textplot_bar(x, panel = "Locations", col.panel = "darkgrey", xlab = "Listings", cextext = 0.75, addpct = TRUE, cexpct = 0.5) Here is the chart looks like, As you can see above, the x-axis represents the number of words, and the y axis represents the word itself. Also, each word has information like the amount and the percentage of the word. Another visualization that you can create is the word similarity chart. This chart will visualize the similarity between words in a graph representation. Document Term Matrix (DTM) will be used as the input. DTM is a text representation where each row represents a document, each column represents words, and each cell represents the frequency of words in a document. To create a DTM, you can use command from a text plot like this, data(brussels_reviews_anno, package = 'udpipe')x <- subset(brussels_reviews_anno, xpos %in% "NN" & language %in% "nl" & !is.na(lemma))x <- document_term_frequencies(x, document = "doc_id", term = "lemma")dtm <- document_term_matrix(x)dtm <- dtm_remove_lowfreq(dtm, maxterms = 60)dtm Here is how the matrix look like, After you create the DTM, the next step is to create a correlation matrix by calculating the correlation of each word. To do that, we can use the dtm_cor function where it takes the DTM as the parameter. Here is the command look like, m <- dtm_cor(dtm) Here is the preview of the correlation matrix look like, Now you can create the word correlation graph chart. To do that, we can use the textplot_correlation_glasso function to generate the chart. Besides giving the input, we also set the exclude_zero parameter to true, so it doesn’t show the words that have zero correlation. Here is what the function looks like, textplot_correlation_glasso(m, exclude_zero = TRUE) Here is the result, As you can see above, as the line gets thicker, the correlation is also getting bigger. For example, you can see that word ‘badkamer’, ‘slaapkamer’, and ‘woonkamer’ relates stronger than any words on the graph. Those words are from the dutch language, and they have the same word ‘kamer’ that occur on them. It means room. Another visualization that I want to show you is dependency parsing. Dependency parsing is a way to see which word is dependent on another and how do words relate to each other. Let’s take this sentence as input. sentence <- “UDPipe provides tokenization, tagging, lemmatization and dependency parsing of raw text” To retrieve the dependency parsing, we need to tokenize the sentence and assign the part-of-speech (POS) tag to each word. Thankfully, this process is already done by the udpipe function from the udpipe library. The command looks like this, x <- udpipe(sentence, "english") After that, we will generate the dependency parsing with the textplot_dependencyparser function from the textplot library. The command looks like this, textplot_dependencyparser(x) Here is how the visualization look like, As you can see above, the chart shows the POS tag below the word and the arrow that draws the relationship between words. The last visualization that I want to show you is the word cooccurrence graph. This graph visualizes collections of word pair and how frequent these word pairs occur. We can use a function called textplot_cooccurrence to visualize this chart. Now let’s take the data first. We will use the same data that we use above. With that data, we create a cooccurrence data frame where each row contains the word pair and how many they occur. That cooccurrence data frame will be used as the input for the textplot_cooccurrence function. The code for the data looks like this, data(brussels_reviews_anno, package = 'udpipe')x <- subset(brussels_reviews_anno, xpos %in% "JJ" & language %in% "fr")x <- cooccurrence(x, group = "doc_id", term = "lemma") Here is the data look like, After we get the correct input, now we can create the chart. We will take only the 25 most occur word pairs. Here is the command to do that, textplot_cooccurrence(x, top_n = 25, subtitle = "showing only top 25") Here is the visualization, As you can see, the word pair of ‘agreable’ and ‘bon’ is the most occur on the data. Congratulations! Now you have learned how to use text plot in R. I hope you can use this library on your data science pipeline for solving your data visualization, especially on text data. If you want to see more of my writing, you can follow me on medium. Also, if you have any questions or to have a conversation with me, you can connect with me on LinkedIn. Thank you for reading my article!
[ { "code": null, "e": 327, "s": 172, "text": "Data visualization is an essential task in data science. We can gain insights from the data visualization so it can support our decision for our problems." }, { "code": null, "e": 601, "s": 327, "text": "Text data is one of the most analyzed data by many people. It is also one of the most complex data because we have to spend a lot of time preprocessing the data, ranging from tokenizing the text, deleting terms that are not meaningful, creating a document term matrix, etc." }, { "code": null, "e": 783, "s": 601, "text": "Visualizing data like text sometimes can have the same complexities as preprocessing it. Thankfully, there’s a library that can help us to visualize text data. It’s called TextPlot." }, { "code": null, "e": 990, "s": 783, "text": "TextPlot is a library that is implemented with the R programming language. TextPlot can visualize many things, for example, word frequencies chart, word correlation graph, dependency parsing, and many more." }, { "code": null, "e": 1126, "s": 990, "text": "In this article, I will show you how to use the TextPlot library for visualizing text data using R. Without further, let’s get started!" }, { "code": null, "e": 1263, "s": 1126, "text": "Before we play with the library, we need to install the libraries and load them into our environment. Here is the script for doing that," }, { "code": null, "e": 1641, "s": 1263, "text": "install.packages(\"textplot\")install.packages('udpipe')install.packages('igraph')install.packages('ggraph')install.packages('concaveman')install.packages('BTM')install.packages('glasso')install.packages('qgraph')install.packages('graph')library(ggraph)library(concaveman)library(ggplot2)library(BTM)library(textplot)library(udpipe)library(igraph)library(graph)library(Rgraphviz)" }, { "code": null, "e": 1859, "s": 1641, "text": "The first visualization that you can do with this library is the word frequencies bar chart. For the input, it takes a table that has words and their frequencies. Let’s see how does it look by running this code first," }, { "code": null, "e": 1959, "s": 1859, "text": "data(brussels_listings, package = 'udpipe')x <- table(brussels_listings$neighbourhood)x <- sort(x)x" }, { "code": null, "e": 2004, "s": 1959, "text": "Here is the preview of the input looks like," }, { "code": null, "e": 2138, "s": 2004, "text": "To create word frequencies bar chart, you need to run the textplot_bar function from textplot library. Here is the command look like," }, { "code": null, "e": 2263, "s": 2138, "text": "textplot_bar(x, panel = \"Locations\", col.panel = \"darkgrey\", xlab = \"Listings\", cextext = 0.75, addpct = TRUE, cexpct = 0.5)" }, { "code": null, "e": 2293, "s": 2263, "text": "Here is the chart looks like," }, { "code": null, "e": 2481, "s": 2293, "text": "As you can see above, the x-axis represents the number of words, and the y axis represents the word itself. Also, each word has information like the amount and the percentage of the word." }, { "code": null, "e": 2635, "s": 2481, "text": "Another visualization that you can create is the word similarity chart. This chart will visualize the similarity between words in a graph representation." }, { "code": null, "e": 2849, "s": 2635, "text": "Document Term Matrix (DTM) will be used as the input. DTM is a text representation where each row represents a document, each column represents words, and each cell represents the frequency of words in a document." }, { "code": null, "e": 2914, "s": 2849, "text": "To create a DTM, you can use command from a text plot like this," }, { "code": null, "e": 3197, "s": 2914, "text": "data(brussels_reviews_anno, package = 'udpipe')x <- subset(brussels_reviews_anno, xpos %in% \"NN\" & language %in% \"nl\" & !is.na(lemma))x <- document_term_frequencies(x, document = \"doc_id\", term = \"lemma\")dtm <- document_term_matrix(x)dtm <- dtm_remove_lowfreq(dtm, maxterms = 60)dtm" }, { "code": null, "e": 3231, "s": 3197, "text": "Here is how the matrix look like," }, { "code": null, "e": 3466, "s": 3231, "text": "After you create the DTM, the next step is to create a correlation matrix by calculating the correlation of each word. To do that, we can use the dtm_cor function where it takes the DTM as the parameter. Here is the command look like," }, { "code": null, "e": 3484, "s": 3466, "text": "m <- dtm_cor(dtm)" }, { "code": null, "e": 3541, "s": 3484, "text": "Here is the preview of the correlation matrix look like," }, { "code": null, "e": 3681, "s": 3541, "text": "Now you can create the word correlation graph chart. To do that, we can use the textplot_correlation_glasso function to generate the chart." }, { "code": null, "e": 3850, "s": 3681, "text": "Besides giving the input, we also set the exclude_zero parameter to true, so it doesn’t show the words that have zero correlation. Here is what the function looks like," }, { "code": null, "e": 3902, "s": 3850, "text": "textplot_correlation_glasso(m, exclude_zero = TRUE)" }, { "code": null, "e": 3922, "s": 3902, "text": "Here is the result," }, { "code": null, "e": 4245, "s": 3922, "text": "As you can see above, as the line gets thicker, the correlation is also getting bigger. For example, you can see that word ‘badkamer’, ‘slaapkamer’, and ‘woonkamer’ relates stronger than any words on the graph. Those words are from the dutch language, and they have the same word ‘kamer’ that occur on them. It means room." }, { "code": null, "e": 4423, "s": 4245, "text": "Another visualization that I want to show you is dependency parsing. Dependency parsing is a way to see which word is dependent on another and how do words relate to each other." }, { "code": null, "e": 4458, "s": 4423, "text": "Let’s take this sentence as input." }, { "code": null, "e": 4560, "s": 4458, "text": "sentence <- “UDPipe provides tokenization, tagging, lemmatization and dependency parsing of raw text”" }, { "code": null, "e": 4801, "s": 4560, "text": "To retrieve the dependency parsing, we need to tokenize the sentence and assign the part-of-speech (POS) tag to each word. Thankfully, this process is already done by the udpipe function from the udpipe library. The command looks like this," }, { "code": null, "e": 4834, "s": 4801, "text": "x <- udpipe(sentence, \"english\")" }, { "code": null, "e": 4986, "s": 4834, "text": "After that, we will generate the dependency parsing with the textplot_dependencyparser function from the textplot library. The command looks like this," }, { "code": null, "e": 5015, "s": 4986, "text": "textplot_dependencyparser(x)" }, { "code": null, "e": 5056, "s": 5015, "text": "Here is how the visualization look like," }, { "code": null, "e": 5178, "s": 5056, "text": "As you can see above, the chart shows the POS tag below the word and the arrow that draws the relationship between words." }, { "code": null, "e": 5345, "s": 5178, "text": "The last visualization that I want to show you is the word cooccurrence graph. This graph visualizes collections of word pair and how frequent these word pairs occur." }, { "code": null, "e": 5497, "s": 5345, "text": "We can use a function called textplot_cooccurrence to visualize this chart. Now let’s take the data first. We will use the same data that we use above." }, { "code": null, "e": 5707, "s": 5497, "text": "With that data, we create a cooccurrence data frame where each row contains the word pair and how many they occur. That cooccurrence data frame will be used as the input for the textplot_cooccurrence function." }, { "code": null, "e": 5746, "s": 5707, "text": "The code for the data looks like this," }, { "code": null, "e": 5919, "s": 5746, "text": "data(brussels_reviews_anno, package = 'udpipe')x <- subset(brussels_reviews_anno, xpos %in% \"JJ\" & language %in% \"fr\")x <- cooccurrence(x, group = \"doc_id\", term = \"lemma\")" }, { "code": null, "e": 5947, "s": 5919, "text": "Here is the data look like," }, { "code": null, "e": 6088, "s": 5947, "text": "After we get the correct input, now we can create the chart. We will take only the 25 most occur word pairs. Here is the command to do that," }, { "code": null, "e": 6159, "s": 6088, "text": "textplot_cooccurrence(x, top_n = 25, subtitle = \"showing only top 25\")" }, { "code": null, "e": 6186, "s": 6159, "text": "Here is the visualization," }, { "code": null, "e": 6271, "s": 6186, "text": "As you can see, the word pair of ‘agreable’ and ‘bon’ is the most occur on the data." }, { "code": null, "e": 6460, "s": 6271, "text": "Congratulations! Now you have learned how to use text plot in R. I hope you can use this library on your data science pipeline for solving your data visualization, especially on text data." }, { "code": null, "e": 6632, "s": 6460, "text": "If you want to see more of my writing, you can follow me on medium. Also, if you have any questions or to have a conversation with me, you can connect with me on LinkedIn." } ]
Count numbers in given range such that sum of even digits is greater than sum of odd digits - GeeksforGeeks
11 Nov, 2019 Given two integers L and R denoting a range [L, R]. The task is to find the total count of numbers in the given range [L,R] whose sum of even digits is greater than the sum of odd digits. Examples: Input : L=2 R=10Output : 4Numbers having the property that sum of evendigits is greater than sum of odd digits are: 2, 4, 6, 8 Input : L=2 R=17Output : 7 Prerequisites: Digit-DP Approach:Firstly, count the required numbers up to R i.e. in the range [0, R]. To reach the answer in the range [L, R] solve for the range from zero to R and then subtracting the answer for the range from zero to L – 1. Define the DP states as follows: Consider the number as a sequence of digits, one state is the position at which we are currently at. This position can have values from 0 to 18 if we are dealing with the numbers up to 10^18. In each recursive call, try to build the sequence from left to right by placing a digit from 0 to 9. First state is the sum of the even digits that has been placed so far. Second state is the sum of the odd digits that has been placed so far. Another state is the boolean variable tight which tells the number we are trying to build has already become smaller than R so that in the upcoming recursive calls we can place any digit from 0 to 9. If the number has not become smaller, the maximum limit of digit we can place is the digit at the current position in R. Below is the implementation of the above approach: C++ Java Python3 C# // C++ code to count number in the range// having the sum of even digits greater// than the sum of odd digits#include <bits/stdc++.h> // as the number can be up to 10^18#define int long long using namespace std; vector<int> v; int dp[18][180][180][2]; int memo(int index, int evenSum, int oddSum, int tight){ // Base Case if (index == v.size()) { // check if condition satisfied or not if (evenSum > oddSum) return 1; else return 0; } // If this result is already computed // simply return it if (dp[index][evenSum][oddSum][tight] != -1) return dp[index][evenSum][oddSum][tight]; // Maximum limit upto which we can place // digit. If tight is 0, means number has // already become smaller so we can place // any digit, otherwise num[pos] int limit = (tight) ? v[index] : 9; int ans = 0; for (int d = 0; d <= limit; d++) { int currTight = 0; if (d == v[index]) currTight = tight; // if current digit is odd if (d % 2 != 0) ans += memo(index + 1, evenSum, oddSum + d, currTight); // if current digit is even else ans += memo(index + 1, evenSum + d, oddSum, currTight); } dp[index][evenSum][oddSum][tight] = ans; return ans;}// Function to convert n into its// digit vector and uses memo() function// to return the required countint CountNum(int n){ v.clear(); while (n) { v.push_back(n % 10); n = n / 10; } reverse(v.begin(), v.end()); // Initialize DP memset(dp, -1, sizeof(dp)); return memo(0, 0, 0, 1);} // Driver Code int32_t main(){ int L, R; L = 2; R = 10; cout << CountNum(R) - CountNum(L - 1) << "\n"; return 0;} // Java code to count number in the range// having the sum of even digits greater// than the sum of odd digitsimport java.util.*; class GFG{ static Vector<Integer> v = new Vector<>(); static int[][][][] dp = new int[18][180][180][2]; static int memo(int index, int evenSum, int oddSum, int tight) { // Base Case if (index == v.size()) { // check if condition satisfied or not if (evenSum > oddSum) { return 1; } else { return 0; } } // If this result is already computed // simply return it if (dp[index][evenSum][oddSum][tight] != -1) { return dp[index][evenSum][oddSum][tight]; } // Maximum limit upto which we can place // digit. If tight is 0, means number has // already become smaller so we can place // any digit, otherwise num[pos] int limit = (tight > 0) ? v.get(index) : 9; int ans = 0; for (int d = 0; d <= limit; d++) { int currTight = 0; if (d == v.get(index)) { currTight = tight; } // if current digit is odd if (d % 2 != 0) { ans += memo(index + 1, evenSum, oddSum + d, currTight); } // if current digit is even else { ans += memo(index + 1, evenSum + d, oddSum, currTight); } } dp[index][evenSum][oddSum][tight] = ans; return ans; } // Function to convert n into its // digit vector and uses memo() function // to return the required count static int CountNum(int n) { v.clear(); while (n > 0) { v.add(n % 10); n = n / 10; } Collections.reverse(v); // Initialize DP for (int i = 0; i < 18; i++) { for (int j = 0; j < 180; j++) { for (int k = 0; k < 180; k++) { for (int l = 0; l < 2; l++) { dp[i][j][k][l] = -1; } } } } return memo(0, 0, 0, 1); } // Driver Code public static void main(String[] args) { int L, R; L = 2; R = 10; System.out.println(CountNum(R) - CountNum(L - 1)); }} // This code is contributed by Princi Singh # Python code to count number in the range# having the sum of even digits greater# than the sum of odd digits def memo(index, evenSum, oddSum, tight): # Base Case if index == len(v): # check if condition satisfied or not if evenSum > oddSum: return 1 else: return 0 # If this result is already computed # simply return it if dp[index][evenSum][oddSum][tight] != -1: return dp[index][evenSum][oddSum][tight] # Maximum limit upto which we can place # digit. If tight is 0, means number has # already become smaller so we can place # any digit, otherwise num[index] limit = v[index] if tight else 9 ans = 0 for d in range(limit + 1): currTight = 0 if d == v[index]: currTight = tight # if current digit is odd if d % 2 != 0: ans += memo(index + 1, evenSum, oddSum + d, currTight) # if current digit is even else: ans += memo(index + 1, evenSum + d, oddSum, currTight) dp[index][evenSum][oddSum][tight] = ans return ans # Function to convert n into its digit vector# and uses memo() function to return the# required countdef countNum(n): global dp, v v.clear() num = [] while n: v.append(n % 10) n //= 10 v.reverse() # Initialize dp dp = [[[[-1, -1] for i in range(180)] for j in range(180)] for k in range(18)] return memo(0, 0, 0, 1) # Driver Codeif __name__ == "__main__": dp = [] v = [] L = 2 R = 10 print(countNum(R) - countNum(L - 1)) # This code is contributed by# sanjeev2552 // C# code to count number in the range// having the sum of even digits greater// than the sum of odd digitsusing System.Collections.Generic;using System; class GFG{ static List<int> v = new List<int>(); static int [,,,]dp = new int[18,180,180,2]; static int memo(int index, int evenSum, int oddSum, int tight) { // Base Case if (index == v.Count) { // check if condition satisfied or not if (evenSum > oddSum) { return 1; } else { return 0; } } // If this result is already computed // simply return it if (dp[index,evenSum,oddSum,tight] != -1) { return dp[index,evenSum,oddSum,tight]; } // Maximum limit upto which we can place // digit. If tight is 0, means number has // already become smaller so we can place // any digit, otherwise num[pos] int limit = (tight > 0) ? v[index] : 9; int ans = 0; for (int d = 0; d <= limit; d++) { int currTight = 0; if (d == v[index]) { currTight = tight; } // if current digit is odd if (d % 2 != 0) { ans += memo(index + 1, evenSum, oddSum + d, currTight); } // if current digit is even else { ans += memo(index + 1, evenSum + d, oddSum, currTight); } } dp[index,evenSum,oddSum,tight] = ans; return ans; } // Function to convert n into its // digit vector and uses memo() function // to return the required count static int CountNum(int n) { v.Clear(); while (n > 0) { v.Add(n % 10); n = n / 10; } v.Reverse(); // Initialize DP for (int i = 0; i < 18; i++) { for (int j = 0; j < 180; j++) { for (int k = 0; k < 180; k++) { for (int l = 0; l < 2; l++) { dp[i,j,k,l] = -1; } } } } return memo(0, 0, 0, 1); } // Driver Code public static void Main(String[] args) { int L, R; L = 2; R = 10; Console.WriteLine(CountNum(R) - CountNum(L - 1)); }} /* This code is contributed by PrinciRaj1992 */ 4 Time Complexity : There would be at max 18*(180)*(180)*2 computations when 0 < a,b < 1018 princi singh princiraj1992 sanjeev2552 digit-DP Numbers Dynamic Programming Mathematical Dynamic Programming Mathematical Numbers Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Optimal Substructure Property in Dynamic Programming | DP-2 Min Cost Path | DP-6 Maximum Subarray Sum using Divide and Conquer algorithm Optimal Binary Search Tree | DP-24 Greedy approach vs Dynamic programming Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Program to find sum of elements in a given array Modulo Operator (%) in C/C++ with Examples
[ { "code": null, "e": 24592, "s": 24564, "text": "\n11 Nov, 2019" }, { "code": null, "e": 24780, "s": 24592, "text": "Given two integers L and R denoting a range [L, R]. The task is to find the total count of numbers in the given range [L,R] whose sum of even digits is greater than the sum of odd digits." }, { "code": null, "e": 24790, "s": 24780, "text": "Examples:" }, { "code": null, "e": 24917, "s": 24790, "text": "Input : L=2 R=10Output : 4Numbers having the property that sum of evendigits is greater than sum of odd digits are: 2, 4, 6, 8" }, { "code": null, "e": 24944, "s": 24917, "text": "Input : L=2 R=17Output : 7" }, { "code": null, "e": 24968, "s": 24944, "text": "Prerequisites: Digit-DP" }, { "code": null, "e": 25221, "s": 24968, "text": "Approach:Firstly, count the required numbers up to R i.e. in the range [0, R]. To reach the answer in the range [L, R] solve for the range from zero to R and then subtracting the answer for the range from zero to L – 1. Define the DP states as follows:" }, { "code": null, "e": 25514, "s": 25221, "text": "Consider the number as a sequence of digits, one state is the position at which we are currently at. This position can have values from 0 to 18 if we are dealing with the numbers up to 10^18. In each recursive call, try to build the sequence from left to right by placing a digit from 0 to 9." }, { "code": null, "e": 25585, "s": 25514, "text": "First state is the sum of the even digits that has been placed so far." }, { "code": null, "e": 25656, "s": 25585, "text": "Second state is the sum of the odd digits that has been placed so far." }, { "code": null, "e": 25977, "s": 25656, "text": "Another state is the boolean variable tight which tells the number we are trying to build has already become smaller than R so that in the upcoming recursive calls we can place any digit from 0 to 9. If the number has not become smaller, the maximum limit of digit we can place is the digit at the current position in R." }, { "code": null, "e": 26028, "s": 25977, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26032, "s": 26028, "text": "C++" }, { "code": null, "e": 26037, "s": 26032, "text": "Java" }, { "code": null, "e": 26045, "s": 26037, "text": "Python3" }, { "code": null, "e": 26048, "s": 26045, "text": "C#" }, { "code": "// C++ code to count number in the range// having the sum of even digits greater// than the sum of odd digits#include <bits/stdc++.h> // as the number can be up to 10^18#define int long long using namespace std; vector<int> v; int dp[18][180][180][2]; int memo(int index, int evenSum, int oddSum, int tight){ // Base Case if (index == v.size()) { // check if condition satisfied or not if (evenSum > oddSum) return 1; else return 0; } // If this result is already computed // simply return it if (dp[index][evenSum][oddSum][tight] != -1) return dp[index][evenSum][oddSum][tight]; // Maximum limit upto which we can place // digit. If tight is 0, means number has // already become smaller so we can place // any digit, otherwise num[pos] int limit = (tight) ? v[index] : 9; int ans = 0; for (int d = 0; d <= limit; d++) { int currTight = 0; if (d == v[index]) currTight = tight; // if current digit is odd if (d % 2 != 0) ans += memo(index + 1, evenSum, oddSum + d, currTight); // if current digit is even else ans += memo(index + 1, evenSum + d, oddSum, currTight); } dp[index][evenSum][oddSum][tight] = ans; return ans;}// Function to convert n into its// digit vector and uses memo() function// to return the required countint CountNum(int n){ v.clear(); while (n) { v.push_back(n % 10); n = n / 10; } reverse(v.begin(), v.end()); // Initialize DP memset(dp, -1, sizeof(dp)); return memo(0, 0, 0, 1);} // Driver Code int32_t main(){ int L, R; L = 2; R = 10; cout << CountNum(R) - CountNum(L - 1) << \"\\n\"; return 0;}", "e": 27888, "s": 26048, "text": null }, { "code": "// Java code to count number in the range// having the sum of even digits greater// than the sum of odd digitsimport java.util.*; class GFG{ static Vector<Integer> v = new Vector<>(); static int[][][][] dp = new int[18][180][180][2]; static int memo(int index, int evenSum, int oddSum, int tight) { // Base Case if (index == v.size()) { // check if condition satisfied or not if (evenSum > oddSum) { return 1; } else { return 0; } } // If this result is already computed // simply return it if (dp[index][evenSum][oddSum][tight] != -1) { return dp[index][evenSum][oddSum][tight]; } // Maximum limit upto which we can place // digit. If tight is 0, means number has // already become smaller so we can place // any digit, otherwise num[pos] int limit = (tight > 0) ? v.get(index) : 9; int ans = 0; for (int d = 0; d <= limit; d++) { int currTight = 0; if (d == v.get(index)) { currTight = tight; } // if current digit is odd if (d % 2 != 0) { ans += memo(index + 1, evenSum, oddSum + d, currTight); } // if current digit is even else { ans += memo(index + 1, evenSum + d, oddSum, currTight); } } dp[index][evenSum][oddSum][tight] = ans; return ans; } // Function to convert n into its // digit vector and uses memo() function // to return the required count static int CountNum(int n) { v.clear(); while (n > 0) { v.add(n % 10); n = n / 10; } Collections.reverse(v); // Initialize DP for (int i = 0; i < 18; i++) { for (int j = 0; j < 180; j++) { for (int k = 0; k < 180; k++) { for (int l = 0; l < 2; l++) { dp[i][j][k][l] = -1; } } } } return memo(0, 0, 0, 1); } // Driver Code public static void main(String[] args) { int L, R; L = 2; R = 10; System.out.println(CountNum(R) - CountNum(L - 1)); }} // This code is contributed by Princi Singh", "e": 30475, "s": 27888, "text": null }, { "code": "# Python code to count number in the range# having the sum of even digits greater# than the sum of odd digits def memo(index, evenSum, oddSum, tight): # Base Case if index == len(v): # check if condition satisfied or not if evenSum > oddSum: return 1 else: return 0 # If this result is already computed # simply return it if dp[index][evenSum][oddSum][tight] != -1: return dp[index][evenSum][oddSum][tight] # Maximum limit upto which we can place # digit. If tight is 0, means number has # already become smaller so we can place # any digit, otherwise num[index] limit = v[index] if tight else 9 ans = 0 for d in range(limit + 1): currTight = 0 if d == v[index]: currTight = tight # if current digit is odd if d % 2 != 0: ans += memo(index + 1, evenSum, oddSum + d, currTight) # if current digit is even else: ans += memo(index + 1, evenSum + d, oddSum, currTight) dp[index][evenSum][oddSum][tight] = ans return ans # Function to convert n into its digit vector# and uses memo() function to return the# required countdef countNum(n): global dp, v v.clear() num = [] while n: v.append(n % 10) n //= 10 v.reverse() # Initialize dp dp = [[[[-1, -1] for i in range(180)] for j in range(180)] for k in range(18)] return memo(0, 0, 0, 1) # Driver Codeif __name__ == \"__main__\": dp = [] v = [] L = 2 R = 10 print(countNum(R) - countNum(L - 1)) # This code is contributed by# sanjeev2552", "e": 32166, "s": 30475, "text": null }, { "code": "// C# code to count number in the range// having the sum of even digits greater// than the sum of odd digitsusing System.Collections.Generic;using System; class GFG{ static List<int> v = new List<int>(); static int [,,,]dp = new int[18,180,180,2]; static int memo(int index, int evenSum, int oddSum, int tight) { // Base Case if (index == v.Count) { // check if condition satisfied or not if (evenSum > oddSum) { return 1; } else { return 0; } } // If this result is already computed // simply return it if (dp[index,evenSum,oddSum,tight] != -1) { return dp[index,evenSum,oddSum,tight]; } // Maximum limit upto which we can place // digit. If tight is 0, means number has // already become smaller so we can place // any digit, otherwise num[pos] int limit = (tight > 0) ? v[index] : 9; int ans = 0; for (int d = 0; d <= limit; d++) { int currTight = 0; if (d == v[index]) { currTight = tight; } // if current digit is odd if (d % 2 != 0) { ans += memo(index + 1, evenSum, oddSum + d, currTight); } // if current digit is even else { ans += memo(index + 1, evenSum + d, oddSum, currTight); } } dp[index,evenSum,oddSum,tight] = ans; return ans; } // Function to convert n into its // digit vector and uses memo() function // to return the required count static int CountNum(int n) { v.Clear(); while (n > 0) { v.Add(n % 10); n = n / 10; } v.Reverse(); // Initialize DP for (int i = 0; i < 18; i++) { for (int j = 0; j < 180; j++) { for (int k = 0; k < 180; k++) { for (int l = 0; l < 2; l++) { dp[i,j,k,l] = -1; } } } } return memo(0, 0, 0, 1); } // Driver Code public static void Main(String[] args) { int L, R; L = 2; R = 10; Console.WriteLine(CountNum(R) - CountNum(L - 1)); }} /* This code is contributed by PrinciRaj1992 */", "e": 34742, "s": 32166, "text": null }, { "code": null, "e": 34745, "s": 34742, "text": "4\n" }, { "code": null, "e": 34835, "s": 34745, "text": "Time Complexity : There would be at max 18*(180)*(180)*2 computations when 0 < a,b < 1018" }, { "code": null, "e": 34848, "s": 34835, "text": "princi singh" }, { "code": null, "e": 34862, "s": 34848, "text": "princiraj1992" }, { "code": null, "e": 34874, "s": 34862, "text": "sanjeev2552" }, { "code": null, "e": 34883, "s": 34874, "text": "digit-DP" }, { "code": null, "e": 34891, "s": 34883, "text": "Numbers" }, { "code": null, "e": 34911, "s": 34891, "text": "Dynamic Programming" }, { "code": null, "e": 34924, "s": 34911, "text": "Mathematical" }, { "code": null, "e": 34944, "s": 34924, "text": "Dynamic Programming" }, { "code": null, "e": 34957, "s": 34944, "text": "Mathematical" }, { "code": null, "e": 34965, "s": 34957, "text": "Numbers" }, { "code": null, "e": 35063, "s": 34965, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35072, "s": 35063, "text": "Comments" }, { "code": null, "e": 35085, "s": 35072, "text": "Old Comments" }, { "code": null, "e": 35145, "s": 35085, "text": "Optimal Substructure Property in Dynamic Programming | DP-2" }, { "code": null, "e": 35166, "s": 35145, "text": "Min Cost Path | DP-6" }, { "code": null, "e": 35222, "s": 35166, "text": "Maximum Subarray Sum using Divide and Conquer algorithm" }, { "code": null, "e": 35257, "s": 35222, "text": "Optimal Binary Search Tree | DP-24" }, { "code": null, "e": 35296, "s": 35257, "text": "Greedy approach vs Dynamic programming" }, { "code": null, "e": 35356, "s": 35296, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 35371, "s": 35356, "text": "C++ Data Types" }, { "code": null, "e": 35414, "s": 35371, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 35463, "s": 35414, "text": "Program to find sum of elements in a given array" } ]
Maximum number of edges among all connected components of an undirected graph - GeeksforGeeks
12 Jul, 2021 Given integers ‘N’ and ‘K’ where, N is the number of vertices of an undirected graph and ‘K’ denotes the number of edges in the same graph (each edge is denoted by a pair of integers where i, j means that the vertex ‘i’ is directly connected to the vertex ‘j’ in the graph).The task is to find the maximum number of edges among all the connected components in the given graph.Examples: Input: N = 6, K = 4, Edges = {{1, 2}, {2, 3}, {3, 1}, {4, 5}} Output: 3 Here, graph has 3 components 1st component 1-2-3-1 : 3 edges 2nd component 4-5 : 1 edges 3rd component 6 : 0 edges max(3, 1, 0) = 3 edgesInput: N = 3, K = 2, Edges = {{1, 2}, {2, 3}} Output: 2 Approach: Using Depth First Search, find the sum of the degrees of each of the edges in all the connected components separately. Now, according to Handshaking Lemma, the total number of edges in a connected component of an undirected graph is equal to half of the total sum of the degrees of all of its vertices. Print the maximum number of edges among all the connected components. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to find the connected component// with maximum number of edges#include <bits/stdc++.h>using namespace std; // DFS functionint dfs(int s, vector<int> adj[], vector<bool> visited, int nodes){ // Adding all the edges connected to the vertex int adjListSize = adj[s].size(); visited[s] = true; for (long int i = 0; i < adj[s].size(); i++) { if (visited[adj[s][i]] == false) { adjListSize += dfs(adj[s][i], adj, visited, nodes); } } return adjListSize;} int maxEdges(vector<int> adj[], int nodes){ int res = INT_MIN; vector<bool> visited(nodes, false); for (long int i = 1; i <= nodes; i++) { if (visited[i] == false) { int adjListSize = dfs(i, adj, visited, nodes); res = max(res, adjListSize/2); } } return res;} // Driver codeint main(){ int nodes = 3; vector<int> adj[nodes+1]; // Edge from vertex 1 to vertex 2 adj[1].push_back(2); adj[2].push_back(1); // Edge from vertex 2 to vertex 3 adj[2].push_back(3); adj[3].push_back(2); cout << maxEdges(adj, nodes); return 0;} // Java program to find the connected component// with maximum number of edgesimport java.util.*; class GFG{ // DFS functionstatic int dfs(int s, Vector<Vector<Integer>> adj,boolean visited[], int nodes){ // Adding all the edges connected to the vertex int adjListSize = adj.get(s).size(); visited[s] = true; for (int i = 0; i < adj.get(s).size(); i++) { if (visited[adj.get(s).get(i)] == false) { adjListSize += dfs(adj.get(s).get(i), adj, visited, nodes); } } return adjListSize;} static int maxEdges(Vector<Vector<Integer>> adj, int nodes){ int res = Integer.MIN_VALUE; boolean visited[]=new boolean[nodes+1]; for (int i = 1; i <= nodes; i++) { if (visited[i] == false) { int adjListSize = dfs(i, adj, visited, nodes); res = Math.max(res, adjListSize/2); } } return res;} // Driver codepublic static void main(String args[]){ int nodes = 3; Vector<Vector<Integer>> adj=new Vector<Vector<Integer>>(); for(int i = 0; i < nodes + 1; i++) adj.add(new Vector<Integer>()); // Edge from vertex 1 to vertex 2 adj.get(1).add(2); adj.get(2).add(1); // Edge from vertex 2 to vertex 3 adj.get(2).add(3); adj.get(3).add(2); System.out.println(maxEdges(adj, nodes));}} // This code is contributed by Arnab Kundu # Python3 program to find the connected# component with maximum number of edgesfrom sys import maxsize INT_MIN = -maxsize # DFS functiondef dfs(s: int, adj: list, visited: list, nodes: int) -> int: # Adding all the edges # connected to the vertex adjListSize = len(adj[s]) visited[s] = True for i in range(len(adj[s])): if visited[adj[s][i]] == False: adjListSize += dfs(adj[s][i], adj, visited, nodes) return adjListSize def maxEdges(adj: list, nodes: int) -> int: res = INT_MIN visited = [False] * (nodes + 1) for i in range(1, nodes + 1): if visited[i] == False: adjListSize = dfs(i, adj, visited, nodes) res = max(res, adjListSize // 2) return res # Driver Codeif __name__ == "__main__": nodes = 3 adj = [0] * (nodes + 1) for i in range(nodes + 1): adj[i] = [] # Edge from vertex 1 to vertex 2 adj[1].append(2) adj[2].append(1) # Edge from vertex 2 to vertex 3 adj[2].append(3) adj[3].append(2) print(maxEdges(adj, nodes)) # This code is contributed by sanjeev2552 // C# program to find the connected component// with maximum number of edgesusing System;using System.Collections.Generic; class GFG{ // DFS functionstatic int dfs(int s, List<List<int>> adj, bool []visited, int nodes){ // Adding all the edges connected to the vertex int adjListSize = adj[s].Count; visited[s] = true; for (int i = 0; i < adj[s].Count; i++) { if (visited[adj[s][i]] == false) { adjListSize += dfs(adj[s][i], adj, visited, nodes); } } return adjListSize;} static int maxEdges(List<List<int>> adj, int nodes){ int res = int.MinValue; bool []visited = new bool[nodes + 1]; for (int i = 1; i <= nodes; i++) { if (visited[i] == false) { int adjListSize = dfs(i, adj, visited, nodes); res = Math.Max(res, adjListSize / 2); } } return res;} // Driver codepublic static void Main(String []args){ int nodes = 3; List<List<int>> adj = new List<List<int>>(); for(int i = 0; i < nodes + 1; i++) adj.Add(new List<int>()); // Edge from vertex 1 to vertex 2 adj[1].Add(2); adj[2].Add(1); // Edge from vertex 2 to vertex 3 adj[2].Add(3); adj[3].Add(2); Console.WriteLine(maxEdges(adj, nodes));}} // This code is contributed by PrinciRaj1992 <script> // JavaScript program to find the connected component// with maximum number of edges // DFS functionfunction dfs(s,adj,visited,nodes){ // Adding all the edges connected to the vertex let adjListSize = adj[s].length; visited[s] = true; for (let i = 0; i < adj[s].length; i++) { if (visited[adj[s][i]] == false) { adjListSize += dfs(adj[s][i], adj, visited, nodes); } } return adjListSize;} function maxEdges(adj,nodes){ let res = Number.MIN_VALUE; let visited=new Array(nodes+1); for(let i=0;i<nodes+1;i++) { visited[i]=false; } for (let i = 1; i <= nodes; i++) { if (visited[i] == false) { let adjListSize = dfs(i, adj, visited, nodes); res = Math.max(res, adjListSize/2); } } return res;} // Driver codelet nodes = 3;let adj=[]; for(let i = 0; i < nodes + 1; i++) adj.push([]); // Edge from vertex 1 to vertex 2adj[1].push(2);adj[2].push(1); // Edge from vertex 2 to vertex 3adj[2].push(3);adj[3].push(2); document.write(maxEdges(adj, nodes)+"<br>"); // This code is contributed by avanitrachhadiya2155 </script> 2 Time Complexity : O(nodes + edges) (Same as DFS)Note : We can also use BFS to solve this problem. We simply need to traverse connected components in an undirected graph. Palash Sethi andrew1234 princiraj1992 sanjeev2552 avanitrachhadiya2155 DFS graph-connectivity Technical Scripter 2018 Graph Technical Scripter DFS Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Topological Sorting Detect Cycle in a Directed Graph Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph) Detect cycle in an undirected graph Ford-Fulkerson Algorithm for Maximum Flow Problem Traveling Salesman Problem (TSP) Implementation Check whether a given graph is Bipartite or not Shortest path in an unweighted graph Iterative Depth First Traversal of Graph
[ { "code": null, "e": 24725, "s": 24697, "text": "\n12 Jul, 2021" }, { "code": null, "e": 25113, "s": 24725, "text": "Given integers ‘N’ and ‘K’ where, N is the number of vertices of an undirected graph and ‘K’ denotes the number of edges in the same graph (each edge is denoted by a pair of integers where i, j means that the vertex ‘i’ is directly connected to the vertex ‘j’ in the graph).The task is to find the maximum number of edges among all the connected components in the given graph.Examples: " }, { "code": null, "e": 25380, "s": 25113, "text": "Input: N = 6, K = 4, Edges = {{1, 2}, {2, 3}, {3, 1}, {4, 5}} Output: 3 Here, graph has 3 components 1st component 1-2-3-1 : 3 edges 2nd component 4-5 : 1 edges 3rd component 6 : 0 edges max(3, 1, 0) = 3 edgesInput: N = 3, K = 2, Edges = {{1, 2}, {2, 3}} Output: 2 " }, { "code": null, "e": 25394, "s": 25382, "text": "Approach: " }, { "code": null, "e": 25513, "s": 25394, "text": "Using Depth First Search, find the sum of the degrees of each of the edges in all the connected components separately." }, { "code": null, "e": 25697, "s": 25513, "text": "Now, according to Handshaking Lemma, the total number of edges in a connected component of an undirected graph is equal to half of the total sum of the degrees of all of its vertices." }, { "code": null, "e": 25767, "s": 25697, "text": "Print the maximum number of edges among all the connected components." }, { "code": null, "e": 25820, "s": 25767, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25824, "s": 25820, "text": "C++" }, { "code": null, "e": 25829, "s": 25824, "text": "Java" }, { "code": null, "e": 25837, "s": 25829, "text": "Python3" }, { "code": null, "e": 25840, "s": 25837, "text": "C#" }, { "code": null, "e": 25851, "s": 25840, "text": "Javascript" }, { "code": "// C++ program to find the connected component// with maximum number of edges#include <bits/stdc++.h>using namespace std; // DFS functionint dfs(int s, vector<int> adj[], vector<bool> visited, int nodes){ // Adding all the edges connected to the vertex int adjListSize = adj[s].size(); visited[s] = true; for (long int i = 0; i < adj[s].size(); i++) { if (visited[adj[s][i]] == false) { adjListSize += dfs(adj[s][i], adj, visited, nodes); } } return adjListSize;} int maxEdges(vector<int> adj[], int nodes){ int res = INT_MIN; vector<bool> visited(nodes, false); for (long int i = 1; i <= nodes; i++) { if (visited[i] == false) { int adjListSize = dfs(i, adj, visited, nodes); res = max(res, adjListSize/2); } } return res;} // Driver codeint main(){ int nodes = 3; vector<int> adj[nodes+1]; // Edge from vertex 1 to vertex 2 adj[1].push_back(2); adj[2].push_back(1); // Edge from vertex 2 to vertex 3 adj[2].push_back(3); adj[3].push_back(2); cout << maxEdges(adj, nodes); return 0;}", "e": 27013, "s": 25851, "text": null }, { "code": "// Java program to find the connected component// with maximum number of edgesimport java.util.*; class GFG{ // DFS functionstatic int dfs(int s, Vector<Vector<Integer>> adj,boolean visited[], int nodes){ // Adding all the edges connected to the vertex int adjListSize = adj.get(s).size(); visited[s] = true; for (int i = 0; i < adj.get(s).size(); i++) { if (visited[adj.get(s).get(i)] == false) { adjListSize += dfs(adj.get(s).get(i), adj, visited, nodes); } } return adjListSize;} static int maxEdges(Vector<Vector<Integer>> adj, int nodes){ int res = Integer.MIN_VALUE; boolean visited[]=new boolean[nodes+1]; for (int i = 1; i <= nodes; i++) { if (visited[i] == false) { int adjListSize = dfs(i, adj, visited, nodes); res = Math.max(res, adjListSize/2); } } return res;} // Driver codepublic static void main(String args[]){ int nodes = 3; Vector<Vector<Integer>> adj=new Vector<Vector<Integer>>(); for(int i = 0; i < nodes + 1; i++) adj.add(new Vector<Integer>()); // Edge from vertex 1 to vertex 2 adj.get(1).add(2); adj.get(2).add(1); // Edge from vertex 2 to vertex 3 adj.get(2).add(3); adj.get(3).add(2); System.out.println(maxEdges(adj, nodes));}} // This code is contributed by Arnab Kundu", "e": 28401, "s": 27013, "text": null }, { "code": "# Python3 program to find the connected# component with maximum number of edgesfrom sys import maxsize INT_MIN = -maxsize # DFS functiondef dfs(s: int, adj: list, visited: list, nodes: int) -> int: # Adding all the edges # connected to the vertex adjListSize = len(adj[s]) visited[s] = True for i in range(len(adj[s])): if visited[adj[s][i]] == False: adjListSize += dfs(adj[s][i], adj, visited, nodes) return adjListSize def maxEdges(adj: list, nodes: int) -> int: res = INT_MIN visited = [False] * (nodes + 1) for i in range(1, nodes + 1): if visited[i] == False: adjListSize = dfs(i, adj, visited, nodes) res = max(res, adjListSize // 2) return res # Driver Codeif __name__ == \"__main__\": nodes = 3 adj = [0] * (nodes + 1) for i in range(nodes + 1): adj[i] = [] # Edge from vertex 1 to vertex 2 adj[1].append(2) adj[2].append(1) # Edge from vertex 2 to vertex 3 adj[2].append(3) adj[3].append(2) print(maxEdges(adj, nodes)) # This code is contributed by sanjeev2552", "e": 29625, "s": 28401, "text": null }, { "code": "// C# program to find the connected component// with maximum number of edgesusing System;using System.Collections.Generic; class GFG{ // DFS functionstatic int dfs(int s, List<List<int>> adj, bool []visited, int nodes){ // Adding all the edges connected to the vertex int adjListSize = adj[s].Count; visited[s] = true; for (int i = 0; i < adj[s].Count; i++) { if (visited[adj[s][i]] == false) { adjListSize += dfs(adj[s][i], adj, visited, nodes); } } return adjListSize;} static int maxEdges(List<List<int>> adj, int nodes){ int res = int.MinValue; bool []visited = new bool[nodes + 1]; for (int i = 1; i <= nodes; i++) { if (visited[i] == false) { int adjListSize = dfs(i, adj, visited, nodes); res = Math.Max(res, adjListSize / 2); } } return res;} // Driver codepublic static void Main(String []args){ int nodes = 3; List<List<int>> adj = new List<List<int>>(); for(int i = 0; i < nodes + 1; i++) adj.Add(new List<int>()); // Edge from vertex 1 to vertex 2 adj[1].Add(2); adj[2].Add(1); // Edge from vertex 2 to vertex 3 adj[2].Add(3); adj[3].Add(2); Console.WriteLine(maxEdges(adj, nodes));}} // This code is contributed by PrinciRaj1992", "e": 30986, "s": 29625, "text": null }, { "code": "<script> // JavaScript program to find the connected component// with maximum number of edges // DFS functionfunction dfs(s,adj,visited,nodes){ // Adding all the edges connected to the vertex let adjListSize = adj[s].length; visited[s] = true; for (let i = 0; i < adj[s].length; i++) { if (visited[adj[s][i]] == false) { adjListSize += dfs(adj[s][i], adj, visited, nodes); } } return adjListSize;} function maxEdges(adj,nodes){ let res = Number.MIN_VALUE; let visited=new Array(nodes+1); for(let i=0;i<nodes+1;i++) { visited[i]=false; } for (let i = 1; i <= nodes; i++) { if (visited[i] == false) { let adjListSize = dfs(i, adj, visited, nodes); res = Math.max(res, adjListSize/2); } } return res;} // Driver codelet nodes = 3;let adj=[]; for(let i = 0; i < nodes + 1; i++) adj.push([]); // Edge from vertex 1 to vertex 2adj[1].push(2);adj[2].push(1); // Edge from vertex 2 to vertex 3adj[2].push(3);adj[3].push(2); document.write(maxEdges(adj, nodes)+\"<br>\"); // This code is contributed by avanitrachhadiya2155 </script>", "e": 32144, "s": 30986, "text": null }, { "code": null, "e": 32146, "s": 32144, "text": "2" }, { "code": null, "e": 32319, "s": 32148, "text": "Time Complexity : O(nodes + edges) (Same as DFS)Note : We can also use BFS to solve this problem. We simply need to traverse connected components in an undirected graph. " }, { "code": null, "e": 32332, "s": 32319, "text": "Palash Sethi" }, { "code": null, "e": 32343, "s": 32332, "text": "andrew1234" }, { "code": null, "e": 32357, "s": 32343, "text": "princiraj1992" }, { "code": null, "e": 32369, "s": 32357, "text": "sanjeev2552" }, { "code": null, "e": 32390, "s": 32369, "text": "avanitrachhadiya2155" }, { "code": null, "e": 32394, "s": 32390, "text": "DFS" }, { "code": null, "e": 32413, "s": 32394, "text": "graph-connectivity" }, { "code": null, "e": 32437, "s": 32413, "text": "Technical Scripter 2018" }, { "code": null, "e": 32443, "s": 32437, "text": "Graph" }, { "code": null, "e": 32462, "s": 32443, "text": "Technical Scripter" }, { "code": null, "e": 32466, "s": 32462, "text": "DFS" }, { "code": null, "e": 32472, "s": 32466, "text": "Graph" }, { "code": null, "e": 32570, "s": 32472, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32579, "s": 32570, "text": "Comments" }, { "code": null, "e": 32592, "s": 32579, "text": "Old Comments" }, { "code": null, "e": 32612, "s": 32592, "text": "Topological Sorting" }, { "code": null, "e": 32645, "s": 32612, "text": "Detect Cycle in a Directed Graph" }, { "code": null, "e": 32713, "s": 32645, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 32788, "s": 32713, "text": "Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)" }, { "code": null, "e": 32824, "s": 32788, "text": "Detect cycle in an undirected graph" }, { "code": null, "e": 32874, "s": 32824, "text": "Ford-Fulkerson Algorithm for Maximum Flow Problem" }, { "code": null, "e": 32922, "s": 32874, "text": "Traveling Salesman Problem (TSP) Implementation" }, { "code": null, "e": 32970, "s": 32922, "text": "Check whether a given graph is Bipartite or not" }, { "code": null, "e": 33007, "s": 32970, "text": "Shortest path in an unweighted graph" } ]
Change the string | Practice | GeeksforGeeks
Given a string S, the task is to change the complete string to Uppercase or Lowercase depending upon the case for the first character. Example 1: Input: S = "abCD" Output: abcd Explanation: The first letter (a) is lowercase. Hence, the complete string is made lowercase. ​Example 2: Input: S = "Abcd" Output: ABCD Explanation: The first letter (A) is uppercase. Hence, the complete string is made uppercase. Your Task: You don't need to read input or print anything. Your task is to complete the function modify() which takes the string S as input and returns the resultant string with stated modifications. Expected Time Complexity: O(|S|). Expected Auxiliary Space: O(1) for C++ and O(|S|) for output in Java/Python. Constraints: 1<=|S|<=104 0 akash22bhin 6 hours Total time taken-0.01/1.04 string modify (string s) { // your code here if(s[0]>='a'&&s[0]<='z') { for(int i=1;i<s.length();i++) { if(s[i]>='A'&&s[i]<='Z') s[i]+=32; } } if(s[0]>='A'&&s[0]<='Z') { for(int i=1;i<s.length();i++) { if(s[i]>='a'&&s[i]<='z') s[i]-=32; } } return s; } 0 gurankitbehal781141 week ago class Solution{ public: string modify (string s) { if(s[0]>='A' && s[0]<='Z'){ for(int i=0;i<s.length();i++){ s[i]=toupper(s[i]); } } if(s[0]>='a' && s[0]<='z'){ for(int i=0;i<s.length();i++){ s[i]=tolower(s[i]); } } return s; }}; 0 mayank180919991 week ago string modify (string s) { // your code here string v; if(islower(s[0])){ for(int i=0;i<s.length();i++){ v.push_back(tolower(s[i])); } }else{ for(int i=0;i<s.length();i++){ v.push_back(toupper(s[i])); } } return v; } 0 vermahariom10002 months ago class Solution{ String modify(String s) { if(s.charAt(0)>='a' && s.charAt(0)<='z') return s.toLowerCase(); else return s.toUpperCase(); }} 0 chhitizgoyal2 months ago Java Solution. class Solution{ String modify(String s){ if(s.charAt(0)>=65 && s.charAt(0)<=90){ return s.toUpperCase(); } return s.toLowerCase(); }} 0 1ashishchauhan20022 months ago string modify (string s) { if(s[0]>=65 && s[0]<=90){ transform(s.begin(), s.end(), s.begin(), ::toupper); } if(s[0]>=97 && s[0]<=122){ transform(s.begin(), s.end(), s.begin(), ::tolower); } return s; } +1 shubhamkhavare2 months ago class Solution{ String modify(String s){ if (Character.isUpperCase(s.charAt(0))) { return s.toUpperCase(); } return s.toLowerCase(); }} +1 sdmrf2 months ago Python : class Solution: def modify(self, s): if s[0].isupper()==True: return s.upper() else: return s.lower() 0 yash7raut2 months ago class Solution: def modify(self, s): # code here x = s[0].isupper() if(x == True): s = s.upper() else: s = s.lower() return(s) +1 as0042303 months ago In C++; string modify (string s) { string str = ""; for(int i = 0; i < s.size(); i++) { if(islower(s[0])) str += tolower(s[i]); else str += toupper(s[i]); } return str; } 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": 373, "s": 238, "text": "Given a string S, the task is to change the complete string to Uppercase or Lowercase depending upon the case for the first character." }, { "code": null, "e": 384, "s": 373, "text": "Example 1:" }, { "code": null, "e": 512, "s": 384, "text": "Input:\nS = \"abCD\"\nOutput: abcd\nExplanation: The first letter (a) is \nlowercase. Hence, the complete string\nis made lowercase.\n\n" }, { "code": null, "e": 527, "s": 512, "text": "​Example 2:" }, { "code": null, "e": 653, "s": 527, "text": "Input: \nS = \"Abcd\"\nOutput: ABCD\nExplanation: The first letter (A) is\nuppercase. Hence, the complete string\nis made uppercase." }, { "code": null, "e": 854, "s": 653, "text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function modify() which takes the string S as input and returns the resultant string with stated modifications." }, { "code": null, "e": 966, "s": 854, "text": "\nExpected Time Complexity: O(|S|).\nExpected Auxiliary Space: O(1) for C++ and O(|S|) for output in Java/Python." }, { "code": null, "e": 992, "s": 966, "text": "\nConstraints:\n1<=|S|<=104" }, { "code": null, "e": 996, "s": 994, "text": "0" }, { "code": null, "e": 1016, "s": 996, "text": "akash22bhin 6 hours" }, { "code": null, "e": 1043, "s": 1016, "text": "Total time taken-0.01/1.04" }, { "code": null, "e": 1464, "s": 1043, "text": "string modify (string s) { // your code here if(s[0]>='a'&&s[0]<='z') { for(int i=1;i<s.length();i++) { if(s[i]>='A'&&s[i]<='Z') s[i]+=32; } } if(s[0]>='A'&&s[0]<='Z') { for(int i=1;i<s.length();i++) { if(s[i]>='a'&&s[i]<='z') s[i]-=32; } } return s; }" }, { "code": null, "e": 1466, "s": 1464, "text": "0" }, { "code": null, "e": 1495, "s": 1466, "text": "gurankitbehal781141 week ago" }, { "code": null, "e": 1831, "s": 1495, "text": "class Solution{ public: string modify (string s) { if(s[0]>='A' && s[0]<='Z'){ for(int i=0;i<s.length();i++){ s[i]=toupper(s[i]); } } if(s[0]>='a' && s[0]<='z'){ for(int i=0;i<s.length();i++){ s[i]=tolower(s[i]); } } return s; }};" }, { "code": null, "e": 1833, "s": 1831, "text": "0" }, { "code": null, "e": 1858, "s": 1833, "text": "mayank180919991 week ago" }, { "code": null, "e": 2246, "s": 1858, "text": " string modify (string s)\n {\n // your code here\n string v;\n if(islower(s[0])){\n for(int i=0;i<s.length();i++){\n v.push_back(tolower(s[i]));\n } \n }else{\n for(int i=0;i<s.length();i++){\n v.push_back(toupper(s[i]));\n } \n }\n return v;\n }" }, { "code": null, "e": 2248, "s": 2246, "text": "0" }, { "code": null, "e": 2276, "s": 2248, "text": "vermahariom10002 months ago" }, { "code": null, "e": 2459, "s": 2276, "text": "class Solution{ String modify(String s) { if(s.charAt(0)>='a' && s.charAt(0)<='z') return s.toLowerCase(); else return s.toUpperCase(); }}" }, { "code": null, "e": 2461, "s": 2459, "text": "0" }, { "code": null, "e": 2486, "s": 2461, "text": "chhitizgoyal2 months ago" }, { "code": null, "e": 2502, "s": 2486, "text": "Java Solution. " }, { "code": null, "e": 2672, "s": 2502, "text": "class Solution{ String modify(String s){ if(s.charAt(0)>=65 && s.charAt(0)<=90){ return s.toUpperCase(); } return s.toLowerCase(); }}" }, { "code": null, "e": 2674, "s": 2672, "text": "0" }, { "code": null, "e": 2705, "s": 2674, "text": "1ashishchauhan20022 months ago" }, { "code": null, "e": 2949, "s": 2705, "text": " string modify (string s) { if(s[0]>=65 && s[0]<=90){ transform(s.begin(), s.end(), s.begin(), ::toupper); } if(s[0]>=97 && s[0]<=122){ transform(s.begin(), s.end(), s.begin(), ::tolower); } return s; }" }, { "code": null, "e": 2954, "s": 2951, "text": "+1" }, { "code": null, "e": 2981, "s": 2954, "text": "shubhamkhavare2 months ago" }, { "code": null, "e": 3155, "s": 2981, "text": "class Solution{ String modify(String s){ if (Character.isUpperCase(s.charAt(0))) { return s.toUpperCase(); } return s.toLowerCase(); }}" }, { "code": null, "e": 3158, "s": 3155, "text": "+1" }, { "code": null, "e": 3176, "s": 3158, "text": "sdmrf2 months ago" }, { "code": null, "e": 3185, "s": 3176, "text": "Python :" }, { "code": null, "e": 3321, "s": 3185, "text": "class Solution: def modify(self, s): if s[0].isupper()==True: return s.upper() else: return s.lower()" }, { "code": null, "e": 3323, "s": 3321, "text": "0" }, { "code": null, "e": 3345, "s": 3323, "text": "yash7raut2 months ago" }, { "code": null, "e": 3534, "s": 3345, "text": "class Solution: def modify(self, s): # code here x = s[0].isupper() if(x == True): s = s.upper() else: s = s.lower() return(s) " }, { "code": null, "e": 3537, "s": 3534, "text": "+1" }, { "code": null, "e": 3558, "s": 3537, "text": "as0042303 months ago" }, { "code": null, "e": 3566, "s": 3558, "text": "In C++;" }, { "code": null, "e": 3813, "s": 3566, "text": " string modify (string s) { string str = \"\"; for(int i = 0; i < s.size(); i++) { if(islower(s[0])) str += tolower(s[i]); else str += toupper(s[i]); } return str; }" }, { "code": null, "e": 3959, "s": 3813, "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": 3995, "s": 3959, "text": " Login to access your submissions. " }, { "code": null, "e": 4005, "s": 3995, "text": "\nProblem\n" }, { "code": null, "e": 4015, "s": 4005, "text": "\nContest\n" }, { "code": null, "e": 4078, "s": 4015, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4226, "s": 4078, "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": 4434, "s": 4226, "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": 4540, "s": 4434, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
CSS | border-image-source Property - GeeksforGeeks
03 Nov, 2021 The border-image-source property is used to specify the image source which is to be set as the border of an element. Syntax: border-image-source: url(image-path.png)| none| initial| inherit; Note: If the value is none, the border styles will be used. The specified image can be divided into regions with the help of border-image-slice property. Default Value : Its default value is none.Values: none: No image is specified. image: Used to specify the path of the image to be used as the border of an element. initial: Initializes the property with it’s default value. inherit: It takes the value from the parent element. Example: HTML <!DOCTYPE html> <html> <head> <title> CSS | border-image-source Property </title> <style> body { text-align:center; color:green; } .border1 { border: 10px solid transparent; padding: 15px; border-image-source: url( https://media.geeksforgeeks.org/wp-content/uploads/border1-2.png); border-image-repeat: round; border-image-slice: 50; border-image-width: 20px; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>border-image-source property</h2> <div class = "border1">GEEKSFORGEEKS</div> </body></html> Output: Supported Browsers: The browsers supported by CSS | border-image-source Property are listed below: Chrome 15.0 Edge 11.0 Firefox 15.0 Opera 15.0 Safari 6.0 ManasChhabra2 CSS-Properties Picked CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? Types of CSS (Cascading Style Sheet) How to create footer to stay at the bottom of a Web page? How to update Node.js and NPM to next version ? Express.js express.Router() Function Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 23377, "s": 23349, "text": "\n03 Nov, 2021" }, { "code": null, "e": 23496, "s": 23377, "text": "The border-image-source property is used to specify the image source which is to be set as the border of an element. " }, { "code": null, "e": 23506, "s": 23496, "text": "Syntax: " }, { "code": null, "e": 23572, "s": 23506, "text": "border-image-source: url(image-path.png)| none| initial| inherit;" }, { "code": null, "e": 23729, "s": 23572, "text": " Note: If the value is none, the border styles will be used. The specified image can be divided into regions with the help of border-image-slice property. " }, { "code": null, "e": 23780, "s": 23729, "text": "Default Value : Its default value is none.Values: " }, { "code": null, "e": 23809, "s": 23780, "text": "none: No image is specified." }, { "code": null, "e": 23894, "s": 23809, "text": "image: Used to specify the path of the image to be used as the border of an element." }, { "code": null, "e": 23953, "s": 23894, "text": "initial: Initializes the property with it’s default value." }, { "code": null, "e": 24006, "s": 23953, "text": "inherit: It takes the value from the parent element." }, { "code": null, "e": 24017, "s": 24006, "text": "Example: " }, { "code": null, "e": 24022, "s": 24017, "text": "HTML" }, { "code": "<!DOCTYPE html> <html> <head> <title> CSS | border-image-source Property </title> <style> body { text-align:center; color:green; } .border1 { border: 10px solid transparent; padding: 15px; border-image-source: url( https://media.geeksforgeeks.org/wp-content/uploads/border1-2.png); border-image-repeat: round; border-image-slice: 50; border-image-width: 20px; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>border-image-source property</h2> <div class = \"border1\">GEEKSFORGEEKS</div> </body></html> ", "e": 24814, "s": 24022, "text": null }, { "code": null, "e": 24824, "s": 24814, "text": "Output: " }, { "code": null, "e": 24925, "s": 24824, "text": "Supported Browsers: The browsers supported by CSS | border-image-source Property are listed below: " }, { "code": null, "e": 24937, "s": 24925, "text": "Chrome 15.0" }, { "code": null, "e": 24947, "s": 24937, "text": "Edge 11.0" }, { "code": null, "e": 24960, "s": 24947, "text": "Firefox 15.0" }, { "code": null, "e": 24971, "s": 24960, "text": "Opera 15.0" }, { "code": null, "e": 24982, "s": 24971, "text": "Safari 6.0" }, { "code": null, "e": 24998, "s": 24984, "text": "ManasChhabra2" }, { "code": null, "e": 25013, "s": 24998, "text": "CSS-Properties" }, { "code": null, "e": 25020, "s": 25013, "text": "Picked" }, { "code": null, "e": 25024, "s": 25020, "text": "CSS" }, { "code": null, "e": 25041, "s": 25024, "text": "Web Technologies" }, { "code": null, "e": 25139, "s": 25041, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25148, "s": 25139, "text": "Comments" }, { "code": null, "e": 25161, "s": 25148, "text": "Old Comments" }, { "code": null, "e": 25223, "s": 25161, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 25273, "s": 25223, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 25310, "s": 25273, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 25368, "s": 25310, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 25416, "s": 25368, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 25453, "s": 25416, "text": "Express.js express.Router() Function" }, { "code": null, "e": 25486, "s": 25453, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 25548, "s": 25486, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 25591, "s": 25548, "text": "How to fetch data from an API in ReactJS ?" } ]
How to get Subtraction of tuples in Python
When it is required to subtract the tuples, the 'map' method and lambda function can be used. The map function applies a given function/operation to every item in an iterable (such as list, tuple). It returns a list as the result. Anonymous function is a function which is defined without a name. In general, functions in Python are defined using 'def' keyword, but anonymous function is defined with the help of 'lambda' keyword. It takes a single expression, but can take any number of arguments. It uses the expression and returns the result of it. Below is a demonstration of the same − Live Demo my_tuple_1 = (7, 8, 11, 0 ,3, 4) my_tuple_2 = (3, 2, 22, 45, 12, 9) print ("The first tuple is : " ) print(my_tuple_1) print ("The second tuple is : " ) print(my_tuple_2) my_result = tuple(map(lambda i, j: i - j, my_tuple_1, my_tuple_2)) print("The tuple after subtraction is : " ) print(my_result) The first tuple is : (7, 8, 11, 0, 3, 4) The second tuple is : (3, 2, 22, 45, 12, 9) The tuple after subtraction is : (4, 6, -11, -45, -9, -5) Two tuples are defined, and are displayed on the console. The lambda function is used to subtract each of the corresponding elements from the two tuples. This operation is mapped to all elements using the 'map' method. This result is converted into a tuple. This result is assigned to a value. It is displayed as output on the console.
[ { "code": null, "e": 1156, "s": 1062, "text": "When it is required to subtract the tuples, the 'map' method and lambda function can be used." }, { "code": null, "e": 1293, "s": 1156, "text": "The map function applies a given function/operation to every item in an iterable (such as list, tuple). It returns a list as the result." }, { "code": null, "e": 1614, "s": 1293, "text": "Anonymous function is a function which is defined without a name. In general, functions in Python are defined using 'def' keyword, but anonymous function is defined with the help of 'lambda' keyword. It takes a single expression, but can take any number of arguments. It uses the expression and returns the result of it." }, { "code": null, "e": 1653, "s": 1614, "text": "Below is a demonstration of the same −" }, { "code": null, "e": 1663, "s": 1653, "text": "Live Demo" }, { "code": null, "e": 1965, "s": 1663, "text": "my_tuple_1 = (7, 8, 11, 0 ,3, 4)\nmy_tuple_2 = (3, 2, 22, 45, 12, 9)\n\nprint (\"The first tuple is : \" )\nprint(my_tuple_1)\nprint (\"The second tuple is : \" )\nprint(my_tuple_2)\n\nmy_result = tuple(map(lambda i, j: i - j, my_tuple_1, my_tuple_2))\n\nprint(\"The tuple after subtraction is : \" )\nprint(my_result)" }, { "code": null, "e": 2108, "s": 1965, "text": "The first tuple is :\n(7, 8, 11, 0, 3, 4)\nThe second tuple is :\n(3, 2, 22, 45, 12, 9)\nThe tuple after subtraction is :\n(4, 6, -11, -45, -9, -5)" }, { "code": null, "e": 2166, "s": 2108, "text": "Two tuples are defined, and are displayed on the console." }, { "code": null, "e": 2262, "s": 2166, "text": "The lambda function is used to subtract each of the corresponding elements from the two tuples." }, { "code": null, "e": 2327, "s": 2262, "text": "This operation is mapped to all elements using the 'map' method." }, { "code": null, "e": 2366, "s": 2327, "text": "This result is converted into a tuple." }, { "code": null, "e": 2402, "s": 2366, "text": "This result is assigned to a value." }, { "code": null, "e": 2444, "s": 2402, "text": "It is displayed as output on the console." } ]
How can I position JButtons vertically one after another in Java Swing?
Position buttons vertically one after another using the Box class. Use the createVerticalBox() method that displays components from top to bottom − JButton button1 = new JButton("One"); JButton button2 = new JButton("Two"); JButton button3 = new JButton("Three"); Box box = Box.createVerticalBox(); box.add(button1); box.add(button2); box.add(button3); The following is an example to position buttons vertically one after another − package my; import javax.swing.Box; import javax.swing.JButton; import javax.swing.JFrame; public class SwingDemo { public static void main(String[] args) { JButton button1 = new JButton("One"); JButton button2 = new JButton("Two"); JButton button3 = new JButton("Three"); JButton button4 = new JButton("Four"); JButton button5 = new JButton("Five"); JButton button6 = new JButton("Six"); JButton button7 = new JButton("Seven"); Box box = Box.createVerticalBox(); box.add(button1); box.add(button2); box.add(button3); box.add(button4); box.add(button5); box.add(button6); box.add(button7); JFrame frame = new JFrame(); frame.add(box); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationByPlatform(true); frame.setSize(500, 300); frame.setVisible(true); } }
[ { "code": null, "e": 1210, "s": 1062, "text": "Position buttons vertically one after another using the Box class. Use the createVerticalBox() method that displays components from top to bottom −" }, { "code": null, "e": 1415, "s": 1210, "text": "JButton button1 = new JButton(\"One\");\nJButton button2 = new JButton(\"Two\");\nJButton button3 = new JButton(\"Three\");\nBox box = Box.createVerticalBox();\nbox.add(button1);\nbox.add(button2);\nbox.add(button3);" }, { "code": null, "e": 1494, "s": 1415, "text": "The following is an example to position buttons vertically one after another −" }, { "code": null, "e": 2403, "s": 1494, "text": "package my;\nimport javax.swing.Box;\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\npublic class SwingDemo {\n public static void main(String[] args) {\n JButton button1 = new JButton(\"One\");\n JButton button2 = new JButton(\"Two\");\n JButton button3 = new JButton(\"Three\");\n JButton button4 = new JButton(\"Four\");\n JButton button5 = new JButton(\"Five\");\n JButton button6 = new JButton(\"Six\");\n JButton button7 = new JButton(\"Seven\");\n Box box = Box.createVerticalBox();\n box.add(button1);\n box.add(button2);\n box.add(button3);\n box.add(button4);\n box.add(button5);\n box.add(button6);\n box.add(button7);\n JFrame frame = new JFrame();\n frame.add(box);\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.setLocationByPlatform(true);\n frame.setSize(500, 300);\n frame.setVisible(true);\n }\n}" } ]
A Complete Sentiment Analysis Project Using Python’s Scikit-Learn | by Rashida Nasrin Sucky | Towards Data Science
Sentiment analysis is one of the most important parts of Natural Language Processing. It is different than machine learning with numeric data because text data cannot be processed by an algorithm directly. It needs to be transformed into a numeric form. So, text data are vectorized before they get fed into the machine learning model. There are different methods of vectorization. This article will demonstrate sentiment analysis using two types of vectorizers and three machine learning models. I am using the Amazon Baby Products dataset from Kaggle for this project. Please feel free to download the dataset from this link if you want to follow along. The original dataset has three features: name(name of the products), review(Customer reviews of the products), and rating(rating of the customer of a product ranging from 1 to 5). The review column will be the input column and the rating column will be used to understand the sentiments of the review. Here are some important data preprocessing steps: The dataset has about 183,500 rows of data. There are 1147 null values. I simply will get rid of those null values.As the dataset is pretty big, it takes a lot of time to run some machine learning algorithm. So, I used 30% of the data for this project which is still 54,000 data. The sample was representative.If the rating is 1 and 2 that will be considered a bad review or negative review. And if the review is 3, 4, and 5, the review will be considered as a good review or positive review. So, I added a new column named ‘sentiments’ to the dataset that will use 1 for the positive reviews and 0 for the negative reviews. The dataset has about 183,500 rows of data. There are 1147 null values. I simply will get rid of those null values. As the dataset is pretty big, it takes a lot of time to run some machine learning algorithm. So, I used 30% of the data for this project which is still 54,000 data. The sample was representative. If the rating is 1 and 2 that will be considered a bad review or negative review. And if the review is 3, 4, and 5, the review will be considered as a good review or positive review. So, I added a new column named ‘sentiments’ to the dataset that will use 1 for the positive reviews and 0 for the negative reviews. Maybe I put a lot of code in one block. If that is a lot, please break it down and run into small pieces for better understanding. Here is the code block that imports the dataset, takes a 30% representative sample, and adds the new column ‘sentiments’: import pandas as pddf = pd.read_csv('amazon_baby.csv')#getting rid of null valuesdf = df.dropna()#Taking a 30% representative sampleimport numpy as npnp.random.seed(34)df1 = df.sample(frac = 0.3)#Adding the sentiments columndf1['sentiments'] = df1.rating.apply(lambda x: 0 if x in [1, 2] else 1) Here is how the dataset looks like now. This is the first 5 rows of data: Before starting the sentiment analysis, it is necessary to define the input features and the labels. Here there is only one feature, which is the ‘review’. The label will be the ‘sentiments’. The goal of this project is to train a model that can output if a review is positive or negative. X = df1['review']y = df1['sentiments'] First I will use Count Vectorizer as a vectorizing method. This article will focus on how to apply the vectorizers. So, I am not going for the details. But please feel free to check out this article to learn more about Count Vectorizer if you are totally new to vectorizers. I will use a count vectorizer to vectorize the text data in the review column (training feature for this project) and then use three different classification models from scikit-learn models. After that, to evaluate the model on this dataset find out the accuracy, confusion matrix, true positive rates, and true negative rates. Here are the steps. The first step is to split the dataset into training sets and testing sets.Vectorize the input feature that is out review column (both training and testing data)import the model from scikit learn library.Find the accuracy scorefind the true positive and true negative rates. The first step is to split the dataset into training sets and testing sets. Vectorize the input feature that is out review column (both training and testing data) import the model from scikit learn library. Find the accuracy score find the true positive and true negative rates. I will repeat this same process for three different classifiers now. The classifiers that will be used here are Logistic Regression, Support Vector Machine, and K Nearest Neighbor Classifier. I will summarise the results towards the end of this article. Logistic Regression Here is the code block for logistic regression. I used the comments in between the code. from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.5, random_state=24)from sklearn.feature_extraction.text import CountVectorizercv = CountVectorizer()#Vectorizing the text datactmTr = cv.fit_transform(X_train)X_test_dtm = cv.transform(X_test)from sklearn.linear_model import LogisticRegression#Training the modellr = LogisticRegression()lr.fit(ctmTr, y_train)#Accuracy scorelr_score = lr.score(X_test_dtm, y_test)print("Results for Logistic Regression with CountVectorizer")print(lr_score)#Predicting the labels for test datay_pred_lr = lr.predict(X_test_dtm)from sklearn.metrics import confusion_matrix#Confusion matrixcm_lr = confusion_matrix(y_test, y_pred_lr)tn, fp, fn, tp = confusion_matrix(y_test, y_pred_lr).ravel()print(tn, fp, fn, tp)#True positive and true negative ratestpr_lr = round(tp/(tp + fn), 4)tnr_lr = round(tn/(tn+fp), 4)print(tpr_lr, tnr_lr) As you can see I have the print statement to print accuracy, true positive, false positive, true negative, false negative, true negative rate, and false-negative rate. Support Vector Machine I will repeat the exact same process as before to use a support vector machine. from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.5, random_state=123)#Vectorizing the text datacv = CountVectorizer()ctmTr = cv.fit_transform(X_train)X_test_dtm = cv.transform(X_test)from sklearn import svm#Training the modelsvcl = svm.SVC()svcl.fit(ctmTr, y_train)svcl_score = svcl.score(X_test_dtm, y_test)print("Results for Support Vector Machine with CountVectorizer")print(svcl_score)y_pred_sv = svcl.predict(X_test_dtm)#Confusion matrixcm_sv = confusion_matrix(y_test, y_pred_sv)tn, fp, fn, tp = confusion_matrix(y_test, y_pred_sv).ravel()print(tn, fp, fn, tp)tpr_sv = round(tp/(tp + fn), 4)tnr_sv = round(tn/(tn+fp), 4)print(tpr_sv, tnr_sv) I should warn you that support vector machine takes a lot more time than logistic regression. K Nearest Neighbor I will run a KNN classifier and get the same evaluation matrix as before. Codes will be almost the same. from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.5, random_state=143)from sklearn.feature_extraction.text import CountVectorizercv = CountVectorizer()ctmTr = cv.fit_transform(X_train)X_test_dtm = cv.transform(X_test)from sklearn.neighbors import KNeighborsClassifierknn = KNeighborsClassifier(n_neighbors=5)knn.fit(ctmTr, y_train)knn_score = knn.score(X_test_dtm, y_test)print("Results for KNN Classifier with CountVectorizer")print(knn_score)y_pred_knn = knn.predict(X_test_dtm)#Confusion matrixcm_knn = confusion_matrix(y_test, y_pred_knn)tn, fp, fn, tp = confusion_matrix(y_test, y_pred_knn).ravel()print(tn, fp, fn, tp)tpr_knn = round(tp/(tp + fn), 4)tnr_knn = round(tn/(tn+fp), 4)print(tpr_knn, tnr_knn) KNN classifier takes less time than Support Vector Machine classifier. With that, the three classifiers are done for the count vectorizer method. Next, I will use the TF-IDF vectorizer. This vectorizer is known to be a more popular one because it uses the term frequency of the words. Please feel free to check this article to learn details about the TF-IDF vectorizer. I will follow exactly the same process I did for the count vectorizer. Only the vectorizer will be different. But that’s not a problem. Super cool sklearn library will take care of the calculation part as usual. Logistic Regression The complete code block for the Logistic regression again with the TF-IDF vectorizer: from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.5, random_state=45)from sklearn.feature_extraction.text import TfidfVectorizer#tfidf vectorizervectorizer = TfidfVectorizer()X_train_vec = vectorizer.fit_transform(X_train)X_test_vec = vectorizer.transform(X_test)from sklearn.linear_model import LogisticRegressionlr = LogisticRegression()lr.fit(X_train_vec, y_train)lr_score = lr.score(X_test_vec, y_test)print("Results for Logistic Regression with tfidf")print(lr_score)y_pred_lr = lr.predict(X_test_vec)#Confusion matrixfrom sklearn.metrics import confusion_matrixcm_knn = confusion_matrix(y_test, y_pred_lr)tn, fp, fn, tp = confusion_matrix(y_test, y_pred_lr).ravel()print(tn, fp, fn, tp)tpr_knn = round(tp/(tp + fn), 4)tnr_knn = round(tn/(tn+fp), 4)print(tpr_knn, tnr_knn) As you can see you can reuse the codes from before except for the vectorizer part. Support Vector Machine It will also be the same process as the previous support vector machine except for the vectorizer. from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.5, random_state=55)vectorizer = TfidfVectorizer()X_train_vec = vectorizer.fit_transform(X_train)X_test_vec = vectorizer.transform(X_test)from sklearn import svm#params = {'kernel':('linear', 'rbf'), 'C':[1, 10, 100]}svcl = svm.SVC(kernel = 'rbf')#clf_sv = GridSearchCV(svcl, params)svcl.fit(X_train_vec, y_train)svcl_score = svcl.score(X_test_vec, y_test)print("Results for Support Vector Machine with tfidf")print(svcl_score)y_pred_sv = svcl.predict(X_test_vec)#Confusion matrixfrom sklearn.metrics import confusion_matrixcm_sv = confusion_matrix(y_test, y_pred_sv)tn, fp, fn, tp = confusion_matrix(y_test, y_pred_sv).ravel()print(tn, fp, fn, tp)tpr_sv = round(tp/(tp + fn), 4)tnr_sv = round(tn/(tn+fp), 4)print(tpr_sv, tnr_sv) As before it will take a lot more time than logistic regression. So, it may require some patience. K Nearest Neighbor This is the last one. from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.5, random_state=65)vectorizer = TfidfVectorizer()X_train_vec = vectorizer.fit_transform(X_train)X_test_vec = vectorizer.transform(X_test)from sklearn.neighbors import KNeighborsClassifierknn = KNeighborsClassifier(n_neighbors=5)knn.fit(X_train_vec, y_train)knn_score = knn.score(X_test_vec, y_test)print("Results for KNN Classifier with tfidf")print(knn_score)y_pred_knn = knn.predict(X_test_vec)#Confusion matrixcm_knn = confusion_matrix(y_test, y_pred_knn)tn, fp, fn, tp = confusion_matrix(y_test, y_pred_knn).ravel()print(tn, fp, fn, tp)tpr_knn = round(tp/(tp + fn), 4)tnr_knn = round(tn/(tn+fp), 4)print(tpr_knn, tnr_knn) Here I summarised the results for all six code blocks above. Here are some key findings: Overall TF-IDF vectorizer gave us slightly better results than the count vectorizer part. For both the vectorizer.Logistic regression was the best out of all three classifiers used for this project considering overall accuracy, true positive rate, and true negative rate.The KNN classifier does not seem to be suitable for this project. Though true positive rates look very good, true negative rates look really poor. Overall TF-IDF vectorizer gave us slightly better results than the count vectorizer part. For both the vectorizer. Logistic regression was the best out of all three classifiers used for this project considering overall accuracy, true positive rate, and true negative rate. The KNN classifier does not seem to be suitable for this project. Though true positive rates look very good, true negative rates look really poor. I have done this project as a part of one of my classes and decided to share this. You may wonder why I split the dataset into training and testing every time I trained a model. This was a requirement for the class. The idea is a certain train-test split may have a bias towards a certain classifier. So, I had to split the dataset before each model. Feel free to follow me on Twitter and like my Facebook page.
[ { "code": null, "e": 669, "s": 172, "text": "Sentiment analysis is one of the most important parts of Natural Language Processing. It is different than machine learning with numeric data because text data cannot be processed by an algorithm directly. It needs to be transformed into a numeric form. So, text data are vectorized before they get fed into the machine learning model. There are different methods of vectorization. This article will demonstrate sentiment analysis using two types of vectorizers and three machine learning models." }, { "code": null, "e": 828, "s": 669, "text": "I am using the Amazon Baby Products dataset from Kaggle for this project. Please feel free to download the dataset from this link if you want to follow along." }, { "code": null, "e": 1180, "s": 828, "text": "The original dataset has three features: name(name of the products), review(Customer reviews of the products), and rating(rating of the customer of a product ranging from 1 to 5). The review column will be the input column and the rating column will be used to understand the sentiments of the review. Here are some important data preprocessing steps:" }, { "code": null, "e": 1805, "s": 1180, "text": "The dataset has about 183,500 rows of data. There are 1147 null values. I simply will get rid of those null values.As the dataset is pretty big, it takes a lot of time to run some machine learning algorithm. So, I used 30% of the data for this project which is still 54,000 data. The sample was representative.If the rating is 1 and 2 that will be considered a bad review or negative review. And if the review is 3, 4, and 5, the review will be considered as a good review or positive review. So, I added a new column named ‘sentiments’ to the dataset that will use 1 for the positive reviews and 0 for the negative reviews." }, { "code": null, "e": 1921, "s": 1805, "text": "The dataset has about 183,500 rows of data. There are 1147 null values. I simply will get rid of those null values." }, { "code": null, "e": 2117, "s": 1921, "text": "As the dataset is pretty big, it takes a lot of time to run some machine learning algorithm. So, I used 30% of the data for this project which is still 54,000 data. The sample was representative." }, { "code": null, "e": 2432, "s": 2117, "text": "If the rating is 1 and 2 that will be considered a bad review or negative review. And if the review is 3, 4, and 5, the review will be considered as a good review or positive review. So, I added a new column named ‘sentiments’ to the dataset that will use 1 for the positive reviews and 0 for the negative reviews." }, { "code": null, "e": 2563, "s": 2432, "text": "Maybe I put a lot of code in one block. If that is a lot, please break it down and run into small pieces for better understanding." }, { "code": null, "e": 2685, "s": 2563, "text": "Here is the code block that imports the dataset, takes a 30% representative sample, and adds the new column ‘sentiments’:" }, { "code": null, "e": 2981, "s": 2685, "text": "import pandas as pddf = pd.read_csv('amazon_baby.csv')#getting rid of null valuesdf = df.dropna()#Taking a 30% representative sampleimport numpy as npnp.random.seed(34)df1 = df.sample(frac = 0.3)#Adding the sentiments columndf1['sentiments'] = df1.rating.apply(lambda x: 0 if x in [1, 2] else 1)" }, { "code": null, "e": 3055, "s": 2981, "text": "Here is how the dataset looks like now. This is the first 5 rows of data:" }, { "code": null, "e": 3345, "s": 3055, "text": "Before starting the sentiment analysis, it is necessary to define the input features and the labels. Here there is only one feature, which is the ‘review’. The label will be the ‘sentiments’. The goal of this project is to train a model that can output if a review is positive or negative." }, { "code": null, "e": 3384, "s": 3345, "text": "X = df1['review']y = df1['sentiments']" }, { "code": null, "e": 3659, "s": 3384, "text": "First I will use Count Vectorizer as a vectorizing method. This article will focus on how to apply the vectorizers. So, I am not going for the details. But please feel free to check out this article to learn more about Count Vectorizer if you are totally new to vectorizers." }, { "code": null, "e": 4007, "s": 3659, "text": "I will use a count vectorizer to vectorize the text data in the review column (training feature for this project) and then use three different classification models from scikit-learn models. After that, to evaluate the model on this dataset find out the accuracy, confusion matrix, true positive rates, and true negative rates. Here are the steps." }, { "code": null, "e": 4282, "s": 4007, "text": "The first step is to split the dataset into training sets and testing sets.Vectorize the input feature that is out review column (both training and testing data)import the model from scikit learn library.Find the accuracy scorefind the true positive and true negative rates." }, { "code": null, "e": 4358, "s": 4282, "text": "The first step is to split the dataset into training sets and testing sets." }, { "code": null, "e": 4445, "s": 4358, "text": "Vectorize the input feature that is out review column (both training and testing data)" }, { "code": null, "e": 4489, "s": 4445, "text": "import the model from scikit learn library." }, { "code": null, "e": 4513, "s": 4489, "text": "Find the accuracy score" }, { "code": null, "e": 4561, "s": 4513, "text": "find the true positive and true negative rates." }, { "code": null, "e": 4815, "s": 4561, "text": "I will repeat this same process for three different classifiers now. The classifiers that will be used here are Logistic Regression, Support Vector Machine, and K Nearest Neighbor Classifier. I will summarise the results towards the end of this article." }, { "code": null, "e": 4835, "s": 4815, "text": "Logistic Regression" }, { "code": null, "e": 4924, "s": 4835, "text": "Here is the code block for logistic regression. I used the comments in between the code." }, { "code": null, "e": 5902, "s": 4924, "text": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.5, random_state=24)from sklearn.feature_extraction.text import CountVectorizercv = CountVectorizer()#Vectorizing the text datactmTr = cv.fit_transform(X_train)X_test_dtm = cv.transform(X_test)from sklearn.linear_model import LogisticRegression#Training the modellr = LogisticRegression()lr.fit(ctmTr, y_train)#Accuracy scorelr_score = lr.score(X_test_dtm, y_test)print(\"Results for Logistic Regression with CountVectorizer\")print(lr_score)#Predicting the labels for test datay_pred_lr = lr.predict(X_test_dtm)from sklearn.metrics import confusion_matrix#Confusion matrixcm_lr = confusion_matrix(y_test, y_pred_lr)tn, fp, fn, tp = confusion_matrix(y_test, y_pred_lr).ravel()print(tn, fp, fn, tp)#True positive and true negative ratestpr_lr = round(tp/(tp + fn), 4)tnr_lr = round(tn/(tn+fp), 4)print(tpr_lr, tnr_lr)" }, { "code": null, "e": 6070, "s": 5902, "text": "As you can see I have the print statement to print accuracy, true positive, false positive, true negative, false negative, true negative rate, and false-negative rate." }, { "code": null, "e": 6093, "s": 6070, "text": "Support Vector Machine" }, { "code": null, "e": 6173, "s": 6093, "text": "I will repeat the exact same process as before to use a support vector machine." }, { "code": null, "e": 6936, "s": 6173, "text": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.5, random_state=123)#Vectorizing the text datacv = CountVectorizer()ctmTr = cv.fit_transform(X_train)X_test_dtm = cv.transform(X_test)from sklearn import svm#Training the modelsvcl = svm.SVC()svcl.fit(ctmTr, y_train)svcl_score = svcl.score(X_test_dtm, y_test)print(\"Results for Support Vector Machine with CountVectorizer\")print(svcl_score)y_pred_sv = svcl.predict(X_test_dtm)#Confusion matrixcm_sv = confusion_matrix(y_test, y_pred_sv)tn, fp, fn, tp = confusion_matrix(y_test, y_pred_sv).ravel()print(tn, fp, fn, tp)tpr_sv = round(tp/(tp + fn), 4)tnr_sv = round(tn/(tn+fp), 4)print(tpr_sv, tnr_sv)" }, { "code": null, "e": 7030, "s": 6936, "text": "I should warn you that support vector machine takes a lot more time than logistic regression." }, { "code": null, "e": 7049, "s": 7030, "text": "K Nearest Neighbor" }, { "code": null, "e": 7154, "s": 7049, "text": "I will run a KNN classifier and get the same evaluation matrix as before. Codes will be almost the same." }, { "code": null, "e": 7978, "s": 7154, "text": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.5, random_state=143)from sklearn.feature_extraction.text import CountVectorizercv = CountVectorizer()ctmTr = cv.fit_transform(X_train)X_test_dtm = cv.transform(X_test)from sklearn.neighbors import KNeighborsClassifierknn = KNeighborsClassifier(n_neighbors=5)knn.fit(ctmTr, y_train)knn_score = knn.score(X_test_dtm, y_test)print(\"Results for KNN Classifier with CountVectorizer\")print(knn_score)y_pred_knn = knn.predict(X_test_dtm)#Confusion matrixcm_knn = confusion_matrix(y_test, y_pred_knn)tn, fp, fn, tp = confusion_matrix(y_test, y_pred_knn).ravel()print(tn, fp, fn, tp)tpr_knn = round(tp/(tp + fn), 4)tnr_knn = round(tn/(tn+fp), 4)print(tpr_knn, tnr_knn)" }, { "code": null, "e": 8049, "s": 7978, "text": "KNN classifier takes less time than Support Vector Machine classifier." }, { "code": null, "e": 8124, "s": 8049, "text": "With that, the three classifiers are done for the count vectorizer method." }, { "code": null, "e": 8348, "s": 8124, "text": "Next, I will use the TF-IDF vectorizer. This vectorizer is known to be a more popular one because it uses the term frequency of the words. Please feel free to check this article to learn details about the TF-IDF vectorizer." }, { "code": null, "e": 8560, "s": 8348, "text": "I will follow exactly the same process I did for the count vectorizer. Only the vectorizer will be different. But that’s not a problem. Super cool sklearn library will take care of the calculation part as usual." }, { "code": null, "e": 8580, "s": 8560, "text": "Logistic Regression" }, { "code": null, "e": 8666, "s": 8580, "text": "The complete code block for the Logistic regression again with the TF-IDF vectorizer:" }, { "code": null, "e": 9558, "s": 8666, "text": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.5, random_state=45)from sklearn.feature_extraction.text import TfidfVectorizer#tfidf vectorizervectorizer = TfidfVectorizer()X_train_vec = vectorizer.fit_transform(X_train)X_test_vec = vectorizer.transform(X_test)from sklearn.linear_model import LogisticRegressionlr = LogisticRegression()lr.fit(X_train_vec, y_train)lr_score = lr.score(X_test_vec, y_test)print(\"Results for Logistic Regression with tfidf\")print(lr_score)y_pred_lr = lr.predict(X_test_vec)#Confusion matrixfrom sklearn.metrics import confusion_matrixcm_knn = confusion_matrix(y_test, y_pred_lr)tn, fp, fn, tp = confusion_matrix(y_test, y_pred_lr).ravel()print(tn, fp, fn, tp)tpr_knn = round(tp/(tp + fn), 4)tnr_knn = round(tn/(tn+fp), 4)print(tpr_knn, tnr_knn)" }, { "code": null, "e": 9641, "s": 9558, "text": "As you can see you can reuse the codes from before except for the vectorizer part." }, { "code": null, "e": 9664, "s": 9641, "text": "Support Vector Machine" }, { "code": null, "e": 9763, "s": 9664, "text": "It will also be the same process as the previous support vector machine except for the vectorizer." }, { "code": null, "e": 10656, "s": 9763, "text": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.5, random_state=55)vectorizer = TfidfVectorizer()X_train_vec = vectorizer.fit_transform(X_train)X_test_vec = vectorizer.transform(X_test)from sklearn import svm#params = {'kernel':('linear', 'rbf'), 'C':[1, 10, 100]}svcl = svm.SVC(kernel = 'rbf')#clf_sv = GridSearchCV(svcl, params)svcl.fit(X_train_vec, y_train)svcl_score = svcl.score(X_test_vec, y_test)print(\"Results for Support Vector Machine with tfidf\")print(svcl_score)y_pred_sv = svcl.predict(X_test_vec)#Confusion matrixfrom sklearn.metrics import confusion_matrixcm_sv = confusion_matrix(y_test, y_pred_sv)tn, fp, fn, tp = confusion_matrix(y_test, y_pred_sv).ravel()print(tn, fp, fn, tp)tpr_sv = round(tp/(tp + fn), 4)tnr_sv = round(tn/(tn+fp), 4)print(tpr_sv, tnr_sv)" }, { "code": null, "e": 10755, "s": 10656, "text": "As before it will take a lot more time than logistic regression. So, it may require some patience." }, { "code": null, "e": 10774, "s": 10755, "text": "K Nearest Neighbor" }, { "code": null, "e": 10796, "s": 10774, "text": "This is the last one." }, { "code": null, "e": 11586, "s": 10796, "text": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.5, random_state=65)vectorizer = TfidfVectorizer()X_train_vec = vectorizer.fit_transform(X_train)X_test_vec = vectorizer.transform(X_test)from sklearn.neighbors import KNeighborsClassifierknn = KNeighborsClassifier(n_neighbors=5)knn.fit(X_train_vec, y_train)knn_score = knn.score(X_test_vec, y_test)print(\"Results for KNN Classifier with tfidf\")print(knn_score)y_pred_knn = knn.predict(X_test_vec)#Confusion matrixcm_knn = confusion_matrix(y_test, y_pred_knn)tn, fp, fn, tp = confusion_matrix(y_test, y_pred_knn).ravel()print(tn, fp, fn, tp)tpr_knn = round(tp/(tp + fn), 4)tnr_knn = round(tn/(tn+fp), 4)print(tpr_knn, tnr_knn)" }, { "code": null, "e": 11647, "s": 11586, "text": "Here I summarised the results for all six code blocks above." }, { "code": null, "e": 11675, "s": 11647, "text": "Here are some key findings:" }, { "code": null, "e": 12093, "s": 11675, "text": "Overall TF-IDF vectorizer gave us slightly better results than the count vectorizer part. For both the vectorizer.Logistic regression was the best out of all three classifiers used for this project considering overall accuracy, true positive rate, and true negative rate.The KNN classifier does not seem to be suitable for this project. Though true positive rates look very good, true negative rates look really poor." }, { "code": null, "e": 12208, "s": 12093, "text": "Overall TF-IDF vectorizer gave us slightly better results than the count vectorizer part. For both the vectorizer." }, { "code": null, "e": 12366, "s": 12208, "text": "Logistic regression was the best out of all three classifiers used for this project considering overall accuracy, true positive rate, and true negative rate." }, { "code": null, "e": 12513, "s": 12366, "text": "The KNN classifier does not seem to be suitable for this project. Though true positive rates look very good, true negative rates look really poor." }, { "code": null, "e": 12864, "s": 12513, "text": "I have done this project as a part of one of my classes and decided to share this. You may wonder why I split the dataset into training and testing every time I trained a model. This was a requirement for the class. The idea is a certain train-test split may have a bias towards a certain classifier. So, I had to split the dataset before each model." } ]
Track objects with Camshift using OpenCV - GeeksforGeeks
10 Feb, 2020 OpenCV is the huge open-source library for computer vision, machine learning, and image processing and now it plays a major role in real-time operation which is very important in today’s systems. By using it, one can process images and videos to identify objects, faces, or even the handwriting of a human. Camshift or we can say Continuously Adaptive Meanshift is an enhanced version of the meanshift algorithm which provides more accuracy and robustness to the model. With the help of Camshift algorithm, the size of the window keeps updating when the tracking window tries to converge. The tracking is done by using the color information of the object. Also, it provides the best fitting tracking window for object tracking. It applies meanshift first and then updates the size of the window as: It then calculates the best fitting ellipse to it and again applies the meanshift with the newly scaled search window and the previous window. This process is continued until the required accuracy is met. Note: For more information about meanshift refer to Python OpenCV: Meanshift Below is the implementation. import numpy as npimport cv2 as cv # Read the input videocap = cv.VideoCapture('sample.mp4') # take first frame of the# videoret, frame = cap.read() # setup initial region of# trackerx, y, width, height = 400, 440, 150, 150track_window = (x, y, width, height) # set up the Region of# Interest for trackingroi = frame[y:y + height, x : x + width] # convert ROI from BGR to# HSV formathsv_roi = cv.cvtColor(roi, cv.COLOR_BGR2HSV) # perform masking operationmask = cv.inRange(hsv_roi, np.array((0., 60., 32.)), np.array((180., 255., 255))) roi_hist = cv.calcHist([hsv_roi], [0], mask, [180], [0, 180]) cv.normalize(roi_hist, roi_hist, 0, 255, cv.NORM_MINMAX) # Setup the termination criteria, # either 15 iteration or move by# atleast 2 ptterm_crit = ( cv.TERM_CRITERIA_EPS | cv.TERM_CRITERIA_COUNT, 15, 2) while(1): ret, frame = cap.read() # Resize the video frames. frame = cv.resize(frame, (720, 720), fx = 0, fy = 0, interpolation = cv.INTER_CUBIC) cv.imshow('Original', frame) # perform thresholding on # the video frames ret1, frame1 = cv.threshold(frame, 180, 155, cv.THRESH_TOZERO_INV) # convert from BGR to HSV # format. hsv = cv.cvtColor(frame1, cv.COLOR_BGR2HSV) dst = cv.calcBackProject([hsv], [0], roi_hist, [0, 180], 1) # apply Camshift to get the # new location ret2, track_window = cv.CamShift(dst, track_window, term_crit) # Draw it on image pts = cv.boxPoints(ret2) # convert from floating # to integer pts = np.int0(pts) # Draw Tracking window on the # video frame. Result = cv.polylines(frame, [pts], True, (0, 255, 255), 2) cv.imshow('Camshift', Result) # set ESC key as the # exit button. k = cv.waitKey(30) & 0xff if k == 27: break # Release the cap objectcap.release() # close all opened windowscv.destroyAllWindows() Output: Python-OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe Python OOPs Concepts Python | Get unique values from a list Check if element exists in list in Python Python Classes and Objects Python | os.path.join() method How To Convert Python Dictionary To JSON? Python | Pandas dataframe.groupby() Create a directory in Python
[ { "code": null, "e": 24212, "s": 24184, "text": "\n10 Feb, 2020" }, { "code": null, "e": 24519, "s": 24212, "text": "OpenCV is the huge open-source library for computer vision, machine learning, and image processing and now it plays a major role in real-time operation which is very important in today’s systems. By using it, one can process images and videos to identify objects, faces, or even the handwriting of a human." }, { "code": null, "e": 25011, "s": 24519, "text": "Camshift or we can say Continuously Adaptive Meanshift is an enhanced version of the meanshift algorithm which provides more accuracy and robustness to the model. With the help of Camshift algorithm, the size of the window keeps updating when the tracking window tries to converge. The tracking is done by using the color information of the object. Also, it provides the best fitting tracking window for object tracking. It applies meanshift first and then updates the size of the window as:" }, { "code": null, "e": 25221, "s": 25016, "text": "It then calculates the best fitting ellipse to it and again applies the meanshift with the newly scaled search window and the previous window. This process is continued until the required accuracy is met." }, { "code": null, "e": 25298, "s": 25221, "text": "Note: For more information about meanshift refer to Python OpenCV: Meanshift" }, { "code": null, "e": 25327, "s": 25298, "text": "Below is the implementation." }, { "code": "import numpy as npimport cv2 as cv # Read the input videocap = cv.VideoCapture('sample.mp4') # take first frame of the# videoret, frame = cap.read() # setup initial region of# trackerx, y, width, height = 400, 440, 150, 150track_window = (x, y, width, height) # set up the Region of# Interest for trackingroi = frame[y:y + height, x : x + width] # convert ROI from BGR to# HSV formathsv_roi = cv.cvtColor(roi, cv.COLOR_BGR2HSV) # perform masking operationmask = cv.inRange(hsv_roi, np.array((0., 60., 32.)), np.array((180., 255., 255))) roi_hist = cv.calcHist([hsv_roi], [0], mask, [180], [0, 180]) cv.normalize(roi_hist, roi_hist, 0, 255, cv.NORM_MINMAX) # Setup the termination criteria, # either 15 iteration or move by# atleast 2 ptterm_crit = ( cv.TERM_CRITERIA_EPS | cv.TERM_CRITERIA_COUNT, 15, 2) while(1): ret, frame = cap.read() # Resize the video frames. frame = cv.resize(frame, (720, 720), fx = 0, fy = 0, interpolation = cv.INTER_CUBIC) cv.imshow('Original', frame) # perform thresholding on # the video frames ret1, frame1 = cv.threshold(frame, 180, 155, cv.THRESH_TOZERO_INV) # convert from BGR to HSV # format. hsv = cv.cvtColor(frame1, cv.COLOR_BGR2HSV) dst = cv.calcBackProject([hsv], [0], roi_hist, [0, 180], 1) # apply Camshift to get the # new location ret2, track_window = cv.CamShift(dst, track_window, term_crit) # Draw it on image pts = cv.boxPoints(ret2) # convert from floating # to integer pts = np.int0(pts) # Draw Tracking window on the # video frame. Result = cv.polylines(frame, [pts], True, (0, 255, 255), 2) cv.imshow('Camshift', Result) # set ESC key as the # exit button. k = cv.waitKey(30) & 0xff if k == 27: break # Release the cap objectcap.release() # close all opened windowscv.destroyAllWindows()", "e": 27822, "s": 25327, "text": null }, { "code": null, "e": 27830, "s": 27822, "text": "Output:" }, { "code": null, "e": 27844, "s": 27830, "text": "Python-OpenCV" }, { "code": null, "e": 27851, "s": 27844, "text": "Python" }, { "code": null, "e": 27949, "s": 27851, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27958, "s": 27949, "text": "Comments" }, { "code": null, "e": 27971, "s": 27958, "text": "Old Comments" }, { "code": null, "e": 28003, "s": 27971, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28059, "s": 28003, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28080, "s": 28059, "text": "Python OOPs Concepts" }, { "code": null, "e": 28119, "s": 28080, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28161, "s": 28119, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28188, "s": 28161, "text": "Python Classes and Objects" }, { "code": null, "e": 28219, "s": 28188, "text": "Python | os.path.join() method" }, { "code": null, "e": 28261, "s": 28219, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28297, "s": 28261, "text": "Python | Pandas dataframe.groupby()" } ]
DATESBETWEEN function
Returns a table that contains a column of dates that begins with the start_date and continues until the end_date. DATESBETWEEN (<dates>, <start_date>, <end_date>) dates A column that contains dates. start_date A date expression. end_date A date expression. A table containing a single column of date values. If start_date is a blank date value, then start_date will be the earliest value in the dates column. If start_date is a blank date value, then start_date will be the earliest value in the dates column. If end_date is a blank date value, then end_date will be the latest value in the dates column. If end_date is a blank date value, then end_date will be the latest value in the dates column. The dates used as the start_date and end_date are inclusive. The dates used as the start_date and end_date are inclusive. If the sales occurred on October 1 and December 31 and you specify October 1 as the start date and December 31 as the end_date, then sales on October 1 and December 31 are counted. If the sales occurred on October 1 and December 31 and you specify October 1 as the start date and December 31 as the end_date, then sales on October 1 and December 31 are counted. = CALCULATE ( SUM (Sales[Sales Amount]), DATESBETWEEN (Sales[Date], DATE (2015,1,1), DATE (2015,3,31)) ) 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": 2115, "s": 2001, "text": "Returns a table that contains a column of dates that begins with the start_date and continues until the end_date." }, { "code": null, "e": 2166, "s": 2115, "text": "DATESBETWEEN (<dates>, <start_date>, <end_date>) \n" }, { "code": null, "e": 2172, "s": 2166, "text": "dates" }, { "code": null, "e": 2202, "s": 2172, "text": "A column that contains dates." }, { "code": null, "e": 2213, "s": 2202, "text": "start_date" }, { "code": null, "e": 2232, "s": 2213, "text": "A date expression." }, { "code": null, "e": 2241, "s": 2232, "text": "end_date" }, { "code": null, "e": 2260, "s": 2241, "text": "A date expression." }, { "code": null, "e": 2311, "s": 2260, "text": "A table containing a single column of date values." }, { "code": null, "e": 2412, "s": 2311, "text": "If start_date is a blank date value, then start_date will be the earliest value in the dates column." }, { "code": null, "e": 2513, "s": 2412, "text": "If start_date is a blank date value, then start_date will be the earliest value in the dates column." }, { "code": null, "e": 2608, "s": 2513, "text": "If end_date is a blank date value, then end_date will be the latest value in the dates column." }, { "code": null, "e": 2703, "s": 2608, "text": "If end_date is a blank date value, then end_date will be the latest value in the dates column." }, { "code": null, "e": 2764, "s": 2703, "text": "The dates used as the start_date and end_date are inclusive." }, { "code": null, "e": 2825, "s": 2764, "text": "The dates used as the start_date and end_date are inclusive." }, { "code": null, "e": 3006, "s": 2825, "text": "If the sales occurred on October 1 and December 31 and you specify October 1 as the start date and December 31 as the end_date, then sales on October 1 and December 31 are counted." }, { "code": null, "e": 3187, "s": 3006, "text": "If the sales occurred on October 1 and December 31 and you specify October 1 as the start date and December 31 as the end_date, then sales on October 1 and December 31 are counted." }, { "code": null, "e": 3295, "s": 3187, "text": "= CALCULATE (\n SUM (Sales[Sales Amount]), DATESBETWEEN (Sales[Date], DATE (2015,1,1), DATE (2015,3,31))\n)" }, { "code": null, "e": 3330, "s": 3295, "text": "\n 53 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3344, "s": 3330, "text": " Abhay Gadiya" }, { "code": null, "e": 3377, "s": 3344, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 3391, "s": 3377, "text": " Randy Minder" }, { "code": null, "e": 3426, "s": 3391, "text": "\n 26 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3440, "s": 3426, "text": " Randy Minder" }, { "code": null, "e": 3447, "s": 3440, "text": " Print" }, { "code": null, "e": 3458, "s": 3447, "text": " Add Notes" } ]
How to deploy Apache Airflow with Celery on AWS | by Axel Furlan | Towards Data Science
Disclaimer: this post assumes basic knowledge of Airflow, AWS ECS, VPC (security groups, etc) and Docker. I suggest an architecture that may not be perfect nor the best in your particular case. In that case, make what you want from this lecture. Where I work, we use Apache Airflow extensively. We have approximately 15 DAGs, that may not seem like a lot, but some of them have many steps (tasks) that involve downloading big SQL backups, transforming some values using Python and re-uploading them into our warehouse. At first, we started using the Sequential Executor (no parallelism, just 1 task running at a time) due to the easy setup and lack of many DAGs. As time went on, DAGs kept increasing and some of them presented the opportunity to make use of parallelism, so with some configurations, we started using the Local Executor. You may ask...Why the whole thing doesn’t cut it anymore? Well, both cases had only 1 container deployed in AWS ECS doing everything: serving the web UI, scheduling the jobs and worker processes executing them. This wasn’t scalable, the only option we had was scaling vertically (you know, adding more vCPU, more RAM and such). There was not another option. Furthermore, if something in the container fails, the whole thing fails (no high availability). Also, the whole service must be public for the webserver to be accessible through the internet. If you want to make certain components private (such as the scheduler and workers) this is NOT possible here. There isn’t any guide talking about how to deploy Airflow in AWS, or making use of their extensive offer of services. It’s easy to deploy the whole thing locally using docker-compose or in an EC2, but is it really what you want? What about completely isolated nodes talking to each other inside the same VPC? Making private what needs to be private and public what needs to be public? This whole diagram might be complicated at a first glance, and maybe even frightening but don’t worry. What you have to understand from this is probably just the following: One can only connect to Airflow’s webserver or Flower (we’ll talk about Flower later) through an ingress. There’s no point of access from the outside to the scheduler, workers, Redis or even the metadata database. You don’t want connections from the outside there. Everything’s inside the same VPC, to make things easier. Every object has its security group, allowing connections only from the correct services. Everything is an AWS Fargate task, again, we’ll talk about Fargate later. Principally, AWS ECS and Fargate are the stars in this. Amazon Elastic Container Service (Amazon ECS) is a fully managed container orchestration service [...] You can choose to run your ECS clusters using AWS Fargate, which is serverless compute for containers. Fargate removes the need to provision and manage servers, lets you specify and pay for resources per application, and improves security through application isolation by design. A nice analogy about serverless computing is this one I read in this cool post: Serverless computing is like driverless cars; there’s still a driver, just not one you can see. You don’t need to ask if the driver is hungry, tired, drunk or needs to stop for a bathroom break. If we ever let driverless cars drive on our roads it will be because we don’t have to care about the driver, just the fact that they will take us where we want to go — Mary Branscombe I like to say that ECS is just a chill Kubernetes, without much to configure it’s ready to deploy your apps using just the Docker image and some extra settings–such as how much CPU or RAM you want your app to be able to use, if you want auto-scaling, use a Load Balancer out of the box and what-not. We should also set up a metadata database, for that we’re going to use the convenient RDS. Before anything else, we have to set which Docker image we’re gonna use and set it as a base image to build on top of it. For this, I’ve used Puckel’s Airflow. This docker image gives you all you need to set up Airflow in any of the 3 main executors. With over 5 million downloads, it’s safe to say that this guy has done a great job. Let’s create our custom Dockerfile. I’ve used the following: I added a personal airflow.cfg (which has configurations for s3 logging and SMTP server credentials), a custom entrypoint.sh and a dags folder that has all my DAGs. In this case, . is already defined in the base image to be /usr/local/airflow using the instruction WORKDIR. My entrypoint is the following: I got rid of some lines in the base image’s entrypoint that were conditions serving the different executors and just made it for Celery only, also getting rid of an annoying wait_for_port function that somehow didn’t work. What this whole thing does is first, sets up useful environment variables and then, depending on the command given in docker run, follows a switch that executes different portions of code. Let’s say, if you’re launching a worker, it’s going to install your Python requirements and then execute the worker process. If it’s the webserver, it’ll install requirements as well but also it’s going to initialize the database with airflow initdb command and then open the webserver for Airflow’s UI. If you want to test the whole thing and make sure everything works, you can do so with Puckel’s docker-compose celery YAML file. After a while, you should be able to access localhost:8080 and see Airflow’s dashboard. You might as well access localhost:5555 and see Flower as well. From this point, run some example DAGs–or even yours–and see for yourself how things are processed from a trigger in the webserver, the scheduler grabbing the task and sending it to queue, and finally, a worker picking it up and running it. For this tutorial, we’re going to keep it simple and use AWS ECR. ECR is just a Docker image repository. ECR is integrated with ECS out of the box. To create a repository, hop into the ECR console and click on Create repository and choose whatever name you feel adequate. Tip: you can have a repository for your staging Airflow and one for production. Remember, all Airflow processes are going to use the same image to avoid redundancy and be DRY. Now enter your new fresh repository and click on View push commands. That’ll walk you through pushing your Airflow image to the repo. If an error comes up during the first step, like unable to locate credentials you probably haven’t set your awscli credentials, look at this. Once you pushed the image and see it in the ECR console, you’re ready for the next step! Let’s start by creating an ECS Cluster, go to Services and choose ECS. Probably as this is your first time, you’re gonna see a screen presenting the service to you and an easy first cluster button. What you need to do here is just create a Network Only cluster. At this point, you will probably have a window that looks like this. This right here is a matter of choice to you, whether you use the same VPC as the rest of your instances or create another one specifically for this cluster–I did the latter. If you choose to do that, I think just 1 subnet will be sufficient. We’re going to set up a PostgreSQL 9.6 micro instance database. If you’re familiar with how to do this, feel free to do it and skip to the next step. Go to Services -> RDS. Go to databases section and Create database. Select the PostgreSQL logo, go for Version 9.6.X, whatever minor version is fine. Now, I’m still deliberating on if I’m super cheap or the airflow metadata database doesn’t really need to be THAT robust, so I opted for a free tier micro instance. If you find that that isn’t enough for you, it’s easy to upgrade later so don’t worry. Next configurations are up to you, whatever instance name, username, password, just make sure it’s going to be created in the same cluster that ECS uses. Great, we have our empty cluster now. Let’s create our task definitions. Task definitions are like blueprints, they define how your service is going to be executed–which container is it going to use, how much CPU and RAM is assigned to it, which ports are mapped, what environment variables does it have, etc. Go to Task Definitions at the left panel and click in Create new Task Definition. Remember, we want Fargate, so select it and hit Next step. From now on, we’ll have to create a task definition for the webserver, the scheduler, and the workers. I’ll walk you through all the necessary configurations you must provide for every task to work correctly. Task Definition Name: identifier name. Choose something descriptive like airflow-webserver, airflow-worker, etc.Task Role: the IAM role the task is going to be injected in the container. Choose one that has permissions for what your task must do–extract secrets from secrets manager, log with awslogs log driver, query buckets from S3. If you’re not sure, just use the basic ecsTaskExecutionRole , if it’s not present in the dropdown check here.Network Mode: awsvpc since we’re using Fargate.Task execution role: the role that’s going to be able to pull the image from AWS ECR and log in Cloudwatch. ecsTaskExecutionRole has both these policies.Task size: almost completely depends on you. Most of your resources will on the workers, hence they’re gonna do all the dirty work. Just to offer a guide, these are my configurations: Webserver: 1GB, 0.5vCPUScheduler: 2GB, 0.5vCPUFlower: 512MB, 0,25vCPUWorker: 3GB, 1vCPURedis: 2GB, 1vCPU Now click on Add container. A right panel is gonna pop up.Container name: container’s identifier name.Image: the ECR repository URL. Example: 1234567890.dkr.ecr.us-east-1.amazonaws.com/airflow-celery:latest. For Redis, use: docker.io/redis:5.0.5Port mappings: for the webserver write 8080. For flower, 5555. For the workers, 8793–to access the logs. For Redis, 6379. Under the ENVIRONMENT section, in Command, choose webserver , flower , worker or scheduler depending on which task you’re creating. You can also make use of environment variables! You can either use value to hardcode the env or use valueFrom to use Secrets Manager or AWS Parameter Store. But please, don’t inject secrets without security measures. More info here. For ALL services except flower, you MUST set POSTGRES_ variables, the ones we referenced in the entrypoint.sh remember? Without those, the services are going to fail miserably trying to connect to a non-existent database. For the scheduler and worker task definitions, you have to set REDIS_HOST. You can set either the IP or an internal DNS as I did here. We’re not setting user and password authentication, I don’t think it’s necessary since the service itself is private. Feel free to do so though. We’re officially done with the Task definition! Hang on, from now on it’s gonna be waaaaay easier. Go to your ECS cluster, in Services tab click on Create. Choose your corresponding task definition.Write the name of the service: webserver, scheduler, workers, etc.For webserver, Redis, flower and scheduler we should always have one task. For workers, we can have as many as we want, remember horizontal scaling?Click on Next. Choose your cluster’s VPC and whatever subnet you want to use.For security groups, just make sure of changing the name for something easier to identify. For instance: airflow-webserver-security-group. We’ll mess with these later.Public IP: remember the first architecture diagram? Well, unless you don’t wanna use a Load Balancer/Ingress, all services should be private.For the webserver and flower, we can add an Application Load Balancer to serve as an alternative for Elastic IPs. Why can’t we use EIPs? It’s not currently possible. To set a LB in AWS, reference here.Confirm and click Create!Repeat for every other service. Choose your corresponding task definition. Write the name of the service: webserver, scheduler, workers, etc. For webserver, Redis, flower and scheduler we should always have one task. For workers, we can have as many as we want, remember horizontal scaling? Click on Next. Choose your cluster’s VPC and whatever subnet you want to use. For security groups, just make sure of changing the name for something easier to identify. For instance: airflow-webserver-security-group. We’ll mess with these later. Public IP: remember the first architecture diagram? Well, unless you don’t wanna use a Load Balancer/Ingress, all services should be private. For the webserver and flower, we can add an Application Load Balancer to serve as an alternative for Elastic IPs. Why can’t we use EIPs? It’s not currently possible. To set a LB in AWS, reference here. Confirm and click Create! Repeat for every other service. After a while, all services should look like this. Don’t worry if some service is not working. We’ll sort out connections between all of them in the next section. What we should do now is ensure each service receives information from the corresponding sources. We’re going to set their security groups. A security group acts as a virtual firewall for your instance to control inbound and outbound traffic. When you launch an instance in a VPC, you can assign up to five security groups to the instance. Security groups act at the instance level, not the subnet level. Therefore, each instance in a subnet in your VPC can be assigned to a different set of security groups.–AWS Documentation Below is the official documentation of the Airflow Celery architecture: I’m going to borrow some lines from Airflow’s documentation: Airflow consist of several components:Workers - Execute the assigned tasksScheduler - Responsible for adding the necessary tasks to the queueWeb server - HTTP Server provides access to DAG/task status informationDatabase - Contains information about the status of tasks, DAGs, Variables, connections, etc.Celery - Queue mechanismThe components communicate with each other in many places[1] Web server –> Workers - Fetches task execution logs[2] Web server –> DAG files - Reveal the DAG structure[3] Web server –> Database - Fetch the status of the tasks[4] Workers –> DAG files - Reveal the DAG structure and execute the tasks[5] Workers –> Database - Gets and stores information about connection configuration, variables and XCOM.[6] Workers –> Celery’s result backend - Saves the status of tasks[7] Workers –> Celery’s broker - Stores commands for execution[8] Scheduler –> Database - Store a DAG run and related tasks[9] Scheduler –> DAG files - Reveal the DAG structure and execute the tasks[10] Scheduler –> Celery’s result backend - Gets information about the status of completed tasks[11] Scheduler –> Celery’s broker - Put the commands to be executed The above should be reflected in the security groups. Go to VPC service in AWS, select Security groups. In the setting up of all services, I asked you to identify them with an appropriate name, this is so you can filter them and provide the configurations easily. From here, select each group and set their correct Inbound Rules. Take for example Redis: Redis Server is running on port 6379 (the one we enabled in the task definition). The architecture diagram shows us that it should be accessible by the workers and the scheduler. We also include flower to check the broker status. Hence, we include rows for each source security group of those instances. Remember, follow the diagram and set all services’ security groups accordingly. This ensures that every connection between the services, that is supposed to be allowed, is. As you can see, the database should accept connections from every Airflow process. Testing is easy, just access the webserver and flower. Launch an example DAG and see in flower how the Active counter is increasing and decreasing fast when tasks are being executed. Don’t worry, if something’s not working, go check the logs of failing container tasks and do a little research, the solution should come up quickly. If you’re still having failures, there’s probably something you forgot to do (or that I forgot to tell you lol). Feel free to comment and I’ll do my best to help you! If everything’s going smooth... This is it! Your Airflow cluster is ready! I know I know...this was long and maybe even a little confusing, but hey! You managed to do it! 👏👏😄. This was a long trip for me, I went through a lot of problems, errors, exceptions setting up my own cluster. I really hope I helped you have fewer headaches with this guide. Until then, thank you and goodbye! 👋👋👋
[ { "code": null, "e": 418, "s": 172, "text": "Disclaimer: this post assumes basic knowledge of Airflow, AWS ECS, VPC (security groups, etc) and Docker. I suggest an architecture that may not be perfect nor the best in your particular case. In that case, make what you want from this lecture." }, { "code": null, "e": 691, "s": 418, "text": "Where I work, we use Apache Airflow extensively. We have approximately 15 DAGs, that may not seem like a lot, but some of them have many steps (tasks) that involve downloading big SQL backups, transforming some values using Python and re-uploading them into our warehouse." }, { "code": null, "e": 1010, "s": 691, "text": "At first, we started using the Sequential Executor (no parallelism, just 1 task running at a time) due to the easy setup and lack of many DAGs. As time went on, DAGs kept increasing and some of them presented the opportunity to make use of parallelism, so with some configurations, we started using the Local Executor." }, { "code": null, "e": 1068, "s": 1010, "text": "You may ask...Why the whole thing doesn’t cut it anymore?" }, { "code": null, "e": 1368, "s": 1068, "text": "Well, both cases had only 1 container deployed in AWS ECS doing everything: serving the web UI, scheduling the jobs and worker processes executing them. This wasn’t scalable, the only option we had was scaling vertically (you know, adding more vCPU, more RAM and such). There was not another option." }, { "code": null, "e": 1670, "s": 1368, "text": "Furthermore, if something in the container fails, the whole thing fails (no high availability). Also, the whole service must be public for the webserver to be accessible through the internet. If you want to make certain components private (such as the scheduler and workers) this is NOT possible here." }, { "code": null, "e": 2055, "s": 1670, "text": "There isn’t any guide talking about how to deploy Airflow in AWS, or making use of their extensive offer of services. It’s easy to deploy the whole thing locally using docker-compose or in an EC2, but is it really what you want? What about completely isolated nodes talking to each other inside the same VPC? Making private what needs to be private and public what needs to be public?" }, { "code": null, "e": 2228, "s": 2055, "text": "This whole diagram might be complicated at a first glance, and maybe even frightening but don’t worry. What you have to understand from this is probably just the following:" }, { "code": null, "e": 2493, "s": 2228, "text": "One can only connect to Airflow’s webserver or Flower (we’ll talk about Flower later) through an ingress. There’s no point of access from the outside to the scheduler, workers, Redis or even the metadata database. You don’t want connections from the outside there." }, { "code": null, "e": 2640, "s": 2493, "text": "Everything’s inside the same VPC, to make things easier. Every object has its security group, allowing connections only from the correct services." }, { "code": null, "e": 2714, "s": 2640, "text": "Everything is an AWS Fargate task, again, we’ll talk about Fargate later." }, { "code": null, "e": 2770, "s": 2714, "text": "Principally, AWS ECS and Fargate are the stars in this." }, { "code": null, "e": 3153, "s": 2770, "text": "Amazon Elastic Container Service (Amazon ECS) is a fully managed container orchestration service [...] You can choose to run your ECS clusters using AWS Fargate, which is serverless compute for containers. Fargate removes the need to provision and manage servers, lets you specify and pay for resources per application, and improves security through application isolation by design." }, { "code": null, "e": 3233, "s": 3153, "text": "A nice analogy about serverless computing is this one I read in this cool post:" }, { "code": null, "e": 3612, "s": 3233, "text": "Serverless computing is like driverless cars; there’s still a driver, just not one you can see. You don’t need to ask if the driver is hungry, tired, drunk or needs to stop for a bathroom break. If we ever let driverless cars drive on our roads it will be because we don’t have to care about the driver, just the fact that they will take us where we want to go — Mary Branscombe" }, { "code": null, "e": 3912, "s": 3612, "text": "I like to say that ECS is just a chill Kubernetes, without much to configure it’s ready to deploy your apps using just the Docker image and some extra settings–such as how much CPU or RAM you want your app to be able to use, if you want auto-scaling, use a Load Balancer out of the box and what-not." }, { "code": null, "e": 4003, "s": 3912, "text": "We should also set up a metadata database, for that we’re going to use the convenient RDS." }, { "code": null, "e": 4338, "s": 4003, "text": "Before anything else, we have to set which Docker image we’re gonna use and set it as a base image to build on top of it. For this, I’ve used Puckel’s Airflow. This docker image gives you all you need to set up Airflow in any of the 3 main executors. With over 5 million downloads, it’s safe to say that this guy has done a great job." }, { "code": null, "e": 4399, "s": 4338, "text": "Let’s create our custom Dockerfile. I’ve used the following:" }, { "code": null, "e": 4673, "s": 4399, "text": "I added a personal airflow.cfg (which has configurations for s3 logging and SMTP server credentials), a custom entrypoint.sh and a dags folder that has all my DAGs. In this case, . is already defined in the base image to be /usr/local/airflow using the instruction WORKDIR." }, { "code": null, "e": 4705, "s": 4673, "text": "My entrypoint is the following:" }, { "code": null, "e": 4928, "s": 4705, "text": "I got rid of some lines in the base image’s entrypoint that were conditions serving the different executors and just made it for Celery only, also getting rid of an annoying wait_for_port function that somehow didn’t work." }, { "code": null, "e": 5421, "s": 4928, "text": "What this whole thing does is first, sets up useful environment variables and then, depending on the command given in docker run, follows a switch that executes different portions of code. Let’s say, if you’re launching a worker, it’s going to install your Python requirements and then execute the worker process. If it’s the webserver, it’ll install requirements as well but also it’s going to initialize the database with airflow initdb command and then open the webserver for Airflow’s UI." }, { "code": null, "e": 5550, "s": 5421, "text": "If you want to test the whole thing and make sure everything works, you can do so with Puckel’s docker-compose celery YAML file." }, { "code": null, "e": 5943, "s": 5550, "text": "After a while, you should be able to access localhost:8080 and see Airflow’s dashboard. You might as well access localhost:5555 and see Flower as well. From this point, run some example DAGs–or even yours–and see for yourself how things are processed from a trigger in the webserver, the scheduler grabbing the task and sending it to queue, and finally, a worker picking it up and running it." }, { "code": null, "e": 6048, "s": 5943, "text": "For this tutorial, we’re going to keep it simple and use AWS ECR. ECR is just a Docker image repository." }, { "code": null, "e": 6091, "s": 6048, "text": "ECR is integrated with ECS out of the box." }, { "code": null, "e": 6391, "s": 6091, "text": "To create a repository, hop into the ECR console and click on Create repository and choose whatever name you feel adequate. Tip: you can have a repository for your staging Airflow and one for production. Remember, all Airflow processes are going to use the same image to avoid redundancy and be DRY." }, { "code": null, "e": 6667, "s": 6391, "text": "Now enter your new fresh repository and click on View push commands. That’ll walk you through pushing your Airflow image to the repo. If an error comes up during the first step, like unable to locate credentials you probably haven’t set your awscli credentials, look at this." }, { "code": null, "e": 6756, "s": 6667, "text": "Once you pushed the image and see it in the ECR console, you’re ready for the next step!" }, { "code": null, "e": 6827, "s": 6756, "text": "Let’s start by creating an ECS Cluster, go to Services and choose ECS." }, { "code": null, "e": 7018, "s": 6827, "text": "Probably as this is your first time, you’re gonna see a screen presenting the service to you and an easy first cluster button. What you need to do here is just create a Network Only cluster." }, { "code": null, "e": 7330, "s": 7018, "text": "At this point, you will probably have a window that looks like this. This right here is a matter of choice to you, whether you use the same VPC as the rest of your instances or create another one specifically for this cluster–I did the latter. If you choose to do that, I think just 1 subnet will be sufficient." }, { "code": null, "e": 7480, "s": 7330, "text": "We’re going to set up a PostgreSQL 9.6 micro instance database. If you’re familiar with how to do this, feel free to do it and skip to the next step." }, { "code": null, "e": 7882, "s": 7480, "text": "Go to Services -> RDS. Go to databases section and Create database. Select the PostgreSQL logo, go for Version 9.6.X, whatever minor version is fine. Now, I’m still deliberating on if I’m super cheap or the airflow metadata database doesn’t really need to be THAT robust, so I opted for a free tier micro instance. If you find that that isn’t enough for you, it’s easy to upgrade later so don’t worry." }, { "code": null, "e": 8036, "s": 7882, "text": "Next configurations are up to you, whatever instance name, username, password, just make sure it’s going to be created in the same cluster that ECS uses." }, { "code": null, "e": 8109, "s": 8036, "text": "Great, we have our empty cluster now. Let’s create our task definitions." }, { "code": null, "e": 8346, "s": 8109, "text": "Task definitions are like blueprints, they define how your service is going to be executed–which container is it going to use, how much CPU and RAM is assigned to it, which ports are mapped, what environment variables does it have, etc." }, { "code": null, "e": 8428, "s": 8346, "text": "Go to Task Definitions at the left panel and click in Create new Task Definition." }, { "code": null, "e": 8487, "s": 8428, "text": "Remember, we want Fargate, so select it and hit Next step." }, { "code": null, "e": 8590, "s": 8487, "text": "From now on, we’ll have to create a task definition for the webserver, the scheduler, and the workers." }, { "code": null, "e": 8696, "s": 8590, "text": "I’ll walk you through all the necessary configurations you must provide for every task to work correctly." }, { "code": null, "e": 9525, "s": 8696, "text": "Task Definition Name: identifier name. Choose something descriptive like airflow-webserver, airflow-worker, etc.Task Role: the IAM role the task is going to be injected in the container. Choose one that has permissions for what your task must do–extract secrets from secrets manager, log with awslogs log driver, query buckets from S3. If you’re not sure, just use the basic ecsTaskExecutionRole , if it’s not present in the dropdown check here.Network Mode: awsvpc since we’re using Fargate.Task execution role: the role that’s going to be able to pull the image from AWS ECR and log in Cloudwatch. ecsTaskExecutionRole has both these policies.Task size: almost completely depends on you. Most of your resources will on the workers, hence they’re gonna do all the dirty work. Just to offer a guide, these are my configurations:" }, { "code": null, "e": 9630, "s": 9525, "text": "Webserver: 1GB, 0.5vCPUScheduler: 2GB, 0.5vCPUFlower: 512MB, 0,25vCPUWorker: 3GB, 1vCPURedis: 2GB, 1vCPU" }, { "code": null, "e": 9997, "s": 9630, "text": "Now click on Add container. A right panel is gonna pop up.Container name: container’s identifier name.Image: the ECR repository URL. Example: 1234567890.dkr.ecr.us-east-1.amazonaws.com/airflow-celery:latest. For Redis, use: docker.io/redis:5.0.5Port mappings: for the webserver write 8080. For flower, 5555. For the workers, 8793–to access the logs. For Redis, 6379." }, { "code": null, "e": 10129, "s": 9997, "text": "Under the ENVIRONMENT section, in Command, choose webserver , flower , worker or scheduler depending on which task you’re creating." }, { "code": null, "e": 10362, "s": 10129, "text": "You can also make use of environment variables! You can either use value to hardcode the env or use valueFrom to use Secrets Manager or AWS Parameter Store. But please, don’t inject secrets without security measures. More info here." }, { "code": null, "e": 10584, "s": 10362, "text": "For ALL services except flower, you MUST set POSTGRES_ variables, the ones we referenced in the entrypoint.sh remember? Without those, the services are going to fail miserably trying to connect to a non-existent database." }, { "code": null, "e": 10864, "s": 10584, "text": "For the scheduler and worker task definitions, you have to set REDIS_HOST. You can set either the IP or an internal DNS as I did here. We’re not setting user and password authentication, I don’t think it’s necessary since the service itself is private. Feel free to do so though." }, { "code": null, "e": 10963, "s": 10864, "text": "We’re officially done with the Task definition! Hang on, from now on it’s gonna be waaaaay easier." }, { "code": null, "e": 11020, "s": 10963, "text": "Go to your ECS cluster, in Services tab click on Create." }, { "code": null, "e": 11919, "s": 11020, "text": "Choose your corresponding task definition.Write the name of the service: webserver, scheduler, workers, etc.For webserver, Redis, flower and scheduler we should always have one task. For workers, we can have as many as we want, remember horizontal scaling?Click on Next. Choose your cluster’s VPC and whatever subnet you want to use.For security groups, just make sure of changing the name for something easier to identify. For instance: airflow-webserver-security-group. We’ll mess with these later.Public IP: remember the first architecture diagram? Well, unless you don’t wanna use a Load Balancer/Ingress, all services should be private.For the webserver and flower, we can add an Application Load Balancer to serve as an alternative for Elastic IPs. Why can’t we use EIPs? It’s not currently possible. To set a LB in AWS, reference here.Confirm and click Create!Repeat for every other service." }, { "code": null, "e": 11962, "s": 11919, "text": "Choose your corresponding task definition." }, { "code": null, "e": 12029, "s": 11962, "text": "Write the name of the service: webserver, scheduler, workers, etc." }, { "code": null, "e": 12178, "s": 12029, "text": "For webserver, Redis, flower and scheduler we should always have one task. For workers, we can have as many as we want, remember horizontal scaling?" }, { "code": null, "e": 12256, "s": 12178, "text": "Click on Next. Choose your cluster’s VPC and whatever subnet you want to use." }, { "code": null, "e": 12424, "s": 12256, "text": "For security groups, just make sure of changing the name for something easier to identify. For instance: airflow-webserver-security-group. We’ll mess with these later." }, { "code": null, "e": 12566, "s": 12424, "text": "Public IP: remember the first architecture diagram? Well, unless you don’t wanna use a Load Balancer/Ingress, all services should be private." }, { "code": null, "e": 12768, "s": 12566, "text": "For the webserver and flower, we can add an Application Load Balancer to serve as an alternative for Elastic IPs. Why can’t we use EIPs? It’s not currently possible. To set a LB in AWS, reference here." }, { "code": null, "e": 12794, "s": 12768, "text": "Confirm and click Create!" }, { "code": null, "e": 12826, "s": 12794, "text": "Repeat for every other service." }, { "code": null, "e": 12989, "s": 12826, "text": "After a while, all services should look like this. Don’t worry if some service is not working. We’ll sort out connections between all of them in the next section." }, { "code": null, "e": 13129, "s": 12989, "text": "What we should do now is ensure each service receives information from the corresponding sources. We’re going to set their security groups." }, { "code": null, "e": 13516, "s": 13129, "text": "A security group acts as a virtual firewall for your instance to control inbound and outbound traffic. When you launch an instance in a VPC, you can assign up to five security groups to the instance. Security groups act at the instance level, not the subnet level. Therefore, each instance in a subnet in your VPC can be assigned to a different set of security groups.–AWS Documentation" }, { "code": null, "e": 13588, "s": 13516, "text": "Below is the official documentation of the Airflow Celery architecture:" }, { "code": null, "e": 13649, "s": 13588, "text": "I’m going to borrow some lines from Airflow’s documentation:" }, { "code": null, "e": 14808, "s": 13649, "text": "Airflow consist of several components:Workers - Execute the assigned tasksScheduler - Responsible for adding the necessary tasks to the queueWeb server - HTTP Server provides access to DAG/task status informationDatabase - Contains information about the status of tasks, DAGs, Variables, connections, etc.Celery - Queue mechanismThe components communicate with each other in many places[1] Web server –> Workers - Fetches task execution logs[2] Web server –> DAG files - Reveal the DAG structure[3] Web server –> Database - Fetch the status of the tasks[4] Workers –> DAG files - Reveal the DAG structure and execute the tasks[5] Workers –> Database - Gets and stores information about connection configuration, variables and XCOM.[6] Workers –> Celery’s result backend - Saves the status of tasks[7] Workers –> Celery’s broker - Stores commands for execution[8] Scheduler –> Database - Store a DAG run and related tasks[9] Scheduler –> DAG files - Reveal the DAG structure and execute the tasks[10] Scheduler –> Celery’s result backend - Gets information about the status of completed tasks[11] Scheduler –> Celery’s broker - Put the commands to be executed" }, { "code": null, "e": 14862, "s": 14808, "text": "The above should be reflected in the security groups." }, { "code": null, "e": 15072, "s": 14862, "text": "Go to VPC service in AWS, select Security groups. In the setting up of all services, I asked you to identify them with an appropriate name, this is so you can filter them and provide the configurations easily." }, { "code": null, "e": 15162, "s": 15072, "text": "From here, select each group and set their correct Inbound Rules. Take for example Redis:" }, { "code": null, "e": 15466, "s": 15162, "text": "Redis Server is running on port 6379 (the one we enabled in the task definition). The architecture diagram shows us that it should be accessible by the workers and the scheduler. We also include flower to check the broker status. Hence, we include rows for each source security group of those instances." }, { "code": null, "e": 15722, "s": 15466, "text": "Remember, follow the diagram and set all services’ security groups accordingly. This ensures that every connection between the services, that is supposed to be allowed, is. As you can see, the database should accept connections from every Airflow process." }, { "code": null, "e": 15905, "s": 15722, "text": "Testing is easy, just access the webserver and flower. Launch an example DAG and see in flower how the Active counter is increasing and decreasing fast when tasks are being executed." }, { "code": null, "e": 16054, "s": 15905, "text": "Don’t worry, if something’s not working, go check the logs of failing container tasks and do a little research, the solution should come up quickly." }, { "code": null, "e": 16221, "s": 16054, "text": "If you’re still having failures, there’s probably something you forgot to do (or that I forgot to tell you lol). Feel free to comment and I’ll do my best to help you!" }, { "code": null, "e": 16253, "s": 16221, "text": "If everything’s going smooth..." }, { "code": null, "e": 16397, "s": 16253, "text": "This is it! Your Airflow cluster is ready! I know I know...this was long and maybe even a little confusing, but hey! You managed to do it! 👏👏😄." }, { "code": null, "e": 16571, "s": 16397, "text": "This was a long trip for me, I went through a lot of problems, errors, exceptions setting up my own cluster. I really hope I helped you have fewer headaches with this guide." } ]
Bubble chart using Plotly in Python - GeeksforGeeks
03 Jul, 2020 Plotly is a Python library which is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. Plotly is an interactive visualization library. The bubble chart in Plotly is created using the scatter plot. It can be created using the scatter() method of plotly.express. A bubble chart is a data visualization which helps to displays multiple circles (bubbles) in a two-dimensional plot as same in scatter plot. A bubble chart is primarily used to depict and show relationships between numeric variables. Example: Python3 import plotly.express as px df = px.data.iris() fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", size='petal_length', hover_data=['petal_width']) fig.show() Output: Marker size and color are used to control the overall size of the marker. Marker size helps to maintain the color inside the bubble in the graph. Scatter is used to actually scale the marker sizes and color based on data. Example: Python3 import plotly.graph_objects as pximport numpy as np # creating random data through randomint # function of numpy.random np.random.seed(42) random_x= np.random.randint(1,101,100) random_y= np.random.randint(1,101,100) plot = px.Figure(data=[px.Scatter( x = random_x, y = random_y, mode = 'markers', marker_size = [115, 20, 30])]) plot.show() Output: To scale the bubble size,use the parameter sizeref. To calculate the values of sizeref use: sizeref = 2. * max(array of size values) / (desired maximum marker size ** 2) Example: Python3 import plotly.graph_objects as pximport numpy as np # creating random data through randomint # function of numpy.random np.random.seed(42) random_x= np.random.randint(1,101,100) random_y= np.random.randint(1,101,100) size = [20, 40, 60, 80, 100, 80, 60, 40, 20, 40] plot = px.Figure(data=[px.Scatter( x = random_x, y = random_y, mode = 'markers', marker=dict( size=size, sizemode='area', sizeref=2.*max(size)/(40.**2), sizemin=4 ))]) plot.show() Output: The color scale is a specialized label which helps to displays a color map with its scale, the color scale is used to display a color palette and its numerical scale for color mapped. Example: Python3 import plotly.graph_objects as pximport numpy as np # creating random data through randomint # function of numpy.random np.random.seed(42) random_x= np.random.randint(1,101,100) random_y= np.random.randint(1,101,100) plot = px.Figure(data=[px.Scatter( x = random_x, y = random_y, mode = 'markers', marker=dict( color = [10, 20, 30, 50], size = [10, 30, 50, 80], showscale=True ))]) plot.show() Output: Python-Plotly Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Python Dictionary Taking input in Python Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python
[ { "code": null, "e": 23677, "s": 23649, "text": "\n03 Jul, 2020" }, { "code": null, "e": 23980, "s": 23677, "text": "Plotly is a Python library which is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. Plotly is an interactive visualization library." }, { "code": null, "e": 24340, "s": 23980, "text": "The bubble chart in Plotly is created using the scatter plot. It can be created using the scatter() method of plotly.express. A bubble chart is a data visualization which helps to displays multiple circles (bubbles) in a two-dimensional plot as same in scatter plot. A bubble chart is primarily used to depict and show relationships between numeric variables." }, { "code": null, "e": 24349, "s": 24340, "text": "Example:" }, { "code": null, "e": 24357, "s": 24349, "text": "Python3" }, { "code": "import plotly.express as px df = px.data.iris() fig = px.scatter(df, x=\"sepal_width\", y=\"sepal_length\", color=\"species\", size='petal_length', hover_data=['petal_width']) fig.show()", "e": 24590, "s": 24357, "text": null }, { "code": null, "e": 24598, "s": 24590, "text": "Output:" }, { "code": null, "e": 24820, "s": 24598, "text": "Marker size and color are used to control the overall size of the marker. Marker size helps to maintain the color inside the bubble in the graph. Scatter is used to actually scale the marker sizes and color based on data." }, { "code": null, "e": 24829, "s": 24820, "text": "Example:" }, { "code": null, "e": 24837, "s": 24829, "text": "Python3" }, { "code": "import plotly.graph_objects as pximport numpy as np # creating random data through randomint # function of numpy.random np.random.seed(42) random_x= np.random.randint(1,101,100) random_y= np.random.randint(1,101,100) plot = px.Figure(data=[px.Scatter( x = random_x, y = random_y, mode = 'markers', marker_size = [115, 20, 30])]) plot.show()", "e": 25213, "s": 24837, "text": null }, { "code": null, "e": 25221, "s": 25213, "text": "Output:" }, { "code": null, "e": 25313, "s": 25221, "text": "To scale the bubble size,use the parameter sizeref. To calculate the values of sizeref use:" }, { "code": null, "e": 25391, "s": 25313, "text": "sizeref = 2. * max(array of size values) / (desired maximum marker size ** 2)" }, { "code": null, "e": 25400, "s": 25391, "text": "Example:" }, { "code": null, "e": 25408, "s": 25400, "text": "Python3" }, { "code": "import plotly.graph_objects as pximport numpy as np # creating random data through randomint # function of numpy.random np.random.seed(42) random_x= np.random.randint(1,101,100) random_y= np.random.randint(1,101,100) size = [20, 40, 60, 80, 100, 80, 60, 40, 20, 40] plot = px.Figure(data=[px.Scatter( x = random_x, y = random_y, mode = 'markers', marker=dict( size=size, sizemode='area', sizeref=2.*max(size)/(40.**2), sizemin=4 ))]) plot.show()", "e": 25921, "s": 25408, "text": null }, { "code": null, "e": 25929, "s": 25921, "text": "Output:" }, { "code": null, "e": 26113, "s": 25929, "text": "The color scale is a specialized label which helps to displays a color map with its scale, the color scale is used to display a color palette and its numerical scale for color mapped." }, { "code": null, "e": 26122, "s": 26113, "text": "Example:" }, { "code": null, "e": 26130, "s": 26122, "text": "Python3" }, { "code": "import plotly.graph_objects as pximport numpy as np # creating random data through randomint # function of numpy.random np.random.seed(42) random_x= np.random.randint(1,101,100) random_y= np.random.randint(1,101,100) plot = px.Figure(data=[px.Scatter( x = random_x, y = random_y, mode = 'markers', marker=dict( color = [10, 20, 30, 50], size = [10, 30, 50, 80], showscale=True ))]) plot.show()", "e": 26583, "s": 26130, "text": null }, { "code": null, "e": 26591, "s": 26583, "text": "Output:" }, { "code": null, "e": 26605, "s": 26591, "text": "Python-Plotly" }, { "code": null, "e": 26612, "s": 26605, "text": "Python" }, { "code": null, "e": 26710, "s": 26612, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26719, "s": 26710, "text": "Comments" }, { "code": null, "e": 26732, "s": 26719, "text": "Old Comments" }, { "code": null, "e": 26760, "s": 26732, "text": "Read JSON file using Python" }, { "code": null, "e": 26810, "s": 26760, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 26832, "s": 26810, "text": "Python map() function" }, { "code": null, "e": 26876, "s": 26832, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 26894, "s": 26876, "text": "Python Dictionary" }, { "code": null, "e": 26917, "s": 26894, "text": "Taking input in Python" }, { "code": null, "e": 26952, "s": 26917, "text": "Read a file line by line in Python" }, { "code": null, "e": 26974, "s": 26952, "text": "Enumerate() in Python" }, { "code": null, "e": 27006, "s": 26974, "text": "How to Install PIP on Windows ?" } ]
Java.io.ByteArrayOutputStream() Class in Java
23 Jan, 2017 java.io.ByteArrayOutputStream class creates an Output Stream for writing data into byte array. The size of buffer grows automatically as data is written to it. There is no affect of closing the byteArrayOutputStream on the working of it’s methods. They can be called even after closing the class.Thus, no methods throws IO exception. Declaration: public class ByteArrayOutputStream extends OutputStream Fields: protected byte[] buf – The buffer where data is stored. protected int count – The number of valid bytes in the buffer. Constructors : ByteArrayOutputStream() : creates a new ByteArrayOutputStream to write bytes ByteArrayOutputStream(int buffersize) : creates a new ByteArrayOutputStream with buferrsize to write bytes. Methods: write(int byte) : java.io.ByteArrayOutputStream.write(int byte) writes specified byte to the Output Stream.Syntax :public void write(int byte) Parameters : byte : byte to be written Return : void public void write(int byte) Parameters : byte : byte to be written Return : void write(byte[] buffer, int offset, int maxlen) : java.io.ByteArrayOutputStream.write(byte[] buffer, int offset, int maxlen) writes maxlen bytes of the data from buffer to the Output Stream. It converts the stream’s contents using the specified charsetName(A named mapping between sequences of sixteen-bit Unicode code units and sequences of bytes.)Syntax :public void write(byte[] buffer, int offset, int maxlen) Parameters : buffer : data of the buffer offset : starting in the destination array - 'buffer'. maxlen : maximum length of array to be read Return : void public void write(byte[] buffer, int offset, int maxlen) Parameters : buffer : data of the buffer offset : starting in the destination array - 'buffer'. maxlen : maximum length of array to be read Return : void toByteArray() : java.io.ByteArrayOutputStream.toByteArray() creates a new byte array having the same as that of Output StreamSyntax :public byte[] toByteArray() Parameters : ---------- Return : new byte array having the same as that of Output Stream Java Program explaining the use of write(byte[] buffer, int offset, int maxlen) and toByteArray() methods :// Java program illustrating the working of ByteArrayOutputStream// write(byte[] buffer, int offset, int maxlen), toByteArray() import java.io.*;public class NewClass{ public static void main(String[] args) throws IOException { ByteArrayOutputStream geek_output = new ByteArrayOutputStream(); byte[] buffer = {'J', 'A', 'V', 'A'}; // Use of write(byte[] buffer, int offset, int maxlen) geek_output.write(buffer, 0, 4); System.out.print("Use of write(buffer, offset, maxlen) by toByteArray() : "); // Use of toByteArray() : for (byte b: geek_output.toByteArray()) { System.out.print(" " + b); } }}Output :Use of write(buffer, offset, maxlen) by toByteArray() : 74 65 86 65 public byte[] toByteArray() Parameters : ---------- Return : new byte array having the same as that of Output Stream Java Program explaining the use of write(byte[] buffer, int offset, int maxlen) and toByteArray() methods : // Java program illustrating the working of ByteArrayOutputStream// write(byte[] buffer, int offset, int maxlen), toByteArray() import java.io.*;public class NewClass{ public static void main(String[] args) throws IOException { ByteArrayOutputStream geek_output = new ByteArrayOutputStream(); byte[] buffer = {'J', 'A', 'V', 'A'}; // Use of write(byte[] buffer, int offset, int maxlen) geek_output.write(buffer, 0, 4); System.out.print("Use of write(buffer, offset, maxlen) by toByteArray() : "); // Use of toByteArray() : for (byte b: geek_output.toByteArray()) { System.out.print(" " + b); } }} Output : Use of write(buffer, offset, maxlen) by toByteArray() : 74 65 86 65 close() : java.io.ByteArrayOutputStream.close() closes the Output Stream and releases the allocated resources.Syntax :public void close() Parameters : -------------- Return : void public void close() Parameters : -------------- Return : void size() : java.io.ByteArrayOutputStream.size() returns the size of buffer present inside the Output Stream.Syntax :public int size() Parameters : -------------- Return : size of buffer present inside the Output Stream. public int size() Parameters : -------------- Return : size of buffer present inside the Output Stream. reset() : java.io.ByteArrayOutputStream.reset() resets the complete stream count to zero and will help the Stream to start as freshSyntax : public void reset() Parameters : -------------- Return : void. public void reset() Parameters : -------------- Return : void. toString() : java.io.ByteArrayOutputStream.toStrign() convert the content of Output Stream to platform’s default Character setSyntax : public String toString() Parameters : -------------- Return : the content of Output Stream by converting it to platform's default Character set public String toString() Parameters : -------------- Return : the content of Output Stream by converting it to platform's default Character set toString(String charsetName) : java.io.ByteArrayOutputStream.toStrign(String charsetName) convert the content of Output Stream to platform’s specified Character setSyntax : public String toString(String charsetName) Parameters : -------------- Return : the content of Output Stream by converting it to platform's default Character set Java Program illustrating the use ByteArrayOutputStream class methods :// Java program illustrating the working of ByteArrayOutputStream// write(), size(), toString(String charsetName),// close(), toString(), reset() import java.io.*;public class NewClass{ public static void main(String[] args) throws IOException { ByteArrayOutputStream geek_output = new ByteArrayOutputStream(); byte[] buffer = {'J', 'A', 'V', 'A'}; for (byte a : buffer) { // Use of write(int byte) : geek_output.write(a); } // Use of size() : int size = geek_output.size(); System.out.println("Use of size() : " + size); // Use of reset() : System.out.println("Use of reset()"); // USe of toString() : String geek = geek_output.toString(); System.out.println("Use of toString() : "+ geek); // Use of toString(String charsetName) String geek1 = geek_output.toString("UTF-8"); System.out.println("Use of toString(String charsetName) : "+ geek1); // Closing the stream geek_output.close(); }}Output :Use of size() : 4 Use of reset() Use of toString() : JAVA Use of toString(String charsetName) : JAVA public String toString(String charsetName) Parameters : -------------- Return : the content of Output Stream by converting it to platform's default Character set Java Program illustrating the use ByteArrayOutputStream class methods : // Java program illustrating the working of ByteArrayOutputStream// write(), size(), toString(String charsetName),// close(), toString(), reset() import java.io.*;public class NewClass{ public static void main(String[] args) throws IOException { ByteArrayOutputStream geek_output = new ByteArrayOutputStream(); byte[] buffer = {'J', 'A', 'V', 'A'}; for (byte a : buffer) { // Use of write(int byte) : geek_output.write(a); } // Use of size() : int size = geek_output.size(); System.out.println("Use of size() : " + size); // Use of reset() : System.out.println("Use of reset()"); // USe of toString() : String geek = geek_output.toString(); System.out.println("Use of toString() : "+ geek); // Use of toString(String charsetName) String geek1 = geek_output.toString("UTF-8"); System.out.println("Use of toString(String charsetName) : "+ geek1); // Closing the stream geek_output.close(); }} Output : Use of size() : 4 Use of reset() Use of toString() : JAVA Use of toString(String charsetName) : JAVA Next Article: io.ByteArrayInputStream class in JavaThis article is contributed by Mohit Gupta . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Java-I/O 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": "\n23 Jan, 2017" }, { "code": null, "e": 362, "s": 28, "text": "java.io.ByteArrayOutputStream class creates an Output Stream for writing data into byte array. The size of buffer grows automatically as data is written to it. There is no affect of closing the byteArrayOutputStream on the working of it’s methods. They can be called even after closing the class.Thus, no methods throws IO exception." }, { "code": null, "e": 375, "s": 362, "text": "Declaration:" }, { "code": null, "e": 434, "s": 375, "text": "public class ByteArrayOutputStream\n extends OutputStream" }, { "code": null, "e": 442, "s": 434, "text": "Fields:" }, { "code": null, "e": 498, "s": 442, "text": "protected byte[] buf – The buffer where data is stored." }, { "code": null, "e": 561, "s": 498, "text": "protected int count – The number of valid bytes in the buffer." }, { "code": null, "e": 576, "s": 561, "text": "Constructors :" }, { "code": null, "e": 653, "s": 576, "text": "ByteArrayOutputStream() : creates a new ByteArrayOutputStream to write bytes" }, { "code": null, "e": 761, "s": 653, "text": "ByteArrayOutputStream(int buffersize) : creates a new ByteArrayOutputStream with buferrsize to write bytes." }, { "code": null, "e": 770, "s": 761, "text": "Methods:" }, { "code": null, "e": 1015, "s": 770, "text": "write(int byte) : java.io.ByteArrayOutputStream.write(int byte) writes specified byte to the Output Stream.Syntax :public void write(int byte)\nParameters : \nbyte : byte to be written\nReturn : \nvoid\n" }, { "code": null, "e": 1145, "s": 1015, "text": "public void write(int byte)\nParameters : \nbyte : byte to be written\nReturn : \nvoid\n" }, { "code": null, "e": 1759, "s": 1145, "text": "write(byte[] buffer, int offset, int maxlen) : java.io.ByteArrayOutputStream.write(byte[] buffer, int offset, int maxlen) writes maxlen bytes of the data from buffer to the Output Stream. It converts the stream’s contents using the specified charsetName(A named mapping between sequences of sixteen-bit Unicode code units and sequences of bytes.)Syntax :public void write(byte[] buffer, int offset, int maxlen)\nParameters : \nbuffer : data of the buffer\noffset : starting in the destination array - 'buffer'.\nmaxlen : maximum length of array to be read\nReturn : \nvoid\n" }, { "code": null, "e": 2019, "s": 1759, "text": "public void write(byte[] buffer, int offset, int maxlen)\nParameters : \nbuffer : data of the buffer\noffset : starting in the destination array - 'buffer'.\nmaxlen : maximum length of array to be read\nReturn : \nvoid\n" }, { "code": null, "e": 3187, "s": 2019, "text": "toByteArray() : java.io.ByteArrayOutputStream.toByteArray() creates a new byte array having the same as that of Output StreamSyntax :public byte[] toByteArray()\nParameters : \n----------\nReturn : \nnew byte array having the same as that of Output Stream\nJava Program explaining the use of write(byte[] buffer, int offset, int maxlen) and toByteArray() methods :// Java program illustrating the working of ByteArrayOutputStream// write(byte[] buffer, int offset, int maxlen), toByteArray() import java.io.*;public class NewClass{ public static void main(String[] args) throws IOException { ByteArrayOutputStream geek_output = new ByteArrayOutputStream(); byte[] buffer = {'J', 'A', 'V', 'A'}; // Use of write(byte[] buffer, int offset, int maxlen) geek_output.write(buffer, 0, 4); System.out.print(\"Use of write(buffer, offset, maxlen) by toByteArray() : \"); // Use of toByteArray() : for (byte b: geek_output.toByteArray()) { System.out.print(\" \" + b); } }}Output :Use of write(buffer, offset, maxlen) by toByteArray() : 74 65 86 65" }, { "code": null, "e": 3353, "s": 3187, "text": "public byte[] toByteArray()\nParameters : \n----------\nReturn : \nnew byte array having the same as that of Output Stream\n" }, { "code": null, "e": 3461, "s": 3353, "text": "Java Program explaining the use of write(byte[] buffer, int offset, int maxlen) and toByteArray() methods :" }, { "code": "// Java program illustrating the working of ByteArrayOutputStream// write(byte[] buffer, int offset, int maxlen), toByteArray() import java.io.*;public class NewClass{ public static void main(String[] args) throws IOException { ByteArrayOutputStream geek_output = new ByteArrayOutputStream(); byte[] buffer = {'J', 'A', 'V', 'A'}; // Use of write(byte[] buffer, int offset, int maxlen) geek_output.write(buffer, 0, 4); System.out.print(\"Use of write(buffer, offset, maxlen) by toByteArray() : \"); // Use of toByteArray() : for (byte b: geek_output.toByteArray()) { System.out.print(\" \" + b); } }}", "e": 4148, "s": 3461, "text": null }, { "code": null, "e": 4157, "s": 4148, "text": "Output :" }, { "code": null, "e": 4226, "s": 4157, "text": "Use of write(buffer, offset, maxlen) by toByteArray() : 74 65 86 65" }, { "code": null, "e": 4455, "s": 4226, "text": "close() : java.io.ByteArrayOutputStream.close() closes the Output Stream and releases the allocated resources.Syntax :public void close()\nParameters : \n--------------\nReturn : \nvoid\n" }, { "code": null, "e": 4566, "s": 4455, "text": "public void close()\nParameters : \n--------------\nReturn : \nvoid\n" }, { "code": null, "e": 4834, "s": 4566, "text": "size() : java.io.ByteArrayOutputStream.size() returns the size of buffer present inside the Output Stream.Syntax :public int size()\nParameters : \n--------------\nReturn : \nsize of buffer present inside the Output Stream. \n" }, { "code": null, "e": 4988, "s": 4834, "text": "public int size()\nParameters : \n--------------\nReturn : \nsize of buffer present inside the Output Stream. \n" }, { "code": null, "e": 5242, "s": 4988, "text": "reset() : java.io.ByteArrayOutputStream.reset() resets the complete stream count to zero and will help the Stream to start as freshSyntax : \npublic void reset()\nParameters : \n--------------\nReturn : \nvoid. \n" }, { "code": null, "e": 5357, "s": 5242, "text": " \npublic void reset()\nParameters : \n--------------\nReturn : \nvoid. \n" }, { "code": null, "e": 5686, "s": 5357, "text": "toString() : java.io.ByteArrayOutputStream.toStrign() convert the content of Output Stream to platform’s default Character setSyntax : \npublic String toString()\nParameters : \n--------------\nReturn : \nthe content of Output Stream by converting it to platform's default Character set\n" }, { "code": null, "e": 5881, "s": 5686, "text": " \npublic String toString()\nParameters : \n--------------\nReturn : \nthe content of Output Stream by converting it to platform's default Character set\n" }, { "code": null, "e": 7517, "s": 5881, "text": "toString(String charsetName) : java.io.ByteArrayOutputStream.toStrign(String charsetName) convert the content of Output Stream to platform’s specified Character setSyntax : \npublic String toString(String charsetName)\nParameters : \n--------------\nReturn : \nthe content of Output Stream by converting it to platform's default Character set\nJava Program illustrating the use ByteArrayOutputStream class methods :// Java program illustrating the working of ByteArrayOutputStream// write(), size(), toString(String charsetName),// close(), toString(), reset() import java.io.*;public class NewClass{ public static void main(String[] args) throws IOException { ByteArrayOutputStream geek_output = new ByteArrayOutputStream(); byte[] buffer = {'J', 'A', 'V', 'A'}; for (byte a : buffer) { // Use of write(int byte) : geek_output.write(a); } // Use of size() : int size = geek_output.size(); System.out.println(\"Use of size() : \" + size); // Use of reset() : System.out.println(\"Use of reset()\"); // USe of toString() : String geek = geek_output.toString(); System.out.println(\"Use of toString() : \"+ geek); // Use of toString(String charsetName) String geek1 = geek_output.toString(\"UTF-8\"); System.out.println(\"Use of toString(String charsetName) : \"+ geek1); // Closing the stream geek_output.close(); }}Output :Use of size() : 4\nUse of reset()\nUse of toString() : JAVA\nUse of toString(String charsetName) : JAVA" }, { "code": null, "e": 7730, "s": 7517, "text": " \npublic String toString(String charsetName)\nParameters : \n--------------\nReturn : \nthe content of Output Stream by converting it to platform's default Character set\n" }, { "code": null, "e": 7802, "s": 7730, "text": "Java Program illustrating the use ByteArrayOutputStream class methods :" }, { "code": "// Java program illustrating the working of ByteArrayOutputStream// write(), size(), toString(String charsetName),// close(), toString(), reset() import java.io.*;public class NewClass{ public static void main(String[] args) throws IOException { ByteArrayOutputStream geek_output = new ByteArrayOutputStream(); byte[] buffer = {'J', 'A', 'V', 'A'}; for (byte a : buffer) { // Use of write(int byte) : geek_output.write(a); } // Use of size() : int size = geek_output.size(); System.out.println(\"Use of size() : \" + size); // Use of reset() : System.out.println(\"Use of reset()\"); // USe of toString() : String geek = geek_output.toString(); System.out.println(\"Use of toString() : \"+ geek); // Use of toString(String charsetName) String geek1 = geek_output.toString(\"UTF-8\"); System.out.println(\"Use of toString(String charsetName) : \"+ geek1); // Closing the stream geek_output.close(); }}", "e": 8875, "s": 7802, "text": null }, { "code": null, "e": 8884, "s": 8875, "text": "Output :" }, { "code": null, "e": 8985, "s": 8884, "text": "Use of size() : 4\nUse of reset()\nUse of toString() : JAVA\nUse of toString(String charsetName) : JAVA" }, { "code": null, "e": 9336, "s": 8985, "text": "Next Article: io.ByteArrayInputStream class in JavaThis article is contributed by Mohit Gupta . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 9461, "s": 9336, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 9470, "s": 9461, "text": "Java-I/O" }, { "code": null, "e": 9475, "s": 9470, "text": "Java" }, { "code": null, "e": 9480, "s": 9475, "text": "Java" } ]
Capacity of a channel in Computer Network
07 Apr, 2020 By capacity of a channel, it means the capacity of the transmission medium (wire or link). Capacity is the number of bits the transmission medium can hold. So basically there are 2 types of channels – Full duplex and half duplex. Half duplex – the transmission can happen in one direction at a time.Full duplex – the transmission can happen in both the direction simultaneously. Half duplex – the transmission can happen in one direction at a time. Full duplex – the transmission can happen in both the direction simultaneously. For example, the transmission medium is operating in its maximum capacity then at that time the number of bits it is holding is called capacity of the transmission medium. But how can we find the capacity mathematically? If the length of the transmission medium is longer then its capacity will be higher. It also depends on the area of cross section of the medium. If the bandwidth is 1 bps, then every second it can take 1 bit. After every second it will move forward so that next bit could occupy the space. Therefore the final time in which it will occupy all the bits will be its propagation delay. The capacity of the channel depends on two things: BandwidthPropagation delay Bandwidth Propagation delay Capacity = bandwidth * propagation delay (in case of half duplex) Capacity =2* bandwidth * propagation delay (in case of full duplex) Computer Networks GATE CS Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Wireless Application Protocol Mobile Internet Protocol (or Mobile IP) GSM in Wireless Communication Difference between MANET and VANET Introduction of Mobile Ad hoc Network (MANET) ACID Properties in DBMS Types of Operating Systems Normal Forms in DBMS Page Replacement Algorithms in Operating Systems Inter Process Communication (IPC)
[ { "code": null, "e": 53, "s": 25, "text": "\n07 Apr, 2020" }, { "code": null, "e": 283, "s": 53, "text": "By capacity of a channel, it means the capacity of the transmission medium (wire or link). Capacity is the number of bits the transmission medium can hold. So basically there are 2 types of channels – Full duplex and half duplex." }, { "code": null, "e": 432, "s": 283, "text": "Half duplex – the transmission can happen in one direction at a time.Full duplex – the transmission can happen in both the direction simultaneously." }, { "code": null, "e": 502, "s": 432, "text": "Half duplex – the transmission can happen in one direction at a time." }, { "code": null, "e": 582, "s": 502, "text": "Full duplex – the transmission can happen in both the direction simultaneously." }, { "code": null, "e": 754, "s": 582, "text": "For example, the transmission medium is operating in its maximum capacity then at that time the number of bits it is holding is called capacity of the transmission medium." }, { "code": null, "e": 803, "s": 754, "text": "But how can we find the capacity mathematically?" }, { "code": null, "e": 888, "s": 803, "text": "If the length of the transmission medium is longer then its capacity will be higher." }, { "code": null, "e": 948, "s": 888, "text": "It also depends on the area of cross section of the medium." }, { "code": null, "e": 1186, "s": 948, "text": "If the bandwidth is 1 bps, then every second it can take 1 bit. After every second it will move forward so that next bit could occupy the space. Therefore the final time in which it will occupy all the bits will be its propagation delay." }, { "code": null, "e": 1237, "s": 1186, "text": "The capacity of the channel depends on two things:" }, { "code": null, "e": 1264, "s": 1237, "text": "BandwidthPropagation delay" }, { "code": null, "e": 1274, "s": 1264, "text": "Bandwidth" }, { "code": null, "e": 1292, "s": 1274, "text": "Propagation delay" }, { "code": null, "e": 1430, "s": 1292, "text": "Capacity = bandwidth * propagation delay \n(in case of half duplex)\n\nCapacity =2* bandwidth * propagation delay \n(in case of full duplex) " }, { "code": null, "e": 1448, "s": 1430, "text": "Computer Networks" }, { "code": null, "e": 1456, "s": 1448, "text": "GATE CS" }, { "code": null, "e": 1474, "s": 1456, "text": "Computer Networks" }, { "code": null, "e": 1572, "s": 1474, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1602, "s": 1572, "text": "Wireless Application Protocol" }, { "code": null, "e": 1642, "s": 1602, "text": "Mobile Internet Protocol (or Mobile IP)" }, { "code": null, "e": 1672, "s": 1642, "text": "GSM in Wireless Communication" }, { "code": null, "e": 1707, "s": 1672, "text": "Difference between MANET and VANET" }, { "code": null, "e": 1753, "s": 1707, "text": "Introduction of Mobile Ad hoc Network (MANET)" }, { "code": null, "e": 1777, "s": 1753, "text": "ACID Properties in DBMS" }, { "code": null, "e": 1804, "s": 1777, "text": "Types of Operating Systems" }, { "code": null, "e": 1825, "s": 1804, "text": "Normal Forms in DBMS" }, { "code": null, "e": 1874, "s": 1825, "text": "Page Replacement Algorithms in Operating Systems" } ]
Python | Ways to sort a zipped list by values
17 Oct, 2019 Zipped lists are those lists where several lists are mapped together to form one list which can be used as one entity altogether. In Python Zip() function is used to map different lists. Let’s discuss a few methods to demonstrate the problem. Method #1: Using lambda and sort # Python code to demonstrate# sort zipped list by values# using lambda and sorted # Declaring initial listslist1 = ['geeks', 'for', 'Geeks']list2 = [3, 2, 1]zipped = zip(list1, list2) # Converting to listzipped = list(zipped) # Printing zipped listprint("Initial zipped list - ", str(zipped)) # Using sorted and lambdares = sorted(zipped, key = lambda x: x[1]) # printing resultprint("final list - ", str(res)) Initial zipped list - [('geeks', 3), ('for', 2), ('Geeks', 1)] final list - [('Geeks', 1), ('for', 2), ('geeks', 3)] Method #2: Using operator and sort # Python code to demonstrate# sort zipped list by values# using operator and sorted import operator# Declaring initial listslist1 = ['akshat', 'Manjeet', 'nikhil']list2 = [3, 2, 1]zipped = zip(list1, list2) # Converting to listzipped = list(zipped) # Printing zipped listprint("Initial zipped list - ", str(zipped)) # Using sorted and operatorres = sorted(zipped, key = operator.itemgetter(1)) # printing resultprint("final list - ", str(res)) Initial zipped list - [('akshat', 3), ('Manjeet', 2), ('nikhil', 1)] final list - [('nikhil', 1), ('Manjeet', 2), ('akshat', 3)] nidhi_biet Python list-programs python-list Python Python Programs python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Oct, 2019" }, { "code": null, "e": 215, "s": 28, "text": "Zipped lists are those lists where several lists are mapped together to form one list which can be used as one entity altogether. In Python Zip() function is used to map different lists." }, { "code": null, "e": 271, "s": 215, "text": "Let’s discuss a few methods to demonstrate the problem." }, { "code": null, "e": 304, "s": 271, "text": "Method #1: Using lambda and sort" }, { "code": "# Python code to demonstrate# sort zipped list by values# using lambda and sorted # Declaring initial listslist1 = ['geeks', 'for', 'Geeks']list2 = [3, 2, 1]zipped = zip(list1, list2) # Converting to listzipped = list(zipped) # Printing zipped listprint(\"Initial zipped list - \", str(zipped)) # Using sorted and lambdares = sorted(zipped, key = lambda x: x[1]) # printing resultprint(\"final list - \", str(res))", "e": 724, "s": 304, "text": null }, { "code": null, "e": 844, "s": 724, "text": "Initial zipped list - [('geeks', 3), ('for', 2), ('Geeks', 1)]\nfinal list - [('Geeks', 1), ('for', 2), ('geeks', 3)]\n" }, { "code": null, "e": 880, "s": 844, "text": " Method #2: Using operator and sort" }, { "code": "# Python code to demonstrate# sort zipped list by values# using operator and sorted import operator# Declaring initial listslist1 = ['akshat', 'Manjeet', 'nikhil']list2 = [3, 2, 1]zipped = zip(list1, list2) # Converting to listzipped = list(zipped) # Printing zipped listprint(\"Initial zipped list - \", str(zipped)) # Using sorted and operatorres = sorted(zipped, key = operator.itemgetter(1)) # printing resultprint(\"final list - \", str(res))", "e": 1333, "s": 880, "text": null }, { "code": null, "e": 1465, "s": 1333, "text": "Initial zipped list - [('akshat', 3), ('Manjeet', 2), ('nikhil', 1)]\nfinal list - [('nikhil', 1), ('Manjeet', 2), ('akshat', 3)]\n" }, { "code": null, "e": 1476, "s": 1465, "text": "nidhi_biet" }, { "code": null, "e": 1497, "s": 1476, "text": "Python list-programs" }, { "code": null, "e": 1509, "s": 1497, "text": "python-list" }, { "code": null, "e": 1516, "s": 1509, "text": "Python" }, { "code": null, "e": 1532, "s": 1516, "text": "Python Programs" }, { "code": null, "e": 1544, "s": 1532, "text": "python-list" } ]
Software Engineering | MOCK (Introduction)
21 May, 2019 Mock is an Object that clone the behavior of a real object. It is basically used in Unit Testing by testing the isolated unit even when Backend is not available. Why we use MOCK object?The unit testing purpose is to approve each unit of software designed and verify that the generated code is working perfectly, interdependent on external dependencies. Most of the cases, Code under test has some external dependencies like APIs and It would be better to create a mock object instead of generating test cases on the real object of the dependencies. A web application consists of two components: Frontend and Backend server that are dependent on each other and run simultaneously.The developer of the Frontend is dependent on the backend developer for a server, APIs, and other external services. In the testing or development phase, a major challenge is to handle the various external dependencies.Real Environment exchanges their data through a server where user-end services are handled by a different server and admin services are handled by another server. Developer facing difficulty while developing software. On the other hand tester not able to do efficient unit testing when software is dependent on external dependencies. In order to provide effective testing, mock server is required. Mock server cut out the dependency on a real server and allows tester to do testing independently. Figure gives virtual Representation of Mock server. Now, in order to effectively utilizes our time and improve testing mechanism, there is a requirement of a Mock server that behaves as a real server, mimic its dependencies. Some of the mocking frameworks available to unit test Java application are Jmock, Mockito, EasyMock. For unit testing, mock objects can be used in place of real objects by simulating the Interfaces required. Mocks are easiest to use while Interface-based design systems. There is some pattern to be followed for Unit testing with Mock objects: Build an Instance or object of Mock object.Define States of Mock objects under defined environment.Set expectations, status codes, responses, error display in mock object.Set Mock object as parameter under domain code.Verify Mock objects under unit testing. Build an Instance or object of Mock object. Define States of Mock objects under defined environment. Set expectations, status codes, responses, error display in mock object. Set Mock object as parameter under domain code. Verify Mock objects under unit testing. SoniAnshu Software Engineering Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 May, 2019" }, { "code": null, "e": 190, "s": 28, "text": "Mock is an Object that clone the behavior of a real object. It is basically used in Unit Testing by testing the isolated unit even when Backend is not available." }, { "code": null, "e": 577, "s": 190, "text": "Why we use MOCK object?The unit testing purpose is to approve each unit of software designed and verify that the generated code is working perfectly, interdependent on external dependencies. Most of the cases, Code under test has some external dependencies like APIs and It would be better to create a mock object instead of generating test cases on the real object of the dependencies." }, { "code": null, "e": 1475, "s": 577, "text": "A web application consists of two components: Frontend and Backend server that are dependent on each other and run simultaneously.The developer of the Frontend is dependent on the backend developer for a server, APIs, and other external services. In the testing or development phase, a major challenge is to handle the various external dependencies.Real Environment exchanges their data through a server where user-end services are handled by a different server and admin services are handled by another server. Developer facing difficulty while developing software. On the other hand tester not able to do efficient unit testing when software is dependent on external dependencies. In order to provide effective testing, mock server is required. Mock server cut out the dependency on a real server and allows tester to do testing independently. Figure gives virtual Representation of Mock server." }, { "code": null, "e": 1919, "s": 1475, "text": "Now, in order to effectively utilizes our time and improve testing mechanism, there is a requirement of a Mock server that behaves as a real server, mimic its dependencies. Some of the mocking frameworks available to unit test Java application are Jmock, Mockito, EasyMock. For unit testing, mock objects can be used in place of real objects by simulating the Interfaces required. Mocks are easiest to use while Interface-based design systems." }, { "code": null, "e": 1992, "s": 1919, "text": "There is some pattern to be followed for Unit testing with Mock objects:" }, { "code": null, "e": 2250, "s": 1992, "text": "Build an Instance or object of Mock object.Define States of Mock objects under defined environment.Set expectations, status codes, responses, error display in mock object.Set Mock object as parameter under domain code.Verify Mock objects under unit testing." }, { "code": null, "e": 2294, "s": 2250, "text": "Build an Instance or object of Mock object." }, { "code": null, "e": 2351, "s": 2294, "text": "Define States of Mock objects under defined environment." }, { "code": null, "e": 2424, "s": 2351, "text": "Set expectations, status codes, responses, error display in mock object." }, { "code": null, "e": 2472, "s": 2424, "text": "Set Mock object as parameter under domain code." }, { "code": null, "e": 2512, "s": 2472, "text": "Verify Mock objects under unit testing." }, { "code": null, "e": 2522, "s": 2512, "text": "SoniAnshu" }, { "code": null, "e": 2543, "s": 2522, "text": "Software Engineering" } ]
What is the difference between CSS and SCSS ?
30 Jun, 2022 Introduction CSS : Cascading Style Sheet is the basically the scripting language. CSS is used for designing web pages.CSS is the most important web technologies that are widely used along with HTML and JavaScript. CSS have file extension of .css. SCSS : Syntactically Awesome Style Sheet is the superset of CSS. SCSS is the more advanced version of CSS. SCSS was designed by Hampton Catlin and was developed by Chris Eppstein and Natalie Weizenbaum. Due to its advanced features it is often termed as Sassy CSS. SCSS have file extension of .scss. Differences: SCSS contains all the features of CSS and contains more features that are not present in CSS which makes it a good choice for developers to use it.SCSS is full of advanced features.SCSS offers variables, you can shorten your code by using variables. It is a great advantage over conventional CSS.Example: In CSSbody{ color: #ffffff; font: $ubuntu-font: 'Ubuntu', 'Arial', 'Helvetica', sans-serif; font-size: xx-large; padding: 2rem; } Output:In SCSS$white: #ffffff; $ubuntu-font: $ubuntu-font: 'Ubuntu', 'Arial', 'Helvetica', sans-serif; body{ color: $white; font: $ubuntu-font; font-size: xx-large; padding: 2rem; } Output:Knowing SCSS helps you to customize Bootstrap 4.SASS adds the feature of @import which lets you import your customized SCSS files.Example:@import "my theme"; @import "framework/bootstrap"; SASS allows us to use nested syntax. Let’s say if you have to style a specific ‘paragraph’ in ‘div’ in ‘footer’ you can definitely do that by SASS.Example:footer { div { p { margin: 2rem; color: #2f2f2f; } } } At last, what makes SASS a good option to use is that it is well documented. SCSS contains all the features of CSS and contains more features that are not present in CSS which makes it a good choice for developers to use it. SCSS is full of advanced features. SCSS offers variables, you can shorten your code by using variables. It is a great advantage over conventional CSS.Example: In CSSbody{ color: #ffffff; font: $ubuntu-font: 'Ubuntu', 'Arial', 'Helvetica', sans-serif; font-size: xx-large; padding: 2rem; } Output:In SCSS$white: #ffffff; $ubuntu-font: $ubuntu-font: 'Ubuntu', 'Arial', 'Helvetica', sans-serif; body{ color: $white; font: $ubuntu-font; font-size: xx-large; padding: 2rem; } Output: Example: In CSSbody{ color: #ffffff; font: $ubuntu-font: 'Ubuntu', 'Arial', 'Helvetica', sans-serif; font-size: xx-large; padding: 2rem; } Output: body{ color: #ffffff; font: $ubuntu-font: 'Ubuntu', 'Arial', 'Helvetica', sans-serif; font-size: xx-large; padding: 2rem; } Output: In SCSS$white: #ffffff; $ubuntu-font: $ubuntu-font: 'Ubuntu', 'Arial', 'Helvetica', sans-serif; body{ color: $white; font: $ubuntu-font; font-size: xx-large; padding: 2rem; } Output: $white: #ffffff; $ubuntu-font: $ubuntu-font: 'Ubuntu', 'Arial', 'Helvetica', sans-serif; body{ color: $white; font: $ubuntu-font; font-size: xx-large; padding: 2rem; } Output: Knowing SCSS helps you to customize Bootstrap 4. SASS adds the feature of @import which lets you import your customized SCSS files.Example:@import "my theme"; @import "framework/bootstrap"; @import "my theme"; @import "framework/bootstrap"; SASS allows us to use nested syntax. Let’s say if you have to style a specific ‘paragraph’ in ‘div’ in ‘footer’ you can definitely do that by SASS.Example:footer { div { p { margin: 2rem; color: #2f2f2f; } } } footer { div { p { margin: 2rem; color: #2f2f2f; } } } At last, what makes SASS a good option to use is that it is well documented. CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples. CSS-Misc Picked SASS CSS Technical Scripter Web Technologies 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": 65, "s": 52, "text": "Introduction" }, { "code": null, "e": 299, "s": 65, "text": "CSS : Cascading Style Sheet is the basically the scripting language. CSS is used for designing web pages.CSS is the most important web technologies that are widely used along with HTML and JavaScript. CSS have file extension of .css." }, { "code": null, "e": 599, "s": 299, "text": "SCSS : Syntactically Awesome Style Sheet is the superset of CSS. SCSS is the more advanced version of CSS. SCSS was designed by Hampton Catlin and was developed by Chris Eppstein and Natalie Weizenbaum. Due to its advanced features it is often termed as Sassy CSS. SCSS have file extension of .scss." }, { "code": null, "e": 612, "s": 599, "text": "Differences:" }, { "code": null, "e": 1834, "s": 612, "text": "SCSS contains all the features of CSS and contains more features that are not present in CSS which makes it a good choice for developers to use it.SCSS is full of advanced features.SCSS offers variables, you can shorten your code by using variables. It is a great advantage over conventional CSS.Example: In CSSbody{\n color: #ffffff;\n font: $ubuntu-font: 'Ubuntu', \n 'Arial',\n 'Helvetica',\n sans-serif;\n font-size: xx-large;\n padding: 2rem;\n}\nOutput:In SCSS$white: #ffffff;\n$ubuntu-font: $ubuntu-font: 'Ubuntu', 'Arial', 'Helvetica', sans-serif;\n\nbody{\n color: $white;\n font: $ubuntu-font;\n font-size: xx-large;\n padding: 2rem;\n}\nOutput:Knowing SCSS helps you to customize Bootstrap 4.SASS adds the feature of @import which lets you import your customized SCSS files.Example:@import \"my theme\";\n@import \"framework/bootstrap\";\nSASS allows us to use nested syntax. Let’s say if you have to style a specific ‘paragraph’ in ‘div’ in ‘footer’ you can definitely do that by SASS.Example:footer {\n div {\n p {\n margin: 2rem;\n color: #2f2f2f;\n }\n }\n}\nAt last, what makes SASS a good option to use is that it is well documented." }, { "code": null, "e": 1982, "s": 1834, "text": "SCSS contains all the features of CSS and contains more features that are not present in CSS which makes it a good choice for developers to use it." }, { "code": null, "e": 2017, "s": 1982, "text": "SCSS is full of advanced features." }, { "code": null, "e": 2535, "s": 2017, "text": "SCSS offers variables, you can shorten your code by using variables. It is a great advantage over conventional CSS.Example: In CSSbody{\n color: #ffffff;\n font: $ubuntu-font: 'Ubuntu', \n 'Arial',\n 'Helvetica',\n sans-serif;\n font-size: xx-large;\n padding: 2rem;\n}\nOutput:In SCSS$white: #ffffff;\n$ubuntu-font: $ubuntu-font: 'Ubuntu', 'Arial', 'Helvetica', sans-serif;\n\nbody{\n color: $white;\n font: $ubuntu-font;\n font-size: xx-large;\n padding: 2rem;\n}\nOutput:" }, { "code": null, "e": 2751, "s": 2535, "text": "Example: In CSSbody{\n color: #ffffff;\n font: $ubuntu-font: 'Ubuntu', \n 'Arial',\n 'Helvetica',\n sans-serif;\n font-size: xx-large;\n padding: 2rem;\n}\nOutput:" }, { "code": null, "e": 2945, "s": 2751, "text": "body{\n color: #ffffff;\n font: $ubuntu-font: 'Ubuntu', \n 'Arial',\n 'Helvetica',\n sans-serif;\n font-size: xx-large;\n padding: 2rem;\n}\n" }, { "code": null, "e": 2953, "s": 2945, "text": "Output:" }, { "code": null, "e": 3141, "s": 2953, "text": "In SCSS$white: #ffffff;\n$ubuntu-font: $ubuntu-font: 'Ubuntu', 'Arial', 'Helvetica', sans-serif;\n\nbody{\n color: $white;\n font: $ubuntu-font;\n font-size: xx-large;\n padding: 2rem;\n}\nOutput:" }, { "code": null, "e": 3315, "s": 3141, "text": "$white: #ffffff;\n$ubuntu-font: $ubuntu-font: 'Ubuntu', 'Arial', 'Helvetica', sans-serif;\n\nbody{\n color: $white;\n font: $ubuntu-font;\n font-size: xx-large;\n padding: 2rem;\n}\n" }, { "code": null, "e": 3323, "s": 3315, "text": "Output:" }, { "code": null, "e": 3372, "s": 3323, "text": "Knowing SCSS helps you to customize Bootstrap 4." }, { "code": null, "e": 3514, "s": 3372, "text": "SASS adds the feature of @import which lets you import your customized SCSS files.Example:@import \"my theme\";\n@import \"framework/bootstrap\";\n" }, { "code": null, "e": 3566, "s": 3514, "text": "@import \"my theme\";\n@import \"framework/bootstrap\";\n" }, { "code": null, "e": 3825, "s": 3566, "text": "SASS allows us to use nested syntax. Let’s say if you have to style a specific ‘paragraph’ in ‘div’ in ‘footer’ you can definitely do that by SASS.Example:footer {\n div {\n p {\n margin: 2rem;\n color: #2f2f2f;\n }\n }\n}\n" }, { "code": null, "e": 3929, "s": 3825, "text": "footer {\n div {\n p {\n margin: 2rem;\n color: #2f2f2f;\n }\n }\n}\n" }, { "code": null, "e": 4006, "s": 3929, "text": "At last, what makes SASS a good option to use is that it is well documented." }, { "code": null, "e": 4192, "s": 4006, "text": "CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples." }, { "code": null, "e": 4201, "s": 4192, "text": "CSS-Misc" }, { "code": null, "e": 4208, "s": 4201, "text": "Picked" }, { "code": null, "e": 4213, "s": 4208, "text": "SASS" }, { "code": null, "e": 4217, "s": 4213, "text": "CSS" }, { "code": null, "e": 4236, "s": 4217, "text": "Technical Scripter" }, { "code": null, "e": 4253, "s": 4236, "text": "Web Technologies" } ]
Python | Pandas dataframe.corr()
22 Apr, 2020 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.corr() is used to find the pairwise correlation of all columns in the dataframe. Any na values are automatically excluded. For any non-numeric data type columns in the dataframe it is ignored. Syntax: DataFrame.corr(self, method=’pearson’, min_periods=1) Parameters:method :pearson : standard correlation coefficientkendall : Kendall Tau correlation coefficientspearman : Spearman rank correlationmin_periods : Minimum number of observations required per pair of columns to have a valid result. Currently only available for pearson and spearman correlation Returns: count :y : DataFrame Note: The correlation of a variable with itself is 1. For link to CSV file Used in Code, click here Example #1: Use corr() function to find the correlation among the columns in the dataframe using ‘Pearson’ method. # importing pandas as pdimport pandas as pd # Making data frame from the csv filedf = pd.read_csv("nba.csv") # Printing the first 10 rows of the data frame for visualizationdf[:10] Now use corr() function to find the correlation among the columns. We are only having four numeric columns in the dataframe. # To find the correlation among# the columns using pearson methoddf.corr(method ='pearson') Output : The output dataframe can be interpreted as for any cell, row variable correlation with the column variable is the value of the cell. As mentioned earlier, that the correlation of a variable with itself is 1. For that reason all the diagonal values are 1.00 Example #2: Use corr() function to find the correlation among the columns in the dataframe using ‘kendall’ method. # importing pandas as pdimport pandas as pd # Making data frame from the csv filedf = pd.read_csv("nba.csv") # To find the correlation among# the columns using kendall methoddf.corr(method ='kendall') Output : The output dataframe can be interpreted as for any cell, row variable correlation with the column variable is the value of the cell. As mentioned earlier, that the correlation of a variable with itself is 1. For that reason all the diagonal values are 1.00. pratibha_gupta Python pandas-dataFrame Python pandas-dataFrame-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n22 Apr, 2020" }, { "code": null, "e": 267, "s": 53, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 477, "s": 267, "text": "Pandas dataframe.corr() is used to find the pairwise correlation of all columns in the dataframe. Any na values are automatically excluded. For any non-numeric data type columns in the dataframe it is ignored." }, { "code": null, "e": 539, "s": 477, "text": "Syntax: DataFrame.corr(self, method=’pearson’, min_periods=1)" }, { "code": null, "e": 841, "s": 539, "text": "Parameters:method :pearson : standard correlation coefficientkendall : Kendall Tau correlation coefficientspearman : Spearman rank correlationmin_periods : Minimum number of observations required per pair of columns to have a valid result. Currently only available for pearson and spearman correlation" }, { "code": null, "e": 871, "s": 841, "text": "Returns: count :y : DataFrame" }, { "code": null, "e": 925, "s": 871, "text": "Note: The correlation of a variable with itself is 1." }, { "code": null, "e": 971, "s": 925, "text": "For link to CSV file Used in Code, click here" }, { "code": null, "e": 1086, "s": 971, "text": "Example #1: Use corr() function to find the correlation among the columns in the dataframe using ‘Pearson’ method." }, { "code": "# importing pandas as pdimport pandas as pd # Making data frame from the csv filedf = pd.read_csv(\"nba.csv\") # Printing the first 10 rows of the data frame for visualizationdf[:10]", "e": 1269, "s": 1086, "text": null }, { "code": null, "e": 1394, "s": 1269, "text": "Now use corr() function to find the correlation among the columns. We are only having four numeric columns in the dataframe." }, { "code": "# To find the correlation among# the columns using pearson methoddf.corr(method ='pearson')", "e": 1486, "s": 1394, "text": null }, { "code": null, "e": 1495, "s": 1486, "text": "Output :" }, { "code": null, "e": 1867, "s": 1495, "text": "The output dataframe can be interpreted as for any cell, row variable correlation with the column variable is the value of the cell. As mentioned earlier, that the correlation of a variable with itself is 1. For that reason all the diagonal values are 1.00 Example #2: Use corr() function to find the correlation among the columns in the dataframe using ‘kendall’ method." }, { "code": "# importing pandas as pdimport pandas as pd # Making data frame from the csv filedf = pd.read_csv(\"nba.csv\") # To find the correlation among# the columns using kendall methoddf.corr(method ='kendall')", "e": 2070, "s": 1867, "text": null }, { "code": null, "e": 2079, "s": 2070, "text": "Output :" }, { "code": null, "e": 2337, "s": 2079, "text": "The output dataframe can be interpreted as for any cell, row variable correlation with the column variable is the value of the cell. As mentioned earlier, that the correlation of a variable with itself is 1. For that reason all the diagonal values are 1.00." }, { "code": null, "e": 2352, "s": 2337, "text": "pratibha_gupta" }, { "code": null, "e": 2376, "s": 2352, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2408, "s": 2376, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 2422, "s": 2408, "text": "Python-pandas" }, { "code": null, "e": 2429, "s": 2422, "text": "Python" } ]
User Authentication and CRUD Operation with Firebase Realtime Database in Android
10 Jan, 2022 Firebase is a famous product of Google which is used by so many developers to add backend functionality for their website as well as apps. The Firebase will make your job really easier for the backend database and handling the database. In this article, we will take a look at the implementation of the Firebase Realtime Database in Android. In this article, we will be adding an Email and password authentication inside our app and along with that, we will be performing the CRUD (Create, Read, Update and Delete) operations inside our application using the Firebase Realtime Database. https://www.youtube.com/watch?v=-Gvpf8tXpbc In this article, we will be building a simple Android Application in which we will be firstly authenticating the user with their email and password. After that, we will display the list of courses that are available on Geeks for Geeks in the recycler view. We will be able to perform CRUD operations on these courses. Below is the video in which we will get to see what we are going to build in this article. Step 1: Create a new Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Connect your app to Firebase After creating a new project navigate to the Tools option on the top bar. Inside that click on Firebase. After clicking on Firebase, you can get to see the right column mentioned below in the screenshot. Inside that column Navigate to Firebase Realtime Database. Click on that option and you will get to see two options on Connect app to Firebase and Add Firebase Realtime Database to your app. Click on Connect now and your app will be connected to Firebase. After that click on the second option and now your App is connected to Firebase. After connecting your app to Firebase you will get to see the below screen. After that verify that dependency for the Firebase Realtime database has been added to our Gradle file. Now navigate to the app > Gradle Scripts and inside that file check whether the below dependency is added or not. If the below dependency is not added in your build.gradle file. Add the below dependency in the dependencies section. Below is the complete dependencies section in which there are dependencies for authentication as well as the database. dependencies { implementation 'androidx.appcompat:appcompat:1.3.0' implementation 'com.google.android.material:material:1.4.0' // dependency for picasso for loading image from url implementation 'com.squareup.picasso:picasso:2.71828' implementation 'androidx.constraintlayout:constraintlayout:2.0.4' // dependency for firebase database. implementation 'com.google.firebase:firebase-database:20.0.0' implementation platform('com.google.firebase:firebase-bom:28.2.1') // dependency for firebase authentication. implementation 'com.google.firebase:firebase-auth' testImplementation 'junit:junit:4.+' androidTestImplementation 'androidx.test.ext:junit:1.1.3' androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0' } After adding this dependency sync your project and now we are ready for creating our app. If you want to know more about connecting your app to Firebase. Refer to this article to get in detail about Adding Firebase to Android App. Step 3: Creating 4 different empty activities Navigate to the app > Your app’s package name > Right-click on it > New > Activity > Select Empty Activity and Create a New Activity. Below is the name for the four different activities which we have to pass while creating new activities. AddCourseActivity: This activity we will use for adding a new Course. EditCourseActivity: This activity will be used to edit our course as well as delete our course. LoginActivity: This activity will be used for Login purposes for existing user login. RegisterActivity: This activity is used for the registration of new Users. MainActivity.java file will be already present in which we will be displaying the list of courses in RecyclerView. Step 4: Working with AndroidManifest.xml file Navigate to app > AndroidManifest.xml file and add internet permissions to it. Below is the complete code for the AndroidManifest.xml file. Inside this file, we are also changing our launcher activity to Login Activity. Comments are added in the code to get to know in more detail. XML <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.gtappdevelopers.firebasecrudapp"> <!--permissions for internet--> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.FirebaseCrudApp"> <activity android:name=".EditCourseActivity" android:label="Edit Course" /> <activity android:name=".AddCourseActivity" android:label="Add Course" /> <activity android:name=".RegisterActivity" android:label="Register" /> <!--login activity is set as launcher activity--> <activity android:name=".LoginActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".MainActivity" /> </application> </manifest> Step 5: Updating colors.xml file Navigate to the app > res > values > colors.xml and add the below colors to it. XML <?xml version="1.0" encoding="utf-8"?><resources xmlns:tools="http://schemas.android.com/tools"> <color name="purple_200">#296D98</color> <color name="purple_500">#296D98</color> <color name="purple_700">#296D98</color> <color name="teal_200">#FF03DAC5</color> <color name="teal_700">#FF018786</color> <color name="black">#FF000000</color> <color name="white">#FFFFFFFF</color> <color name="black_shade_1">#0e2433</color> <color name="black_shade_2">#1C4966</color> <color name="black_shade_3">#22252D</color> <color name="mtrl_textinput_default_box_stroke_color" tools:override="true">#296D98</color> <color name="light_blue_shade_1">#296D98</color> <color name="gray">#424242</color> <color name="yellow">#ffa500</color> <color name="dark_blue_shade">#0D2162</color> <color name="dark_blue_shade_2">#17388E</color> <color name="light_blue_shade">#12B2E6</color> </resources> Step 6: Updating our themes.xml file Navigate to the app > res > values > themes.xml and add the below code to it. XML <resources xmlns:tools="http://schemas.android.com/tools"> <!-- Base application theme. --> <style name="Theme.FirebaseCrudApp" parent="Theme.MaterialComponents.DayNight.DarkActionBar"> <!-- Primary brand color. --> <item name="colorPrimary">@color/purple_500</item> <item name="colorPrimaryVariant">@color/purple_700</item> <item name="colorOnPrimary">@color/white</item> <!-- Secondary brand color. --> <item name="colorSecondary">@color/teal_200</item> <item name="colorSecondaryVariant">@color/teal_700</item> <item name="colorOnSecondary">@color/black</item> <!-- Status bar color. --> <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item> <!-- Customize your theme here. --> </style> <style name="AppBottomSheetDialogTheme" parent="Theme.Design.Light.BottomSheetDialog"> <item name="bottomSheetStyle">@style/AppModalStyle</item> </style> <style name="BottomSheetDialogTheme" parent="Theme.Design.Light.BottomSheetDialog"> <item name="bottomSheetStyle">@style/BottomSheetStyle</item> </style> <style name="BottomSheetStyle" parent="Widget.Design.BottomSheet.Modal"> <item name="android:background">@android:color/transparent</item> </style> <style name="AppModalStyle" parent="Widget.Design.BottomSheet.Modal"> <item name="android:background">@drawable/rounded_drawable</item> </style> <style name="LoginTextInputLayoutStyle" parent="Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense"> <item name="boxStrokeColor">#296D98</item> <item name="boxStrokeWidth">1dp</item> </style> </resources> Step 7: Creating a custom background for our button and custom progress bar background Navigate to the app > res > drawable > Right-click on it > New Drawable Resource file and name it as button_back and add below code to it. Comments are added in the code to get to know in detail. XML <?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <!--for specifying corner radius--> <corners android:radius="20dp" /> <!-- for specifying solid color--> <solid android:color="@color/black_shade_1" /> </shape> Navigate to the app > res > drawable > Right-click on it > New Drawable Resource file and name it as progress_back and add the below code to it. Comments are added in the code to get to know in detail. XML <?xml version="1.0" encoding="utf-8"?><rotate xmlns:android="http://schemas.android.com/apk/res/android" android:fromDegrees="0" android:pivotX="50%" android:pivotY="50%" android:toDegrees="360"> <!--shape tag is used to build a shape in XML--> <shape android:innerRadiusRatio="3" android:shape="ring" android:thicknessRatio="8" android:useLevel="false"> <!--set the size of the shape--> <size android:width="76dip" android:height="76dip" /> <!--set the color gradients of the shape--> <gradient android:angle="0" android:endColor="#00ffffff" android:startColor="@color/purple_200" android:type="sweep" android:useLevel="false" /> </shape> </rotate> Step 8: Working with activity_register.xml file Navigate to the app > res > activity_register.xml and add the below code to it. Comments are added in the code to get to know in more detail. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/black_shade_1" tools:context=".RegisterActivity"> <!--edit text for user name--> <com.google.android.material.textfield.TextInputLayout android:id="@+id/idTILUserName" style="@style/LoginTextInputLayoutStyle" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="20dp" android:layout_marginTop="140dp" android:layout_marginEnd="20dp" android:hint="Enter User Name" android:padding="5dp" android:textColorHint="@color/white" app:hintTextColor="@color/white"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/idEdtUserName" android:layout_width="match_parent" android:layout_height="match_parent" android:ems="10" android:importantForAutofill="no" android:inputType="textEmailAddress" android:textColor="@color/white" android:textColorHint="@color/white" android:textSize="14sp" /> </com.google.android.material.textfield.TextInputLayout> <!--edit text for user password--> <com.google.android.material.textfield.TextInputLayout android:id="@+id/idTILPassword" style="@style/LoginTextInputLayoutStyle" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idTILUserName" android:layout_marginStart="20dp" android:layout_marginTop="20dp" android:layout_marginEnd="20dp" android:hint="Enter Your Password" android:padding="5dp" android:textColorHint="@color/white" app:hintTextColor="@color/white"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/idEdtPassword" android:layout_width="match_parent" android:layout_height="match_parent" android:ems="10" android:importantForAutofill="no" android:inputType="textPassword" android:textColor="@color/white" android:textColorHint="@color/white" android:textSize="14sp" /> </com.google.android.material.textfield.TextInputLayout> <!--edit text for confirmation of user password--> <com.google.android.material.textfield.TextInputLayout android:id="@+id/idTILConfirmPassword" style="@style/LoginTextInputLayoutStyle" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idTILPassword" android:layout_marginStart="20dp" android:layout_marginTop="20dp" android:layout_marginEnd="20dp" android:hint="Confirm Your Password" android:padding="5dp" android:textColorHint="@color/white" app:hintTextColor="@color/white"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/idEdtConfirmPassword" android:layout_width="match_parent" android:layout_height="match_parent" android:ems="10" android:importantForAutofill="no" android:inputType="textPassword" android:textColor="@color/white" android:textColorHint="@color/white" android:textSize="14sp" /> </com.google.android.material.textfield.TextInputLayout> <!--button for creating user account.--> <Button android:id="@+id/idBtnRegister" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idTILConfirmPassword" android:layout_marginStart="25dp" android:layout_marginTop="40dp" android:layout_marginEnd="25dp" android:background="@drawable/button_back" android:text="Register" android:textAllCaps="false" /> <!--text view for displaying a text on clicking we will open a login page--> <TextView android:id="@+id/idTVLoginUser" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idBtnRegister" android:layout_marginTop="40dp" android:gravity="center" android:padding="10dp" android:text="Already a User ? Login Here" android:textAlignment="center" android:textAllCaps="false" android:textColor="@color/white" android:textSize="18sp" /> <!--progress bar as a loading indicator--> <ProgressBar android:id="@+id/idPBLoading" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:indeterminate="true" android:indeterminateDrawable="@drawable/progress_back" android:visibility="gone" /> </RelativeLayout> Step 9: Working with RegisterActivity.java file Navigate to the app > java > your app’s package name > RegisterActivity.java file and add the below code to it. Comments are added in the code to get to know in more detail. Java package com.gtappdevelopers.firebasecrudapp; import android.content.Intent;import android.os.Bundle;import android.text.TextUtils;import android.view.View;import android.widget.Button;import android.widget.ProgressBar;import android.widget.TextView;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity; import com.google.android.gms.tasks.OnCompleteListener;import com.google.android.gms.tasks.Task;import com.google.android.material.textfield.TextInputEditText;import com.google.firebase.auth.AuthResult;import com.google.firebase.auth.FirebaseAuth; public class RegisterActivity extends AppCompatActivity { // creating variables for edit text and textview, // firebase auth, button and progress bar. private TextInputEditText userNameEdt, passwordEdt, confirmPwdEdt; private TextView loginTV; private Button registerBtn; private FirebaseAuth mAuth; private ProgressBar loadingPB; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); // initializing all our variables. userNameEdt = findViewById(R.id.idEdtUserName); passwordEdt = findViewById(R.id.idEdtPassword); loadingPB = findViewById(R.id.idPBLoading); confirmPwdEdt = findViewById(R.id.idEdtConfirmPassword); loginTV = findViewById(R.id.idTVLoginUser); registerBtn = findViewById(R.id.idBtnRegister); mAuth = FirebaseAuth.getInstance(); // adding on click for login tv. loginTV.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // opening a login activity on clicking login text. Intent i = new Intent(RegisterActivity.this, LoginActivity.class); startActivity(i); } }); // adding click listener for register button. registerBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // hiding our progress bar. loadingPB.setVisibility(View.VISIBLE); // getting data fro =m our edit text. String userName = userNameEdt.getText().toString(); String pwd = passwordEdt.getText().toString(); String cnfPwd = confirmPwdEdt.getText().toString(); // checking if the password and confirm password is equal or not. if (!pwd.equals(cnfPwd)) { Toast.makeText(RegisterActivity.this, "Please check both having same password..", Toast.LENGTH_SHORT).show(); } else if (TextUtils.isEmpty(userName) && TextUtils.isEmpty(pwd) && TextUtils.isEmpty(cnfPwd)) { // checking if the text fields are empty or not. Toast.makeText(RegisterActivity.this, "Please enter your credentials..", Toast.LENGTH_SHORT).show(); } else { // on below line we are creating a new user by passing email and password. mAuth.createUserWithEmailAndPassword(userName, pwd).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { // on below line we are checking if the task is success or not. if (task.isSuccessful()) { // in on success method we are hiding our progress bar and opening a login activity. loadingPB.setVisibility(View.GONE); Toast.makeText(RegisterActivity.this, "User Registered..", Toast.LENGTH_SHORT).show(); Intent i = new Intent(RegisterActivity.this, LoginActivity.class); startActivity(i); finish(); } else { // in else condition we are displaying a failure toast message. loadingPB.setVisibility(View.GONE); Toast.makeText(RegisterActivity.this, "Fail to register user..", Toast.LENGTH_SHORT).show(); } } }); } } }); }} Step 10: Working with activity_login.xml file Navigate to the app > res > activity_login.xml and add the below code to it. Comments are added in the code to get to know in more detail. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/black_shade_1" tools:context=".LoginActivity"> <!--edit text for user name--> <com.google.android.material.textfield.TextInputLayout android:id="@+id/idTILUserName" style="@style/LoginTextInputLayoutStyle" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="20dp" android:layout_marginTop="140dp" android:layout_marginEnd="20dp" android:hint="Enter User Name" android:padding="5dp" android:textColorHint="@color/white" app:hintTextColor="@color/white"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/idEdtUserName" android:layout_width="match_parent" android:layout_height="match_parent" android:ems="10" android:importantForAutofill="no" android:inputType="textEmailAddress" android:textColor="@color/white" android:textColorHint="@color/white" android:textSize="14sp" /> </com.google.android.material.textfield.TextInputLayout> <!--edit text for password--> <com.google.android.material.textfield.TextInputLayout android:id="@+id/idTILPassword" style="@style/LoginTextInputLayoutStyle" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idTILUserName" android:layout_marginStart="20dp" android:layout_marginTop="40dp" android:layout_marginEnd="20dp" android:hint="Enter your Password" android:padding="5dp" android:textColorHint="@color/white" app:hintTextColor="@color/white"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/idEdtPassword" android:layout_width="match_parent" android:layout_height="match_parent" android:ems="10" android:importantForAutofill="no" android:inputType="textPassword" android:textColor="@color/white" android:textColorHint="@color/white" android:textSize="14sp" /> </com.google.android.material.textfield.TextInputLayout> <!--button for login--> <Button android:id="@+id/idBtnLogin" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idTILPassword" android:layout_marginStart="25dp" android:layout_marginTop="40dp" android:layout_marginEnd="25dp" android:background="@drawable/button_back" android:text="Login" android:textAllCaps="false" /> <!--text view for creating a new account--> <TextView android:id="@+id/idTVNewUser" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idBtnLogin" android:layout_marginTop="40dp" android:gravity="center" android:padding="10dp" android:text="New User ? Register Here" android:textAlignment="center" android:textAllCaps="false" android:textColor="@color/white" android:textSize="18sp" /> <!--progress-bar for loading indicator--> <ProgressBar android:id="@+id/idPBLoading" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/idTVNewUser" android:layout_centerHorizontal="true" android:layout_marginTop="10dp" android:indeterminate="true" android:indeterminateDrawable="@drawable/progress_back" android:visibility="gone" /> </RelativeLayout> Step 11: Working with LoginActivity.java file Navigate to the app > java > your app’s package name > LoginActivity.java file and add the below code to it. Comments are added in the code to get to know in more detail. Java package com.gtappdevelopers.firebasecrudapp; import android.content.Intent;import android.os.Bundle;import android.text.TextUtils;import android.view.View;import android.widget.Button;import android.widget.ProgressBar;import android.widget.TextView;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity; import com.google.android.gms.tasks.OnCompleteListener;import com.google.android.gms.tasks.Task;import com.google.android.material.textfield.TextInputEditText;import com.google.firebase.auth.AuthResult;import com.google.firebase.auth.FirebaseAuth;import com.google.firebase.auth.FirebaseUser; public class LoginActivity extends AppCompatActivity { // creating variable for edit text, textview, // button, progress bar and firebase auth. private TextInputEditText userNameEdt, passwordEdt; private Button loginBtn; private TextView newUserTV; private FirebaseAuth mAuth; private ProgressBar loadingPB; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); // initializing all our variables. userNameEdt = findViewById(R.id.idEdtUserName); passwordEdt = findViewById(R.id.idEdtPassword); loginBtn = findViewById(R.id.idBtnLogin); newUserTV = findViewById(R.id.idTVNewUser); mAuth = FirebaseAuth.getInstance(); loadingPB = findViewById(R.id.idPBLoading); // adding click listener for our new user tv. newUserTV.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // on below line opening a login activity. Intent i = new Intent(LoginActivity.this, RegisterActivity.class); startActivity(i); } }); // adding on click listener for our login button. loginBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // hiding our progress bar. loadingPB.setVisibility(View.VISIBLE); // getting data from our edit text on below line. String email = userNameEdt.getText().toString(); String password = passwordEdt.getText().toString(); // on below line validating the text input. if (TextUtils.isEmpty(email) && TextUtils.isEmpty(password)) { Toast.makeText(LoginActivity.this, "Please enter your credentials..", Toast.LENGTH_SHORT).show(); return; } // on below line we are calling a sign in method and passing email and password to it. mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { // on below line we are checking if the task is success or not. if (task.isSuccessful()) { // on below line we are hiding our progress bar. loadingPB.setVisibility(View.GONE); Toast.makeText(LoginActivity.this, "Login Successful..", Toast.LENGTH_SHORT).show(); // on below line we are opening our mainactivity. Intent i = new Intent(LoginActivity.this, MainActivity.class); startActivity(i); finish(); } else { // hiding our progress bar and displaying a toast message. loadingPB.setVisibility(View.GONE); Toast.makeText(LoginActivity.this, "Please enter valid user credentials..", Toast.LENGTH_SHORT).show(); } } }); } }); } @Override protected void onStart() { super.onStart(); // in on start method checking if // the user is already sign in. FirebaseUser user = mAuth.getCurrentUser(); if (user != null) { // if the user is not null then we are // opening a main activity on below line. Intent i = new Intent(LoginActivity.this, MainActivity.class); startActivity(i); this.finish(); } }} Step 12: Creating a Modal class for our data to be displayed inside our RecyclerView Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as CourseRVModal and add the below code to it. Comments are added in the code to get to know in more detail. Java package com.gtappdevelopers.firebasecrudapp; import android.os.Parcel;import android.os.Parcelable; public class CourseRVModal implements Parcelable { // creating variables for our different fields. private String courseName; private String courseDescription; private String coursePrice; private String bestSuitedFor; private String courseImg; private String courseLink; private String courseId; public String getCourseId() { return courseId; } public void setCourseId(String courseId) { this.courseId = courseId; } // creating an empty constructor. public CourseRVModal() { } protected CourseRVModal(Parcel in) { courseName = in.readString(); courseId = in.readString(); courseDescription = in.readString(); coursePrice = in.readString(); bestSuitedFor = in.readString(); courseImg = in.readString(); courseLink = in.readString(); } public static final Creator<CourseRVModal> CREATOR = new Creator<CourseRVModal>() { @Override public CourseRVModal createFromParcel(Parcel in) { return new CourseRVModal(in); } @Override public CourseRVModal[] newArray(int size) { return new CourseRVModal[size]; } }; // creating getter and setter methods. public String getCourseName() { return courseName; } public void setCourseName(String courseName) { this.courseName = courseName; } public String getCourseDescription() { return courseDescription; } public void setCourseDescription(String courseDescription) { this.courseDescription = courseDescription; } public String getCoursePrice() { return coursePrice; } public void setCoursePrice(String coursePrice) { this.coursePrice = coursePrice; } public String getBestSuitedFor() { return bestSuitedFor; } public void setBestSuitedFor(String bestSuitedFor) { this.bestSuitedFor = bestSuitedFor; } public String getCourseImg() { return courseImg; } public void setCourseImg(String courseImg) { this.courseImg = courseImg; } public String getCourseLink() { return courseLink; } public void setCourseLink(String courseLink) { this.courseLink = courseLink; } public CourseRVModal(String courseId, String courseName, String courseDescription, String coursePrice, String bestSuitedFor, String courseImg, String courseLink) { this.courseName = courseName; this.courseId = courseId; this.courseDescription = courseDescription; this.coursePrice = coursePrice; this.bestSuitedFor = bestSuitedFor; this.courseImg = courseImg; this.courseLink = courseLink; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(courseName); dest.writeString(courseId); dest.writeString(courseDescription); dest.writeString(coursePrice); dest.writeString(bestSuitedFor); dest.writeString(courseImg); dest.writeString(courseLink); }} Step 13: Working with activity_add_course.xml file Navigate to the app > res > layout > activity_add_course.xml and add the below code to it. Comments are added in the code to get to know in more detail. XML <?xml version="1.0" encoding="utf-8"?><ScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/black_shade_1" tools:context=".AddCourseActivity"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <!--edit text for course name--> <com.google.android.material.textfield.TextInputLayout android:id="@+id/idTILCourseName" style="@style/LoginTextInputLayoutStyle" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:layout_marginTop="10dp" android:layout_marginRight="10dp" android:hint="Enter Course Name" android:padding="5dp" android:textColorHint="@color/white" app:hintTextColor="@color/white"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/idEdtCourseName" android:layout_width="match_parent" android:layout_height="match_parent" android:ems="10" android:importantForAutofill="no" android:inputType="textImeMultiLine|textMultiLine" android:textColor="@color/white" android:textColorHint="@color/white" android:textSize="14sp" /> </com.google.android.material.textfield.TextInputLayout> <!--edit text for course price--> <com.google.android.material.textfield.TextInputLayout android:id="@+id/idTILCoursePrice" style="@style/LoginTextInputLayoutStyle" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:layout_marginTop="10dp" android:layout_marginRight="10dp" android:hint="Enter Course Price" android:padding="5dp" android:textColorHint="@color/white" app:boxStrokeColor="@color/purple_200" app:hintTextColor="@color/white"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/idEdtCoursePrice" android:layout_width="match_parent" android:layout_height="match_parent" android:ems="10" android:importantForAutofill="no" android:inputType="phone" android:textColor="@color/white" android:textColorHint="@color/white" android:textSize="14sp" app:boxStrokeColor="@color/purple_200" /> </com.google.android.material.textfield.TextInputLayout> <!--edit text for course suited for--> <com.google.android.material.textfield.TextInputLayout android:id="@+id/idTILCourseSuitedFor" style="@style/LoginTextInputLayoutStyle" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:layout_marginTop="10dp" android:layout_marginRight="10dp" android:hint="Enter Course Suited For" android:padding="5dp" android:textColorHint="@color/white" app:hintTextColor="@color/white"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/idEdtSuitedFor" android:layout_width="match_parent" android:layout_height="match_parent" android:ems="10" android:importantForAutofill="no" android:inputType="textImeMultiLine|textMultiLine" android:textColor="@color/white" android:textColorHint="@color/white" android:textSize="14sp" /> </com.google.android.material.textfield.TextInputLayout> <!--edit text for course image link--> <com.google.android.material.textfield.TextInputLayout android:id="@+id/idTILCourseImageLink" style="@style/LoginTextInputLayoutStyle" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:layout_marginTop="10dp" android:layout_marginRight="10dp" android:hint="Enter Course Image Link" android:padding="5dp" android:textColorHint="@color/white" app:hintTextColor="@color/white"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/idEdtCourseImageLink" android:layout_width="match_parent" android:layout_height="match_parent" android:ems="10" android:importantForAutofill="no" android:inputType="textImeMultiLine|textMultiLine" android:textColor="@color/white" android:textColorHint="@color/white" android:textSize="14sp" /> </com.google.android.material.textfield.TextInputLayout> <!--edit text for course link--> <com.google.android.material.textfield.TextInputLayout android:id="@+id/idTILCourseLink" style="@style/LoginTextInputLayoutStyle" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:layout_marginTop="10dp" android:layout_marginRight="10dp" android:hint="Enter Course Link" android:padding="5dp" android:textColorHint="@color/white" app:hintTextColor="@color/white"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/idEdtCourseLink" android:layout_width="match_parent" android:layout_height="match_parent" android:ems="10" android:importantForAutofill="no" android:inputType="textImeMultiLine|textMultiLine" android:textColor="@color/white" android:textColorHint="@color/white" android:textSize="14sp" /> </com.google.android.material.textfield.TextInputLayout> <!--edit text for course description--> <com.google.android.material.textfield.TextInputLayout android:id="@+id/idTILCourseDescription" style="@style/LoginTextInputLayoutStyle" android:layout_width="match_parent" android:layout_height="200dp" android:layout_marginLeft="10dp" android:layout_marginTop="10dp" android:layout_marginRight="10dp" android:hint="Enter Course Description" android:padding="5dp" android:textColorHint="@color/white" app:hintTextColor="@color/white"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/idEdtCourseDescription" android:layout_width="match_parent" android:layout_height="match_parent" android:ems="10" android:importantForAutofill="no" android:inputType="textImeMultiLine|textMultiLine" android:textColor="@color/white" android:textColorHint="@color/white" android:textSize="14sp" /> </com.google.android.material.textfield.TextInputLayout> <!--button for adding a new course--> <Button android:id="@+id/idBtnAddCourse" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="10dp" android:layout_marginTop="10dp" android:layout_marginEnd="10dp" android:layout_marginBottom="10dp" android:background="@drawable/button_back" android:text="Add Your Course" android:textAllCaps="false" /> </LinearLayout> <!--progress bar for loading indicator--> <ProgressBar android:id="@+id/idPBLoading" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:layout_gravity="center" android:indeterminate="true" android:indeterminateDrawable="@drawable/progress_back" android:visibility="gone" /> </RelativeLayout></ScrollView> Step 14: Working with the AddCourseActivity.java file Navigate to the app > java > your app’s package name > AddCourseActivity.java file and add the below code to it. Comments are added in the code to get to know in more detail. Java package com.gtappdevelopers.firebasecrudapp; import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.ProgressBar;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity; import com.google.android.material.textfield.TextInputEditText;import com.google.firebase.database.DataSnapshot;import com.google.firebase.database.DatabaseError;import com.google.firebase.database.DatabaseReference;import com.google.firebase.database.FirebaseDatabase;import com.google.firebase.database.ValueEventListener; public class AddCourseActivity extends AppCompatActivity { // creating variables for our button, edit text, // firebase database, database reference, progress bar. private Button addCourseBtn; private TextInputEditText courseNameEdt, courseDescEdt, coursePriceEdt, bestSuitedEdt, courseImgEdt, courseLinkEdt; FirebaseDatabase firebaseDatabase; DatabaseReference databaseReference; private ProgressBar loadingPB; private String courseID; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_course); // initializing all our variables. addCourseBtn = findViewById(R.id.idBtnAddCourse); courseNameEdt = findViewById(R.id.idEdtCourseName); courseDescEdt = findViewById(R.id.idEdtCourseDescription); coursePriceEdt = findViewById(R.id.idEdtCoursePrice); bestSuitedEdt = findViewById(R.id.idEdtSuitedFor); courseImgEdt = findViewById(R.id.idEdtCourseImageLink); courseLinkEdt = findViewById(R.id.idEdtCourseLink); loadingPB = findViewById(R.id.idPBLoading); firebaseDatabase = FirebaseDatabase.getInstance(); // on below line creating our database reference. databaseReference = firebaseDatabase.getReference("Courses"); // adding click listener for our add course button. addCourseBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { loadingPB.setVisibility(View.VISIBLE); // getting data from our edit text. String courseName = courseNameEdt.getText().toString(); String courseDesc = courseDescEdt.getText().toString(); String coursePrice = coursePriceEdt.getText().toString(); String bestSuited = bestSuitedEdt.getText().toString(); String courseImg = courseImgEdt.getText().toString(); String courseLink = courseLinkEdt.getText().toString(); courseID = courseName; // on below line we are passing all data to our modal class. CourseRVModal courseRVModal = new CourseRVModal(courseID, courseName, courseDesc, coursePrice, bestSuited, courseImg, courseLink); // on below line we are calling a add value event // to pass data to firebase database. databaseReference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { // on below line we are setting data in our firebase database. databaseReference.child(courseID).setValue(courseRVModal); // displaying a toast message. Toast.makeText(AddCourseActivity.this, "Course Added..", Toast.LENGTH_SHORT).show(); // starting a main activity. startActivity(new Intent(AddCourseActivity.this, MainActivity.class)); } @Override public void onCancelled(@NonNull DatabaseError error) { // displaying a failure message on below line. Toast.makeText(AddCourseActivity.this, "Fail to add Course..", Toast.LENGTH_SHORT).show(); } }); } }); }} Step 15: Creating an item for each course inside our Recycler View. Navigate to app > res > Right-click on it > New Layout Resource file and name it as course_rv_item and add the below code to it. Comments are added in the code to get to know in more detail. XML <?xml version="1.0" encoding="utf-8"?><androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_margin="5dp" app:cardCornerRadius="4dp" app:cardElevation="3dp"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/black_shade_1"> <!--image view for our course--> <ImageView android:id="@+id/idIVCourse" android:layout_width="match_parent" android:layout_height="200dp" android:scaleType="centerCrop" /> <!--text view for course name--> <TextView android:id="@+id/idTVCOurseName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idIVCourse" android:layout_margin="3dp" android:layout_toStartOf="@id/idTVCousePrice" android:layout_toLeftOf="@id/idTVCousePrice" android:padding="4dp" android:text="Course Name" android:textColor="@color/white" android:textSize="15sp" android:textStyle="bold" /> <!--text view for course price--> <TextView android:id="@+id/idTVCousePrice" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/idIVCourse" android:layout_alignParentEnd="true" android:layout_alignParentRight="true" android:layout_margin="3dp" android:gravity="center" android:padding="4dp" android:text="Price" android:textColor="@color/white" android:textSize="15sp" android:textStyle="bold" /> </RelativeLayout> </androidx.cardview.widget.CardView> Step 16: Working with activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to it. Comments are added in the code to get to know in more detail. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout 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:id="@+id/idRLHome" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/black_shade_1" tools:context=".MainActivity"> <!--recycler view for our data--> <androidx.recyclerview.widget.RecyclerView android:id="@+id/idRVCourses" android:layout_width="match_parent" android:layout_height="wrap_content" tools:listitem="@layout/course_rv_item" /> <!--progress bar for loading indicator--> <ProgressBar android:id="@+id/idPBLoading" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:indeterminate="true" android:indeterminateDrawable="@drawable/progress_back" /> <!--floating action button--> <com.google.android.material.floatingactionbutton.FloatingActionButton android:id="@+id/idFABAddCourse" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentEnd="true" android:layout_alignParentRight="true" android:layout_alignParentBottom="true" android:layout_margin="20dp" android:src="@drawable/ic_add" app:background="@color/black_shade_1" app:backgroundTint="@color/black_shade_2" app:tint="@color/white" /> </RelativeLayout> Step 17: Creating an Adapter class for setting data to each item of RecyclerView Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as CourseRVAdapter and add the below code to it. Comments are added in the code to get to know in more detail. Java package com.gtappdevelopers.firebasecrudapp; import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.view.animation.Animation;import android.view.animation.AnimationUtils;import android.widget.ImageView;import android.widget.TextView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; import com.squareup.picasso.Picasso; import java.util.ArrayList; public class CourseRVAdapter extends RecyclerView.Adapter<CourseRVAdapter.ViewHolder> { // creating variables for our list, context, interface and position. private ArrayList<CourseRVModal> courseRVModalArrayList; private Context context; private CourseClickInterface courseClickInterface; int lastPos = -1; // creating a constructor. public CourseRVAdapter(ArrayList<CourseRVModal> courseRVModalArrayList, Context context, CourseClickInterface courseClickInterface) { this.courseRVModalArrayList = courseRVModalArrayList; this.context = context; this.courseClickInterface = courseClickInterface; } @NonNull @Override public CourseRVAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // inflating our layout file on below line. View view = LayoutInflater.from(context).inflate(R.layout.course_rv_item, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull CourseRVAdapter.ViewHolder holder, int position) { // setting data to our recycler view item on below line. CourseRVModal courseRVModal = courseRVModalArrayList.get(position); holder.courseTV.setText(courseRVModal.getCourseName()); holder.coursePriceTV.setText("Rs. " + courseRVModal.getCoursePrice()); Picasso.get().load(courseRVModal.getCourseImg()).into(holder.courseIV); // adding animation to recycler view item on below line. setAnimation(holder.itemView, position); holder.courseIV.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { courseClickInterface.onCourseClick(position); } }); } private void setAnimation(View itemView, int position) { if (position > lastPos) { // on below line we are setting animation. Animation animation = AnimationUtils.loadAnimation(context, android.R.anim.slide_in_left); itemView.setAnimation(animation); lastPos = position; } } @Override public int getItemCount() { return courseRVModalArrayList.size(); } public static class ViewHolder extends RecyclerView.ViewHolder { // creating variable for our image view and text view on below line. private ImageView courseIV; private TextView courseTV, coursePriceTV; public ViewHolder(@NonNull View itemView) { super(itemView); // initializing all our variables on below line. courseIV = itemView.findViewById(R.id.idIVCourse); courseTV = itemView.findViewById(R.id.idTVCOurseName); coursePriceTV = itemView.findViewById(R.id.idTVCousePrice); } } // creating a interface for on click public interface CourseClickInterface { void onCourseClick(int position); }} Step 18: Creating a menu file for displaying menu options Navigate to the app > res > Right-click on it > New > Directory and name it as menu. Now navigate to the menu directory, Right-click on it > New > Menu Resource file and name it as menu_main.xml and add the below code to it. Comments are added in the code to get to know in more detail. XML <?xml version="1.0" encoding="utf-8"?><menu xmlns:android="http://schemas.android.com/apk/res/android"> <!--specifying item for displaying option--> <item android:id="@+id/idLogOut" android:icon="@drawable/ic_logout" android:title="Log Out" /></menu> Step 19: Creating a layout file for displaying a bottom sheet Navigate to the app > res > layout > Right-click on it > New > Layout Resource file and name it as bottom_sheet_layout and add below code to it. Comments are added in the code to get to know in more detail. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/idRLBSheet" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/black_shade_1" android:padding="4dp"> <!--text view for displaying course name--> <TextView android:id="@+id/idTVCourseName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="3dp" android:padding="4dp" android:text="Course Name" android:textColor="@color/white" android:textSize="15sp" android:textStyle="bold" /> <!--image view for displaying course image--> <ImageView android:id="@+id/idIVCourse" android:layout_width="100dp" android:layout_height="100dp" android:layout_below="@id/idTVCourseName" android:layout_centerVertical="true" android:layout_margin="4dp" android:padding="4dp" android:src="@drawable/ic_launcher_background" /> <!--text view for displaying course description--> <TextView android:id="@+id/idTVCourseDesc" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idTVCourseName" android:layout_margin="4dp" android:layout_toEndOf="@id/idIVCourse" android:layout_toRightOf="@id/idIVCourse" android:padding="3dp" android:text="Description" android:textColor="@color/white" /> <!--text view for displaying course best suited for--> <TextView android:id="@+id/idTVSuitedFor" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idTVCourseDesc" android:layout_margin="4dp" android:layout_toRightOf="@id/idIVCourse" android:padding="3dp" android:text="Suited for" android:textColor="@color/white" /> <!--text view for displaying course price--> <TextView android:id="@+id/idTVCoursePrice" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idTVSuitedFor" android:layout_margin="4dp" android:layout_toRightOf="@id/idIVCourse" android:padding="3dp" android:text="Price" android:textColor="@color/white" android:textSize="18sp" android:textStyle="bold" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idTVCoursePrice" android:orientation="horizontal" android:weightSum="2"> <!--button for editing course--> <Button android:id="@+id/idBtnEditCourse" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_margin="6dp" android:layout_weight="1" android:text="Edit Course" android:textAllCaps="false" /> <!--button for viewing course details--> <Button android:id="@+id/idBtnVIewDetails" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_margin="6dp" android:layout_weight="1" android:text="View Details" android:textAllCaps="false" /> </LinearLayout> </RelativeLayout> Step 20: Working with the MainActivity.java file Navigate to the app > java > your app’s package name > MainActivity.java file and add the below code to it. Comments are added in the code to get to know in detail. Java package com.gtappdevelopers.firebasecrudapp; import android.content.Intent;import android.net.Uri;import android.os.Bundle;import android.view.LayoutInflater;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.Button;import android.widget.ImageView;import android.widget.ProgressBar;import android.widget.RelativeLayout;import android.widget.TextView;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.annotation.Nullable;import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView; import com.google.android.material.bottomsheet.BottomSheetDialog;import com.google.android.material.floatingactionbutton.FloatingActionButton;import com.google.firebase.auth.FirebaseAuth;import com.google.firebase.database.ChildEventListener;import com.google.firebase.database.DataSnapshot;import com.google.firebase.database.DatabaseError;import com.google.firebase.database.DatabaseReference;import com.google.firebase.database.FirebaseDatabase;import com.squareup.picasso.Picasso; import java.util.ArrayList; public class MainActivity extends AppCompatActivity implements CourseRVAdapter.CourseClickInterface { // creating variables for fab, firebase database, // progress bar, list, adapter,firebase auth, // recycler view and relative layout. private FloatingActionButton addCourseFAB; FirebaseDatabase firebaseDatabase; DatabaseReference databaseReference; private RecyclerView courseRV; private FirebaseAuth mAuth; private ProgressBar loadingPB; private ArrayList<CourseRVModal> courseRVModalArrayList; private CourseRVAdapter courseRVAdapter; private RelativeLayout homeRL; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing all our variables. courseRV = findViewById(R.id.idRVCourses); homeRL = findViewById(R.id.idRLBSheet); loadingPB = findViewById(R.id.idPBLoading); addCourseFAB = findViewById(R.id.idFABAddCourse); firebaseDatabase = FirebaseDatabase.getInstance(); mAuth = FirebaseAuth.getInstance(); courseRVModalArrayList = new ArrayList<>(); // on below line we are getting database reference. databaseReference = firebaseDatabase.getReference("Courses"); // on below line adding a click listener for our floating action button. addCourseFAB.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // opening a new activity for adding a course. Intent i = new Intent(MainActivity.this, AddCourseActivity.class); startActivity(i); } }); // on below line initializing our adapter class. courseRVAdapter = new CourseRVAdapter(courseRVModalArrayList, this, this::onCourseClick); // setting layout malinger to recycler view on below line. courseRV.setLayoutManager(new LinearLayoutManager(this)); // setting adapter to recycler view on below line. courseRV.setAdapter(courseRVAdapter); // on below line calling a method to fetch courses from database. getCourses(); } private void getCourses() { // on below line clearing our list. courseRVModalArrayList.clear(); // on below line we are calling add child event listener method to read the data. databaseReference.addChildEventListener(new ChildEventListener() { @Override public void onChildAdded(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) { // on below line we are hiding our progress bar. loadingPB.setVisibility(View.GONE); // adding snapshot to our array list on below line. courseRVModalArrayList.add(snapshot.getValue(CourseRVModal.class)); // notifying our adapter that data has changed. courseRVAdapter.notifyDataSetChanged(); } @Override public void onChildChanged(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) { // this method is called when new child is added // we are notifying our adapter and making progress bar // visibility as gone. loadingPB.setVisibility(View.GONE); courseRVAdapter.notifyDataSetChanged(); } @Override public void onChildRemoved(@NonNull DataSnapshot snapshot) { // notifying our adapter when child is removed. courseRVAdapter.notifyDataSetChanged(); loadingPB.setVisibility(View.GONE); } @Override public void onChildMoved(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) { // notifying our adapter when child is moved. courseRVAdapter.notifyDataSetChanged(); loadingPB.setVisibility(View.GONE); } @Override public void onCancelled(@NonNull DatabaseError error) { } }); } @Override public void onCourseClick(int position) { // calling a method to display a bottom sheet on below line. displayBottomSheet(courseRVModalArrayList.get(position)); } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { // adding a click listener for option selected on below line. int id = item.getItemId(); switch (id) { case R.id.idLogOut: // displaying a toast message on user logged out inside on click. Toast.makeText(getApplicationContext(), "User Logged Out", Toast.LENGTH_LONG).show(); // on below line we are signing out our user. mAuth.signOut(); // on below line we are opening our login activity. Intent i = new Intent(MainActivity.this, LoginActivity.class); startActivity(i); this.finish(); return true; default: return super.onOptionsItemSelected(item); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // on below line we are inflating our menu // file for displaying our menu options. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } private void displayBottomSheet(CourseRVModal modal) { // on below line we are creating our bottom sheet dialog. final BottomSheetDialog bottomSheetTeachersDialog = new BottomSheetDialog(this, R.style.BottomSheetDialogTheme); // on below line we are inflating our layout file for our bottom sheet. View layout = LayoutInflater.from(this).inflate(R.layout.bottom_sheet_layout, homeRL); // setting content view for bottom sheet on below line. bottomSheetTeachersDialog.setContentView(layout); // on below line we are setting a cancelable bottomSheetTeachersDialog.setCancelable(false); bottomSheetTeachersDialog.setCanceledOnTouchOutside(true); // calling a method to display our bottom sheet. bottomSheetTeachersDialog.show(); // on below line we are creating variables for // our text view and image view inside bottom sheet // and initialing them with their ids. TextView courseNameTV = layout.findViewById(R.id.idTVCourseName); TextView courseDescTV = layout.findViewById(R.id.idTVCourseDesc); TextView suitedForTV = layout.findViewById(R.id.idTVSuitedFor); TextView priceTV = layout.findViewById(R.id.idTVCoursePrice); ImageView courseIV = layout.findViewById(R.id.idIVCourse); // on below line we are setting data to different views on below line. courseNameTV.setText(modal.getCourseName()); courseDescTV.setText(modal.getCourseDescription()); suitedForTV.setText("Suited for " + modal.getBestSuitedFor()); priceTV.setText("Rs." + modal.getCoursePrice()); Picasso.get().load(modal.getCourseImg()).into(courseIV); Button viewBtn = layout.findViewById(R.id.idBtnVIewDetails); Button editBtn = layout.findViewById(R.id.idBtnEditCourse); // adding on click listener for our edit button. editBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // on below line we are opening our EditCourseActivity on below line. Intent i = new Intent(MainActivity.this, EditCourseActivity.class); // on below line we are passing our course modal i.putExtra("course", modal); startActivity(i); } }); // adding click listener for our view button on below line. viewBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // on below line we are navigating to browser // for displaying course details from its url Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(modal.getCourseLink())); startActivity(i); } }); }} Step 21: Working with activity_edit_course.xml file Navigate to the app > res > layout > activity_edit_course.xml and add the below code to it. Comments are added in the code to get to know in detail. XML <?xml version="1.0" encoding="utf-8"?><ScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/black_shade_1" tools:context=".EditCourseActivity"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <!--edit text for adding a course name--> <com.google.android.material.textfield.TextInputLayout android:id="@+id/idTILCourseName" style="@style/LoginTextInputLayoutStyle" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:layout_marginTop="10dp" android:layout_marginRight="10dp" android:hint="Enter Course Name" android:padding="5dp" android:textColorHint="@color/white" app:hintTextColor="@color/white"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/idEdtCourseName" android:layout_width="match_parent" android:layout_height="match_parent" android:ems="10" android:importantForAutofill="no" android:inputType="textImeMultiLine|textMultiLine" android:textColor="@color/white" android:textColorHint="@color/white" android:textSize="14sp" /> </com.google.android.material.textfield.TextInputLayout> <!--edit text for adding a course price--> <com.google.android.material.textfield.TextInputLayout android:id="@+id/idTILCoursePrice" style="@style/LoginTextInputLayoutStyle" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:layout_marginTop="10dp" android:layout_marginRight="10dp" android:hint="Enter Course Price" android:padding="5dp" android:textColorHint="@color/white" app:boxStrokeColor="@color/purple_200" app:hintTextColor="@color/white"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/idEdtCoursePrice" android:layout_width="match_parent" android:layout_height="match_parent" android:ems="10" android:importantForAutofill="no" android:inputType="phone" android:textColor="@color/white" android:textColorHint="@color/white" android:textSize="14sp" app:boxStrokeColor="@color/purple_200" /> </com.google.android.material.textfield.TextInputLayout> <!--edit text for adding a course best suited for--> <com.google.android.material.textfield.TextInputLayout android:id="@+id/idTILCourseSuitedFor" style="@style/LoginTextInputLayoutStyle" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:layout_marginTop="10dp" android:layout_marginRight="10dp" android:hint="Enter Course Suited For" android:padding="5dp" android:textColorHint="@color/white" app:hintTextColor="@color/white"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/idEdtSuitedFor" android:layout_width="match_parent" android:layout_height="match_parent" android:ems="10" android:importantForAutofill="no" android:inputType="textImeMultiLine|textMultiLine" android:textColor="@color/white" android:textColorHint="@color/white" android:textSize="14sp" /> </com.google.android.material.textfield.TextInputLayout> <!--edit text for adding a course image link--> <com.google.android.material.textfield.TextInputLayout android:id="@+id/idTILCourseImageLink" style="@style/LoginTextInputLayoutStyle" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:layout_marginTop="10dp" android:layout_marginRight="10dp" android:hint="Enter Course Image Link" android:padding="5dp" android:textColorHint="@color/white" app:hintTextColor="@color/white"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/idEdtCourseImageLink" android:layout_width="match_parent" android:layout_height="match_parent" android:ems="10" android:importantForAutofill="no" android:inputType="textImeMultiLine|textMultiLine" android:textColor="@color/white" android:textColorHint="@color/white" android:textSize="14sp" /> </com.google.android.material.textfield.TextInputLayout> <!--edit text for adding a course link--> <com.google.android.material.textfield.TextInputLayout android:id="@+id/idTILCourseLink" style="@style/LoginTextInputLayoutStyle" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:layout_marginTop="10dp" android:layout_marginRight="10dp" android:hint="Enter Course Link" android:padding="5dp" android:textColorHint="@color/white" app:hintTextColor="@color/white"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/idEdtCourseLink" android:layout_width="match_parent" android:layout_height="match_parent" android:ems="10" android:importantForAutofill="no" android:inputType="textImeMultiLine|textMultiLine" android:textColor="@color/white" android:textColorHint="@color/white" android:textSize="14sp" /> </com.google.android.material.textfield.TextInputLayout> <!--edit text for adding a course description--> <com.google.android.material.textfield.TextInputLayout android:id="@+id/idTILCourseDescription" style="@style/LoginTextInputLayoutStyle" android:layout_width="match_parent" android:layout_height="200dp" android:layout_marginLeft="10dp" android:layout_marginTop="10dp" android:layout_marginRight="10dp" android:hint="Enter Course Description" android:padding="5dp" android:textColorHint="@color/white" app:hintTextColor="@color/white"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/idEdtCourseDescription" android:layout_width="match_parent" android:layout_height="match_parent" android:ems="10" android:importantForAutofill="no" android:inputType="textImeMultiLine|textMultiLine" android:textColor="@color/white" android:textColorHint="@color/white" android:textSize="14sp" /> </com.google.android.material.textfield.TextInputLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:weightSum="2"> <!--button for updating a new course--> <Button android:id="@+id/idBtnAddCourse" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginStart="10dp" android:layout_marginTop="10dp" android:layout_marginEnd="10dp" android:layout_marginBottom="10dp" android:layout_weight="1" android:background="@drawable/button_back" android:text="Update Your \n Course" android:textAllCaps="false" /> <!--button for deleting a course--> <Button android:id="@+id/idBtnDeleteCourse" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginStart="10dp" android:layout_marginTop="10dp" android:layout_marginEnd="10dp" android:layout_marginBottom="10dp" android:layout_weight="1" android:background="@drawable/button_back" android:text="Delete Your \n Course" android:textAllCaps="false" /> </LinearLayout> </LinearLayout> <!--progress bar for displaying a loading indicator--> <ProgressBar android:id="@+id/idPBLoading" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:layout_gravity="center" android:layout_marginTop="20dp" android:indeterminate="true" android:indeterminateDrawable="@drawable/progress_back" android:visibility="gone" /> </RelativeLayout> </ScrollView> Step 22: Working with the EditCourseActivity.java file Navigate to the app > java > your app’s package name > EditCourseActivity.java file and add the below code to it. Comments are added in the code to get to know in more detail. Java package com.gtappdevelopers.firebasecrudapp; import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.ProgressBar;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity; import com.google.android.material.textfield.TextInputEditText;import com.google.firebase.database.DataSnapshot;import com.google.firebase.database.DatabaseError;import com.google.firebase.database.DatabaseReference;import com.google.firebase.database.FirebaseDatabase;import com.google.firebase.database.ValueEventListener; import java.util.HashMap;import java.util.Map; public class EditCourseActivity extends AppCompatActivity { // creating variables for our edit text, firebase database, // database reference, course rv modal,progress bar. private TextInputEditText courseNameEdt, courseDescEdt, coursePriceEdt, bestSuitedEdt, courseImgEdt, courseLinkEdt; FirebaseDatabase firebaseDatabase; DatabaseReference databaseReference; CourseRVModal courseRVModal; private ProgressBar loadingPB; // creating a string for our course id. private String courseID; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_course); // initializing all our variables on below line. Button addCourseBtn = findViewById(R.id.idBtnAddCourse); courseNameEdt = findViewById(R.id.idEdtCourseName); courseDescEdt = findViewById(R.id.idEdtCourseDescription); coursePriceEdt = findViewById(R.id.idEdtCoursePrice); bestSuitedEdt = findViewById(R.id.idEdtSuitedFor); courseImgEdt = findViewById(R.id.idEdtCourseImageLink); courseLinkEdt = findViewById(R.id.idEdtCourseLink); loadingPB = findViewById(R.id.idPBLoading); firebaseDatabase = FirebaseDatabase.getInstance(); // on below line we are getting our modal class on which we have passed. courseRVModal = getIntent().getParcelableExtra("course"); Button deleteCourseBtn = findViewById(R.id.idBtnDeleteCourse); if (courseRVModal != null) { // on below line we are setting data to our edit text from our modal class. courseNameEdt.setText(courseRVModal.getCourseName()); coursePriceEdt.setText(courseRVModal.getCoursePrice()); bestSuitedEdt.setText(courseRVModal.getBestSuitedFor()); courseImgEdt.setText(courseRVModal.getCourseImg()); courseLinkEdt.setText(courseRVModal.getCourseLink()); courseDescEdt.setText(courseRVModal.getCourseDescription()); courseID = courseRVModal.getCourseId(); } // on below line we are initialing our database reference and we are adding a child as our course id. databaseReference = firebaseDatabase.getReference("Courses").child(courseID); // on below line we are adding click listener for our add course button. addCourseBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // on below line we are making our progress bar as visible. loadingPB.setVisibility(View.VISIBLE); // on below line we are getting data from our edit text. String courseName = courseNameEdt.getText().toString(); String courseDesc = courseDescEdt.getText().toString(); String coursePrice = coursePriceEdt.getText().toString(); String bestSuited = bestSuitedEdt.getText().toString(); String courseImg = courseImgEdt.getText().toString(); String courseLink = courseLinkEdt.getText().toString(); // on below line we are creating a map for // passing a data using key and value pair. Map<String, Object> map = new HashMap<>(); map.put("courseName", courseName); map.put("courseDescription", courseDesc); map.put("coursePrice", coursePrice); map.put("bestSuitedFor", bestSuited); map.put("courseImg", courseImg); map.put("courseLink", courseLink); map.put("courseId", courseID); // on below line we are calling a database reference on // add value event listener and on data change method databaseReference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { // making progress bar visibility as gone. loadingPB.setVisibility(View.GONE); // adding a map to our database. databaseReference.updateChildren(map); // on below line we are displaying a toast message. Toast.makeText(EditCourseActivity.this, "Course Updated..", Toast.LENGTH_SHORT).show(); // opening a new activity after updating our coarse. startActivity(new Intent(EditCourseActivity.this, MainActivity.class)); } @Override public void onCancelled(@NonNull DatabaseError error) { // displaying a failure message on toast. Toast.makeText(EditCourseActivity.this, "Fail to update course..", Toast.LENGTH_SHORT).show(); } }); } }); // adding a click listener for our delete course button. deleteCourseBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // calling a method to delete a course. deleteCourse(); } }); } private void deleteCourse() { // on below line calling a method to delete the course. databaseReference.removeValue(); // displaying a toast message on below line. Toast.makeText(this, "Course Deleted..", Toast.LENGTH_SHORT).show(); // opening a main activity on below line. startActivity(new Intent(EditCourseActivity.this, MainActivity.class)); }} Note: All the drawable used inside the application are present in the app > res > drawable. You can check out the project on the below GitHub link. Now run your app and see the output of the app. Output: ruhelaa48 surinderdawra388 varshagumber28 sweetyty Android Java Project Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Android SDK and it's Components Flutter - Custom Bottom Navigation Bar Retrofit with Kotlin Coroutine in Android How to Post Data to API using Retrofit in Android? Flutter - Stack Widget Arrays in Java Split() String method in Java with examples Arrays.sort() in Java with examples Reverse a string in Java For-each loop in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n10 Jan, 2022" }, { "code": null, "e": 642, "s": 54, "text": "Firebase is a famous product of Google which is used by so many developers to add backend functionality for their website as well as apps. The Firebase will make your job really easier for the backend database and handling the database. In this article, we will take a look at the implementation of the Firebase Realtime Database in Android. In this article, we will be adding an Email and password authentication inside our app and along with that, we will be performing the CRUD (Create, Read, Update and Delete) operations inside our application using the Firebase Realtime Database. " }, { "code": null, "e": 686, "s": 642, "text": "https://www.youtube.com/watch?v=-Gvpf8tXpbc" }, { "code": null, "e": 1096, "s": 686, "text": "In this article, we will be building a simple Android Application in which we will be firstly authenticating the user with their email and password. After that, we will display the list of courses that are available on Geeks for Geeks in the recycler view. We will be able to perform CRUD operations on these courses. Below is the video in which we will get to see what we are going to build in this article. " }, { "code": null, "e": 1126, "s": 1096, "text": "Step 1: Create a new Project " }, { "code": null, "e": 1288, "s": 1126, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 1325, "s": 1288, "text": "Step 2: Connect your app to Firebase" }, { "code": null, "e": 1529, "s": 1325, "text": "After creating a new project navigate to the Tools option on the top bar. Inside that click on Firebase. After clicking on Firebase, you can get to see the right column mentioned below in the screenshot." }, { "code": null, "e": 1868, "s": 1529, "text": "Inside that column Navigate to Firebase Realtime Database. Click on that option and you will get to see two options on Connect app to Firebase and Add Firebase Realtime Database to your app. Click on Connect now and your app will be connected to Firebase. After that click on the second option and now your App is connected to Firebase. " }, { "code": null, "e": 1946, "s": 1868, "text": "After connecting your app to Firebase you will get to see the below screen. " }, { "code": null, "e": 2402, "s": 1946, "text": "After that verify that dependency for the Firebase Realtime database has been added to our Gradle file. Now navigate to the app > Gradle Scripts and inside that file check whether the below dependency is added or not. If the below dependency is not added in your build.gradle file. Add the below dependency in the dependencies section. Below is the complete dependencies section in which there are dependencies for authentication as well as the database. " }, { "code": null, "e": 3185, "s": 2402, "text": "dependencies {\n implementation 'androidx.appcompat:appcompat:1.3.0'\n implementation 'com.google.android.material:material:1.4.0'\n // dependency for picasso for loading image from url \n implementation 'com.squareup.picasso:picasso:2.71828'\n implementation 'androidx.constraintlayout:constraintlayout:2.0.4'\n // dependency for firebase database. \n implementation 'com.google.firebase:firebase-database:20.0.0'\n implementation platform('com.google.firebase:firebase-bom:28.2.1')\n // dependency for firebase authentication. \n implementation 'com.google.firebase:firebase-auth'\n testImplementation 'junit:junit:4.+'\n androidTestImplementation 'androidx.test.ext:junit:1.1.3'\n androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'\n}" }, { "code": null, "e": 3418, "s": 3185, "text": "After adding this dependency sync your project and now we are ready for creating our app. If you want to know more about connecting your app to Firebase. Refer to this article to get in detail about Adding Firebase to Android App. " }, { "code": null, "e": 3464, "s": 3418, "text": "Step 3: Creating 4 different empty activities" }, { "code": null, "e": 3704, "s": 3464, "text": "Navigate to the app > Your app’s package name > Right-click on it > New > Activity > Select Empty Activity and Create a New Activity. Below is the name for the four different activities which we have to pass while creating new activities. " }, { "code": null, "e": 3774, "s": 3704, "text": "AddCourseActivity: This activity we will use for adding a new Course." }, { "code": null, "e": 3870, "s": 3774, "text": "EditCourseActivity: This activity will be used to edit our course as well as delete our course." }, { "code": null, "e": 3956, "s": 3870, "text": "LoginActivity: This activity will be used for Login purposes for existing user login." }, { "code": null, "e": 4031, "s": 3956, "text": "RegisterActivity: This activity is used for the registration of new Users." }, { "code": null, "e": 4147, "s": 4031, "text": "MainActivity.java file will be already present in which we will be displaying the list of courses in RecyclerView. " }, { "code": null, "e": 4193, "s": 4147, "text": "Step 4: Working with AndroidManifest.xml file" }, { "code": null, "e": 4476, "s": 4193, "text": "Navigate to app > AndroidManifest.xml file and add internet permissions to it. Below is the complete code for the AndroidManifest.xml file. Inside this file, we are also changing our launcher activity to Login Activity. Comments are added in the code to get to know in more detail. " }, { "code": null, "e": 4480, "s": 4476, "text": "XML" }, { "code": "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.gtappdevelopers.firebasecrudapp\"> <!--permissions for internet--> <uses-permission android:name=\"android.permission.INTERNET\" /> <uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\" /> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:roundIcon=\"@mipmap/ic_launcher_round\" android:supportsRtl=\"true\" android:theme=\"@style/Theme.FirebaseCrudApp\"> <activity android:name=\".EditCourseActivity\" android:label=\"Edit Course\" /> <activity android:name=\".AddCourseActivity\" android:label=\"Add Course\" /> <activity android:name=\".RegisterActivity\" android:label=\"Register\" /> <!--login activity is set as launcher activity--> <activity android:name=\".LoginActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> <activity android:name=\".MainActivity\" /> </application> </manifest>", "e": 5763, "s": 4480, "text": null }, { "code": null, "e": 5797, "s": 5763, "text": " Step 5: Updating colors.xml file" }, { "code": null, "e": 5878, "s": 5797, "text": "Navigate to the app > res > values > colors.xml and add the below colors to it. " }, { "code": null, "e": 5882, "s": 5878, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><resources xmlns:tools=\"http://schemas.android.com/tools\"> <color name=\"purple_200\">#296D98</color> <color name=\"purple_500\">#296D98</color> <color name=\"purple_700\">#296D98</color> <color name=\"teal_200\">#FF03DAC5</color> <color name=\"teal_700\">#FF018786</color> <color name=\"black\">#FF000000</color> <color name=\"white\">#FFFFFFFF</color> <color name=\"black_shade_1\">#0e2433</color> <color name=\"black_shade_2\">#1C4966</color> <color name=\"black_shade_3\">#22252D</color> <color name=\"mtrl_textinput_default_box_stroke_color\" tools:override=\"true\">#296D98</color> <color name=\"light_blue_shade_1\">#296D98</color> <color name=\"gray\">#424242</color> <color name=\"yellow\">#ffa500</color> <color name=\"dark_blue_shade\">#0D2162</color> <color name=\"dark_blue_shade_2\">#17388E</color> <color name=\"light_blue_shade\">#12B2E6</color> </resources>", "e": 6813, "s": 5882, "text": null }, { "code": null, "e": 6852, "s": 6813, "text": " Step 6: Updating our themes.xml file " }, { "code": null, "e": 6931, "s": 6852, "text": "Navigate to the app > res > values > themes.xml and add the below code to it. " }, { "code": null, "e": 6935, "s": 6931, "text": "XML" }, { "code": "<resources xmlns:tools=\"http://schemas.android.com/tools\"> <!-- Base application theme. --> <style name=\"Theme.FirebaseCrudApp\" parent=\"Theme.MaterialComponents.DayNight.DarkActionBar\"> <!-- Primary brand color. --> <item name=\"colorPrimary\">@color/purple_500</item> <item name=\"colorPrimaryVariant\">@color/purple_700</item> <item name=\"colorOnPrimary\">@color/white</item> <!-- Secondary brand color. --> <item name=\"colorSecondary\">@color/teal_200</item> <item name=\"colorSecondaryVariant\">@color/teal_700</item> <item name=\"colorOnSecondary\">@color/black</item> <!-- Status bar color. --> <item name=\"android:statusBarColor\" tools:targetApi=\"l\">?attr/colorPrimaryVariant</item> <!-- Customize your theme here. --> </style> <style name=\"AppBottomSheetDialogTheme\" parent=\"Theme.Design.Light.BottomSheetDialog\"> <item name=\"bottomSheetStyle\">@style/AppModalStyle</item> </style> <style name=\"BottomSheetDialogTheme\" parent=\"Theme.Design.Light.BottomSheetDialog\"> <item name=\"bottomSheetStyle\">@style/BottomSheetStyle</item> </style> <style name=\"BottomSheetStyle\" parent=\"Widget.Design.BottomSheet.Modal\"> <item name=\"android:background\">@android:color/transparent</item> </style> <style name=\"AppModalStyle\" parent=\"Widget.Design.BottomSheet.Modal\"> <item name=\"android:background\">@drawable/rounded_drawable</item> </style> <style name=\"LoginTextInputLayoutStyle\" parent=\"Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense\"> <item name=\"boxStrokeColor\">#296D98</item> <item name=\"boxStrokeWidth\">1dp</item> </style> </resources>", "e": 8639, "s": 6935, "text": null }, { "code": null, "e": 8727, "s": 8639, "text": " Step 7: Creating a custom background for our button and custom progress bar background" }, { "code": null, "e": 8924, "s": 8727, "text": "Navigate to the app > res > drawable > Right-click on it > New Drawable Resource file and name it as button_back and add below code to it. Comments are added in the code to get to know in detail. " }, { "code": null, "e": 8928, "s": 8924, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><shape xmlns:android=\"http://schemas.android.com/apk/res/android\" android:shape=\"rectangle\"> <!--for specifying corner radius--> <corners android:radius=\"20dp\" /> <!-- for specifying solid color--> <solid android:color=\"@color/black_shade_1\" /> </shape>", "e": 9235, "s": 8928, "text": null }, { "code": null, "e": 9439, "s": 9235, "text": " Navigate to the app > res > drawable > Right-click on it > New Drawable Resource file and name it as progress_back and add the below code to it. Comments are added in the code to get to know in detail. " }, { "code": null, "e": 9443, "s": 9439, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><rotate xmlns:android=\"http://schemas.android.com/apk/res/android\" android:fromDegrees=\"0\" android:pivotX=\"50%\" android:pivotY=\"50%\" android:toDegrees=\"360\"> <!--shape tag is used to build a shape in XML--> <shape android:innerRadiusRatio=\"3\" android:shape=\"ring\" android:thicknessRatio=\"8\" android:useLevel=\"false\"> <!--set the size of the shape--> <size android:width=\"76dip\" android:height=\"76dip\" /> <!--set the color gradients of the shape--> <gradient android:angle=\"0\" android:endColor=\"#00ffffff\" android:startColor=\"@color/purple_200\" android:type=\"sweep\" android:useLevel=\"false\" /> </shape> </rotate>", "e": 10271, "s": 9443, "text": null }, { "code": null, "e": 10320, "s": 10271, "text": " Step 8: Working with activity_register.xml file" }, { "code": null, "e": 10463, "s": 10320, "text": "Navigate to the app > res > activity_register.xml and add the below code to it. Comments are added in the code to get to know in more detail. " }, { "code": null, "e": 10467, "s": 10463, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"@color/black_shade_1\" tools:context=\".RegisterActivity\"> <!--edit text for user name--> <com.google.android.material.textfield.TextInputLayout android:id=\"@+id/idTILUserName\" style=\"@style/LoginTextInputLayoutStyle\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"20dp\" android:layout_marginTop=\"140dp\" android:layout_marginEnd=\"20dp\" android:hint=\"Enter User Name\" android:padding=\"5dp\" android:textColorHint=\"@color/white\" app:hintTextColor=\"@color/white\"> <com.google.android.material.textfield.TextInputEditText android:id=\"@+id/idEdtUserName\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:ems=\"10\" android:importantForAutofill=\"no\" android:inputType=\"textEmailAddress\" android:textColor=\"@color/white\" android:textColorHint=\"@color/white\" android:textSize=\"14sp\" /> </com.google.android.material.textfield.TextInputLayout> <!--edit text for user password--> <com.google.android.material.textfield.TextInputLayout android:id=\"@+id/idTILPassword\" style=\"@style/LoginTextInputLayoutStyle\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idTILUserName\" android:layout_marginStart=\"20dp\" android:layout_marginTop=\"20dp\" android:layout_marginEnd=\"20dp\" android:hint=\"Enter Your Password\" android:padding=\"5dp\" android:textColorHint=\"@color/white\" app:hintTextColor=\"@color/white\"> <com.google.android.material.textfield.TextInputEditText android:id=\"@+id/idEdtPassword\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:ems=\"10\" android:importantForAutofill=\"no\" android:inputType=\"textPassword\" android:textColor=\"@color/white\" android:textColorHint=\"@color/white\" android:textSize=\"14sp\" /> </com.google.android.material.textfield.TextInputLayout> <!--edit text for confirmation of user password--> <com.google.android.material.textfield.TextInputLayout android:id=\"@+id/idTILConfirmPassword\" style=\"@style/LoginTextInputLayoutStyle\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idTILPassword\" android:layout_marginStart=\"20dp\" android:layout_marginTop=\"20dp\" android:layout_marginEnd=\"20dp\" android:hint=\"Confirm Your Password\" android:padding=\"5dp\" android:textColorHint=\"@color/white\" app:hintTextColor=\"@color/white\"> <com.google.android.material.textfield.TextInputEditText android:id=\"@+id/idEdtConfirmPassword\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:ems=\"10\" android:importantForAutofill=\"no\" android:inputType=\"textPassword\" android:textColor=\"@color/white\" android:textColorHint=\"@color/white\" android:textSize=\"14sp\" /> </com.google.android.material.textfield.TextInputLayout> <!--button for creating user account.--> <Button android:id=\"@+id/idBtnRegister\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idTILConfirmPassword\" android:layout_marginStart=\"25dp\" android:layout_marginTop=\"40dp\" android:layout_marginEnd=\"25dp\" android:background=\"@drawable/button_back\" android:text=\"Register\" android:textAllCaps=\"false\" /> <!--text view for displaying a text on clicking we will open a login page--> <TextView android:id=\"@+id/idTVLoginUser\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idBtnRegister\" android:layout_marginTop=\"40dp\" android:gravity=\"center\" android:padding=\"10dp\" android:text=\"Already a User ? Login Here\" android:textAlignment=\"center\" android:textAllCaps=\"false\" android:textColor=\"@color/white\" android:textSize=\"18sp\" /> <!--progress bar as a loading indicator--> <ProgressBar android:id=\"@+id/idPBLoading\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:indeterminate=\"true\" android:indeterminateDrawable=\"@drawable/progress_back\" android:visibility=\"gone\" /> </RelativeLayout>", "e": 15576, "s": 10467, "text": null }, { "code": null, "e": 15625, "s": 15576, "text": " Step 9: Working with RegisterActivity.java file" }, { "code": null, "e": 15800, "s": 15625, "text": "Navigate to the app > java > your app’s package name > RegisterActivity.java file and add the below code to it. Comments are added in the code to get to know in more detail. " }, { "code": null, "e": 15805, "s": 15800, "text": "Java" }, { "code": "package com.gtappdevelopers.firebasecrudapp; import android.content.Intent;import android.os.Bundle;import android.text.TextUtils;import android.view.View;import android.widget.Button;import android.widget.ProgressBar;import android.widget.TextView;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity; import com.google.android.gms.tasks.OnCompleteListener;import com.google.android.gms.tasks.Task;import com.google.android.material.textfield.TextInputEditText;import com.google.firebase.auth.AuthResult;import com.google.firebase.auth.FirebaseAuth; public class RegisterActivity extends AppCompatActivity { // creating variables for edit text and textview, // firebase auth, button and progress bar. private TextInputEditText userNameEdt, passwordEdt, confirmPwdEdt; private TextView loginTV; private Button registerBtn; private FirebaseAuth mAuth; private ProgressBar loadingPB; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); // initializing all our variables. userNameEdt = findViewById(R.id.idEdtUserName); passwordEdt = findViewById(R.id.idEdtPassword); loadingPB = findViewById(R.id.idPBLoading); confirmPwdEdt = findViewById(R.id.idEdtConfirmPassword); loginTV = findViewById(R.id.idTVLoginUser); registerBtn = findViewById(R.id.idBtnRegister); mAuth = FirebaseAuth.getInstance(); // adding on click for login tv. loginTV.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // opening a login activity on clicking login text. Intent i = new Intent(RegisterActivity.this, LoginActivity.class); startActivity(i); } }); // adding click listener for register button. registerBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // hiding our progress bar. loadingPB.setVisibility(View.VISIBLE); // getting data fro =m our edit text. String userName = userNameEdt.getText().toString(); String pwd = passwordEdt.getText().toString(); String cnfPwd = confirmPwdEdt.getText().toString(); // checking if the password and confirm password is equal or not. if (!pwd.equals(cnfPwd)) { Toast.makeText(RegisterActivity.this, \"Please check both having same password..\", Toast.LENGTH_SHORT).show(); } else if (TextUtils.isEmpty(userName) && TextUtils.isEmpty(pwd) && TextUtils.isEmpty(cnfPwd)) { // checking if the text fields are empty or not. Toast.makeText(RegisterActivity.this, \"Please enter your credentials..\", Toast.LENGTH_SHORT).show(); } else { // on below line we are creating a new user by passing email and password. mAuth.createUserWithEmailAndPassword(userName, pwd).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { // on below line we are checking if the task is success or not. if (task.isSuccessful()) { // in on success method we are hiding our progress bar and opening a login activity. loadingPB.setVisibility(View.GONE); Toast.makeText(RegisterActivity.this, \"User Registered..\", Toast.LENGTH_SHORT).show(); Intent i = new Intent(RegisterActivity.this, LoginActivity.class); startActivity(i); finish(); } else { // in else condition we are displaying a failure toast message. loadingPB.setVisibility(View.GONE); Toast.makeText(RegisterActivity.this, \"Fail to register user..\", Toast.LENGTH_SHORT).show(); } } }); } } }); }}", "e": 20267, "s": 15805, "text": null }, { "code": null, "e": 20314, "s": 20267, "text": " Step 10: Working with activity_login.xml file" }, { "code": null, "e": 20454, "s": 20314, "text": "Navigate to the app > res > activity_login.xml and add the below code to it. Comments are added in the code to get to know in more detail. " }, { "code": null, "e": 20458, "s": 20454, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"@color/black_shade_1\" tools:context=\".LoginActivity\"> <!--edit text for user name--> <com.google.android.material.textfield.TextInputLayout android:id=\"@+id/idTILUserName\" style=\"@style/LoginTextInputLayoutStyle\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"20dp\" android:layout_marginTop=\"140dp\" android:layout_marginEnd=\"20dp\" android:hint=\"Enter User Name\" android:padding=\"5dp\" android:textColorHint=\"@color/white\" app:hintTextColor=\"@color/white\"> <com.google.android.material.textfield.TextInputEditText android:id=\"@+id/idEdtUserName\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:ems=\"10\" android:importantForAutofill=\"no\" android:inputType=\"textEmailAddress\" android:textColor=\"@color/white\" android:textColorHint=\"@color/white\" android:textSize=\"14sp\" /> </com.google.android.material.textfield.TextInputLayout> <!--edit text for password--> <com.google.android.material.textfield.TextInputLayout android:id=\"@+id/idTILPassword\" style=\"@style/LoginTextInputLayoutStyle\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idTILUserName\" android:layout_marginStart=\"20dp\" android:layout_marginTop=\"40dp\" android:layout_marginEnd=\"20dp\" android:hint=\"Enter your Password\" android:padding=\"5dp\" android:textColorHint=\"@color/white\" app:hintTextColor=\"@color/white\"> <com.google.android.material.textfield.TextInputEditText android:id=\"@+id/idEdtPassword\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:ems=\"10\" android:importantForAutofill=\"no\" android:inputType=\"textPassword\" android:textColor=\"@color/white\" android:textColorHint=\"@color/white\" android:textSize=\"14sp\" /> </com.google.android.material.textfield.TextInputLayout> <!--button for login--> <Button android:id=\"@+id/idBtnLogin\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idTILPassword\" android:layout_marginStart=\"25dp\" android:layout_marginTop=\"40dp\" android:layout_marginEnd=\"25dp\" android:background=\"@drawable/button_back\" android:text=\"Login\" android:textAllCaps=\"false\" /> <!--text view for creating a new account--> <TextView android:id=\"@+id/idTVNewUser\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idBtnLogin\" android:layout_marginTop=\"40dp\" android:gravity=\"center\" android:padding=\"10dp\" android:text=\"New User ? Register Here\" android:textAlignment=\"center\" android:textAllCaps=\"false\" android:textColor=\"@color/white\" android:textSize=\"18sp\" /> <!--progress-bar for loading indicator--> <ProgressBar android:id=\"@+id/idPBLoading\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idTVNewUser\" android:layout_centerHorizontal=\"true\" android:layout_marginTop=\"10dp\" android:indeterminate=\"true\" android:indeterminateDrawable=\"@drawable/progress_back\" android:visibility=\"gone\" /> </RelativeLayout>", "e": 24437, "s": 20458, "text": null }, { "code": null, "e": 24484, "s": 24437, "text": " Step 11: Working with LoginActivity.java file" }, { "code": null, "e": 24656, "s": 24484, "text": "Navigate to the app > java > your app’s package name > LoginActivity.java file and add the below code to it. Comments are added in the code to get to know in more detail. " }, { "code": null, "e": 24661, "s": 24656, "text": "Java" }, { "code": "package com.gtappdevelopers.firebasecrudapp; import android.content.Intent;import android.os.Bundle;import android.text.TextUtils;import android.view.View;import android.widget.Button;import android.widget.ProgressBar;import android.widget.TextView;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity; import com.google.android.gms.tasks.OnCompleteListener;import com.google.android.gms.tasks.Task;import com.google.android.material.textfield.TextInputEditText;import com.google.firebase.auth.AuthResult;import com.google.firebase.auth.FirebaseAuth;import com.google.firebase.auth.FirebaseUser; public class LoginActivity extends AppCompatActivity { // creating variable for edit text, textview, // button, progress bar and firebase auth. private TextInputEditText userNameEdt, passwordEdt; private Button loginBtn; private TextView newUserTV; private FirebaseAuth mAuth; private ProgressBar loadingPB; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); // initializing all our variables. userNameEdt = findViewById(R.id.idEdtUserName); passwordEdt = findViewById(R.id.idEdtPassword); loginBtn = findViewById(R.id.idBtnLogin); newUserTV = findViewById(R.id.idTVNewUser); mAuth = FirebaseAuth.getInstance(); loadingPB = findViewById(R.id.idPBLoading); // adding click listener for our new user tv. newUserTV.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // on below line opening a login activity. Intent i = new Intent(LoginActivity.this, RegisterActivity.class); startActivity(i); } }); // adding on click listener for our login button. loginBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // hiding our progress bar. loadingPB.setVisibility(View.VISIBLE); // getting data from our edit text on below line. String email = userNameEdt.getText().toString(); String password = passwordEdt.getText().toString(); // on below line validating the text input. if (TextUtils.isEmpty(email) && TextUtils.isEmpty(password)) { Toast.makeText(LoginActivity.this, \"Please enter your credentials..\", Toast.LENGTH_SHORT).show(); return; } // on below line we are calling a sign in method and passing email and password to it. mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { // on below line we are checking if the task is success or not. if (task.isSuccessful()) { // on below line we are hiding our progress bar. loadingPB.setVisibility(View.GONE); Toast.makeText(LoginActivity.this, \"Login Successful..\", Toast.LENGTH_SHORT).show(); // on below line we are opening our mainactivity. Intent i = new Intent(LoginActivity.this, MainActivity.class); startActivity(i); finish(); } else { // hiding our progress bar and displaying a toast message. loadingPB.setVisibility(View.GONE); Toast.makeText(LoginActivity.this, \"Please enter valid user credentials..\", Toast.LENGTH_SHORT).show(); } } }); } }); } @Override protected void onStart() { super.onStart(); // in on start method checking if // the user is already sign in. FirebaseUser user = mAuth.getCurrentUser(); if (user != null) { // if the user is not null then we are // opening a main activity on below line. Intent i = new Intent(LoginActivity.this, MainActivity.class); startActivity(i); this.finish(); } }}", "e": 29156, "s": 24661, "text": null }, { "code": null, "e": 29243, "s": 29156, "text": " Step 12: Creating a Modal class for our data to be displayed inside our RecyclerView" }, { "code": null, "e": 29457, "s": 29243, "text": "Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as CourseRVModal and add the below code to it. Comments are added in the code to get to know in more detail. " }, { "code": null, "e": 29462, "s": 29457, "text": "Java" }, { "code": "package com.gtappdevelopers.firebasecrudapp; import android.os.Parcel;import android.os.Parcelable; public class CourseRVModal implements Parcelable { // creating variables for our different fields. private String courseName; private String courseDescription; private String coursePrice; private String bestSuitedFor; private String courseImg; private String courseLink; private String courseId; public String getCourseId() { return courseId; } public void setCourseId(String courseId) { this.courseId = courseId; } // creating an empty constructor. public CourseRVModal() { } protected CourseRVModal(Parcel in) { courseName = in.readString(); courseId = in.readString(); courseDescription = in.readString(); coursePrice = in.readString(); bestSuitedFor = in.readString(); courseImg = in.readString(); courseLink = in.readString(); } public static final Creator<CourseRVModal> CREATOR = new Creator<CourseRVModal>() { @Override public CourseRVModal createFromParcel(Parcel in) { return new CourseRVModal(in); } @Override public CourseRVModal[] newArray(int size) { return new CourseRVModal[size]; } }; // creating getter and setter methods. public String getCourseName() { return courseName; } public void setCourseName(String courseName) { this.courseName = courseName; } public String getCourseDescription() { return courseDescription; } public void setCourseDescription(String courseDescription) { this.courseDescription = courseDescription; } public String getCoursePrice() { return coursePrice; } public void setCoursePrice(String coursePrice) { this.coursePrice = coursePrice; } public String getBestSuitedFor() { return bestSuitedFor; } public void setBestSuitedFor(String bestSuitedFor) { this.bestSuitedFor = bestSuitedFor; } public String getCourseImg() { return courseImg; } public void setCourseImg(String courseImg) { this.courseImg = courseImg; } public String getCourseLink() { return courseLink; } public void setCourseLink(String courseLink) { this.courseLink = courseLink; } public CourseRVModal(String courseId, String courseName, String courseDescription, String coursePrice, String bestSuitedFor, String courseImg, String courseLink) { this.courseName = courseName; this.courseId = courseId; this.courseDescription = courseDescription; this.coursePrice = coursePrice; this.bestSuitedFor = bestSuitedFor; this.courseImg = courseImg; this.courseLink = courseLink; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(courseName); dest.writeString(courseId); dest.writeString(courseDescription); dest.writeString(coursePrice); dest.writeString(bestSuitedFor); dest.writeString(courseImg); dest.writeString(courseLink); }}", "e": 32681, "s": 29462, "text": null }, { "code": null, "e": 32735, "s": 32683, "text": " Step 13: Working with activity_add_course.xml file" }, { "code": null, "e": 32889, "s": 32735, "text": "Navigate to the app > res > layout > activity_add_course.xml and add the below code to it. Comments are added in the code to get to know in more detail. " }, { "code": null, "e": 32893, "s": 32889, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><ScrollView xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"@color/black_shade_1\" tools:context=\".AddCourseActivity\"> <RelativeLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\"> <!--edit text for course name--> <com.google.android.material.textfield.TextInputLayout android:id=\"@+id/idTILCourseName\" style=\"@style/LoginTextInputLayoutStyle\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginLeft=\"10dp\" android:layout_marginTop=\"10dp\" android:layout_marginRight=\"10dp\" android:hint=\"Enter Course Name\" android:padding=\"5dp\" android:textColorHint=\"@color/white\" app:hintTextColor=\"@color/white\"> <com.google.android.material.textfield.TextInputEditText android:id=\"@+id/idEdtCourseName\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:ems=\"10\" android:importantForAutofill=\"no\" android:inputType=\"textImeMultiLine|textMultiLine\" android:textColor=\"@color/white\" android:textColorHint=\"@color/white\" android:textSize=\"14sp\" /> </com.google.android.material.textfield.TextInputLayout> <!--edit text for course price--> <com.google.android.material.textfield.TextInputLayout android:id=\"@+id/idTILCoursePrice\" style=\"@style/LoginTextInputLayoutStyle\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginLeft=\"10dp\" android:layout_marginTop=\"10dp\" android:layout_marginRight=\"10dp\" android:hint=\"Enter Course Price\" android:padding=\"5dp\" android:textColorHint=\"@color/white\" app:boxStrokeColor=\"@color/purple_200\" app:hintTextColor=\"@color/white\"> <com.google.android.material.textfield.TextInputEditText android:id=\"@+id/idEdtCoursePrice\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:ems=\"10\" android:importantForAutofill=\"no\" android:inputType=\"phone\" android:textColor=\"@color/white\" android:textColorHint=\"@color/white\" android:textSize=\"14sp\" app:boxStrokeColor=\"@color/purple_200\" /> </com.google.android.material.textfield.TextInputLayout> <!--edit text for course suited for--> <com.google.android.material.textfield.TextInputLayout android:id=\"@+id/idTILCourseSuitedFor\" style=\"@style/LoginTextInputLayoutStyle\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginLeft=\"10dp\" android:layout_marginTop=\"10dp\" android:layout_marginRight=\"10dp\" android:hint=\"Enter Course Suited For\" android:padding=\"5dp\" android:textColorHint=\"@color/white\" app:hintTextColor=\"@color/white\"> <com.google.android.material.textfield.TextInputEditText android:id=\"@+id/idEdtSuitedFor\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:ems=\"10\" android:importantForAutofill=\"no\" android:inputType=\"textImeMultiLine|textMultiLine\" android:textColor=\"@color/white\" android:textColorHint=\"@color/white\" android:textSize=\"14sp\" /> </com.google.android.material.textfield.TextInputLayout> <!--edit text for course image link--> <com.google.android.material.textfield.TextInputLayout android:id=\"@+id/idTILCourseImageLink\" style=\"@style/LoginTextInputLayoutStyle\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginLeft=\"10dp\" android:layout_marginTop=\"10dp\" android:layout_marginRight=\"10dp\" android:hint=\"Enter Course Image Link\" android:padding=\"5dp\" android:textColorHint=\"@color/white\" app:hintTextColor=\"@color/white\"> <com.google.android.material.textfield.TextInputEditText android:id=\"@+id/idEdtCourseImageLink\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:ems=\"10\" android:importantForAutofill=\"no\" android:inputType=\"textImeMultiLine|textMultiLine\" android:textColor=\"@color/white\" android:textColorHint=\"@color/white\" android:textSize=\"14sp\" /> </com.google.android.material.textfield.TextInputLayout> <!--edit text for course link--> <com.google.android.material.textfield.TextInputLayout android:id=\"@+id/idTILCourseLink\" style=\"@style/LoginTextInputLayoutStyle\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginLeft=\"10dp\" android:layout_marginTop=\"10dp\" android:layout_marginRight=\"10dp\" android:hint=\"Enter Course Link\" android:padding=\"5dp\" android:textColorHint=\"@color/white\" app:hintTextColor=\"@color/white\"> <com.google.android.material.textfield.TextInputEditText android:id=\"@+id/idEdtCourseLink\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:ems=\"10\" android:importantForAutofill=\"no\" android:inputType=\"textImeMultiLine|textMultiLine\" android:textColor=\"@color/white\" android:textColorHint=\"@color/white\" android:textSize=\"14sp\" /> </com.google.android.material.textfield.TextInputLayout> <!--edit text for course description--> <com.google.android.material.textfield.TextInputLayout android:id=\"@+id/idTILCourseDescription\" style=\"@style/LoginTextInputLayoutStyle\" android:layout_width=\"match_parent\" android:layout_height=\"200dp\" android:layout_marginLeft=\"10dp\" android:layout_marginTop=\"10dp\" android:layout_marginRight=\"10dp\" android:hint=\"Enter Course Description\" android:padding=\"5dp\" android:textColorHint=\"@color/white\" app:hintTextColor=\"@color/white\"> <com.google.android.material.textfield.TextInputEditText android:id=\"@+id/idEdtCourseDescription\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:ems=\"10\" android:importantForAutofill=\"no\" android:inputType=\"textImeMultiLine|textMultiLine\" android:textColor=\"@color/white\" android:textColorHint=\"@color/white\" android:textSize=\"14sp\" /> </com.google.android.material.textfield.TextInputLayout> <!--button for adding a new course--> <Button android:id=\"@+id/idBtnAddCourse\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"10dp\" android:layout_marginTop=\"10dp\" android:layout_marginEnd=\"10dp\" android:layout_marginBottom=\"10dp\" android:background=\"@drawable/button_back\" android:text=\"Add Your Course\" android:textAllCaps=\"false\" /> </LinearLayout> <!--progress bar for loading indicator--> <ProgressBar android:id=\"@+id/idPBLoading\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:layout_gravity=\"center\" android:indeterminate=\"true\" android:indeterminateDrawable=\"@drawable/progress_back\" android:visibility=\"gone\" /> </RelativeLayout></ScrollView>", "e": 42361, "s": 32893, "text": null }, { "code": null, "e": 42416, "s": 42361, "text": " Step 14: Working with the AddCourseActivity.java file" }, { "code": null, "e": 42592, "s": 42416, "text": "Navigate to the app > java > your app’s package name > AddCourseActivity.java file and add the below code to it. Comments are added in the code to get to know in more detail. " }, { "code": null, "e": 42597, "s": 42592, "text": "Java" }, { "code": "package com.gtappdevelopers.firebasecrudapp; import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.ProgressBar;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity; import com.google.android.material.textfield.TextInputEditText;import com.google.firebase.database.DataSnapshot;import com.google.firebase.database.DatabaseError;import com.google.firebase.database.DatabaseReference;import com.google.firebase.database.FirebaseDatabase;import com.google.firebase.database.ValueEventListener; public class AddCourseActivity extends AppCompatActivity { // creating variables for our button, edit text, // firebase database, database reference, progress bar. private Button addCourseBtn; private TextInputEditText courseNameEdt, courseDescEdt, coursePriceEdt, bestSuitedEdt, courseImgEdt, courseLinkEdt; FirebaseDatabase firebaseDatabase; DatabaseReference databaseReference; private ProgressBar loadingPB; private String courseID; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_course); // initializing all our variables. addCourseBtn = findViewById(R.id.idBtnAddCourse); courseNameEdt = findViewById(R.id.idEdtCourseName); courseDescEdt = findViewById(R.id.idEdtCourseDescription); coursePriceEdt = findViewById(R.id.idEdtCoursePrice); bestSuitedEdt = findViewById(R.id.idEdtSuitedFor); courseImgEdt = findViewById(R.id.idEdtCourseImageLink); courseLinkEdt = findViewById(R.id.idEdtCourseLink); loadingPB = findViewById(R.id.idPBLoading); firebaseDatabase = FirebaseDatabase.getInstance(); // on below line creating our database reference. databaseReference = firebaseDatabase.getReference(\"Courses\"); // adding click listener for our add course button. addCourseBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { loadingPB.setVisibility(View.VISIBLE); // getting data from our edit text. String courseName = courseNameEdt.getText().toString(); String courseDesc = courseDescEdt.getText().toString(); String coursePrice = coursePriceEdt.getText().toString(); String bestSuited = bestSuitedEdt.getText().toString(); String courseImg = courseImgEdt.getText().toString(); String courseLink = courseLinkEdt.getText().toString(); courseID = courseName; // on below line we are passing all data to our modal class. CourseRVModal courseRVModal = new CourseRVModal(courseID, courseName, courseDesc, coursePrice, bestSuited, courseImg, courseLink); // on below line we are calling a add value event // to pass data to firebase database. databaseReference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { // on below line we are setting data in our firebase database. databaseReference.child(courseID).setValue(courseRVModal); // displaying a toast message. Toast.makeText(AddCourseActivity.this, \"Course Added..\", Toast.LENGTH_SHORT).show(); // starting a main activity. startActivity(new Intent(AddCourseActivity.this, MainActivity.class)); } @Override public void onCancelled(@NonNull DatabaseError error) { // displaying a failure message on below line. Toast.makeText(AddCourseActivity.this, \"Fail to add Course..\", Toast.LENGTH_SHORT).show(); } }); } }); }}", "e": 46694, "s": 42597, "text": null }, { "code": null, "e": 46764, "s": 46696, "text": "Step 15: Creating an item for each course inside our Recycler View." }, { "code": null, "e": 46956, "s": 46764, "text": "Navigate to app > res > Right-click on it > New Layout Resource file and name it as course_rv_item and add the below code to it. Comments are added in the code to get to know in more detail. " }, { "code": null, "e": 46960, "s": 46956, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.cardview.widget.CardView xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:layout_margin=\"5dp\" app:cardCornerRadius=\"4dp\" app:cardElevation=\"3dp\"> <RelativeLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:background=\"@color/black_shade_1\"> <!--image view for our course--> <ImageView android:id=\"@+id/idIVCourse\" android:layout_width=\"match_parent\" android:layout_height=\"200dp\" android:scaleType=\"centerCrop\" /> <!--text view for course name--> <TextView android:id=\"@+id/idTVCOurseName\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idIVCourse\" android:layout_margin=\"3dp\" android:layout_toStartOf=\"@id/idTVCousePrice\" android:layout_toLeftOf=\"@id/idTVCousePrice\" android:padding=\"4dp\" android:text=\"Course Name\" android:textColor=\"@color/white\" android:textSize=\"15sp\" android:textStyle=\"bold\" /> <!--text view for course price--> <TextView android:id=\"@+id/idTVCousePrice\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idIVCourse\" android:layout_alignParentEnd=\"true\" android:layout_alignParentRight=\"true\" android:layout_margin=\"3dp\" android:gravity=\"center\" android:padding=\"4dp\" android:text=\"Price\" android:textColor=\"@color/white\" android:textSize=\"15sp\" android:textStyle=\"bold\" /> </RelativeLayout> </androidx.cardview.widget.CardView>", "e": 48991, "s": 46960, "text": null }, { "code": null, "e": 49038, "s": 48991, "text": " Step 16: Working with activity_main.xml file " }, { "code": null, "e": 49186, "s": 49038, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to it. Comments are added in the code to get to know in more detail. " }, { "code": null, "e": 49190, "s": 49186, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout 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:id=\"@+id/idRLHome\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"@color/black_shade_1\" tools:context=\".MainActivity\"> <!--recycler view for our data--> <androidx.recyclerview.widget.RecyclerView android:id=\"@+id/idRVCourses\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" tools:listitem=\"@layout/course_rv_item\" /> <!--progress bar for loading indicator--> <ProgressBar android:id=\"@+id/idPBLoading\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:indeterminate=\"true\" android:indeterminateDrawable=\"@drawable/progress_back\" /> <!--floating action button--> <com.google.android.material.floatingactionbutton.FloatingActionButton android:id=\"@+id/idFABAddCourse\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignParentEnd=\"true\" android:layout_alignParentRight=\"true\" android:layout_alignParentBottom=\"true\" android:layout_margin=\"20dp\" android:src=\"@drawable/ic_add\" app:background=\"@color/black_shade_1\" app:backgroundTint=\"@color/black_shade_2\" app:tint=\"@color/white\" /> </RelativeLayout>", "e": 50781, "s": 49190, "text": null }, { "code": null, "e": 50863, "s": 50781, "text": " Step 17: Creating an Adapter class for setting data to each item of RecyclerView" }, { "code": null, "e": 51079, "s": 50863, "text": "Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as CourseRVAdapter and add the below code to it. Comments are added in the code to get to know in more detail. " }, { "code": null, "e": 51084, "s": 51079, "text": "Java" }, { "code": "package com.gtappdevelopers.firebasecrudapp; import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.view.animation.Animation;import android.view.animation.AnimationUtils;import android.widget.ImageView;import android.widget.TextView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; import com.squareup.picasso.Picasso; import java.util.ArrayList; public class CourseRVAdapter extends RecyclerView.Adapter<CourseRVAdapter.ViewHolder> { // creating variables for our list, context, interface and position. private ArrayList<CourseRVModal> courseRVModalArrayList; private Context context; private CourseClickInterface courseClickInterface; int lastPos = -1; // creating a constructor. public CourseRVAdapter(ArrayList<CourseRVModal> courseRVModalArrayList, Context context, CourseClickInterface courseClickInterface) { this.courseRVModalArrayList = courseRVModalArrayList; this.context = context; this.courseClickInterface = courseClickInterface; } @NonNull @Override public CourseRVAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // inflating our layout file on below line. View view = LayoutInflater.from(context).inflate(R.layout.course_rv_item, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull CourseRVAdapter.ViewHolder holder, int position) { // setting data to our recycler view item on below line. CourseRVModal courseRVModal = courseRVModalArrayList.get(position); holder.courseTV.setText(courseRVModal.getCourseName()); holder.coursePriceTV.setText(\"Rs. \" + courseRVModal.getCoursePrice()); Picasso.get().load(courseRVModal.getCourseImg()).into(holder.courseIV); // adding animation to recycler view item on below line. setAnimation(holder.itemView, position); holder.courseIV.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { courseClickInterface.onCourseClick(position); } }); } private void setAnimation(View itemView, int position) { if (position > lastPos) { // on below line we are setting animation. Animation animation = AnimationUtils.loadAnimation(context, android.R.anim.slide_in_left); itemView.setAnimation(animation); lastPos = position; } } @Override public int getItemCount() { return courseRVModalArrayList.size(); } public static class ViewHolder extends RecyclerView.ViewHolder { // creating variable for our image view and text view on below line. private ImageView courseIV; private TextView courseTV, coursePriceTV; public ViewHolder(@NonNull View itemView) { super(itemView); // initializing all our variables on below line. courseIV = itemView.findViewById(R.id.idIVCourse); courseTV = itemView.findViewById(R.id.idTVCOurseName); coursePriceTV = itemView.findViewById(R.id.idTVCousePrice); } } // creating a interface for on click public interface CourseClickInterface { void onCourseClick(int position); }}", "e": 54456, "s": 51084, "text": null }, { "code": null, "e": 54516, "s": 54456, "text": " Step 18: Creating a menu file for displaying menu options" }, { "code": null, "e": 54804, "s": 54516, "text": "Navigate to the app > res > Right-click on it > New > Directory and name it as menu. Now navigate to the menu directory, Right-click on it > New > Menu Resource file and name it as menu_main.xml and add the below code to it. Comments are added in the code to get to know in more detail. " }, { "code": null, "e": 54808, "s": 54804, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><menu xmlns:android=\"http://schemas.android.com/apk/res/android\"> <!--specifying item for displaying option--> <item android:id=\"@+id/idLogOut\" android:icon=\"@drawable/ic_logout\" android:title=\"Log Out\" /></menu>", "e": 55086, "s": 54808, "text": null }, { "code": null, "e": 55151, "s": 55086, "text": " Step 19: Creating a layout file for displaying a bottom sheet " }, { "code": null, "e": 55359, "s": 55151, "text": "Navigate to the app > res > layout > Right-click on it > New > Layout Resource file and name it as bottom_sheet_layout and add below code to it. Comments are added in the code to get to know in more detail. " }, { "code": null, "e": 55363, "s": 55359, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:id=\"@+id/idRLBSheet\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:background=\"@color/black_shade_1\" android:padding=\"4dp\"> <!--text view for displaying course name--> <TextView android:id=\"@+id/idTVCourseName\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"3dp\" android:padding=\"4dp\" android:text=\"Course Name\" android:textColor=\"@color/white\" android:textSize=\"15sp\" android:textStyle=\"bold\" /> <!--image view for displaying course image--> <ImageView android:id=\"@+id/idIVCourse\" android:layout_width=\"100dp\" android:layout_height=\"100dp\" android:layout_below=\"@id/idTVCourseName\" android:layout_centerVertical=\"true\" android:layout_margin=\"4dp\" android:padding=\"4dp\" android:src=\"@drawable/ic_launcher_background\" /> <!--text view for displaying course description--> <TextView android:id=\"@+id/idTVCourseDesc\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idTVCourseName\" android:layout_margin=\"4dp\" android:layout_toEndOf=\"@id/idIVCourse\" android:layout_toRightOf=\"@id/idIVCourse\" android:padding=\"3dp\" android:text=\"Description\" android:textColor=\"@color/white\" /> <!--text view for displaying course best suited for--> <TextView android:id=\"@+id/idTVSuitedFor\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idTVCourseDesc\" android:layout_margin=\"4dp\" android:layout_toRightOf=\"@id/idIVCourse\" android:padding=\"3dp\" android:text=\"Suited for\" android:textColor=\"@color/white\" /> <!--text view for displaying course price--> <TextView android:id=\"@+id/idTVCoursePrice\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idTVSuitedFor\" android:layout_margin=\"4dp\" android:layout_toRightOf=\"@id/idIVCourse\" android:padding=\"3dp\" android:text=\"Price\" android:textColor=\"@color/white\" android:textSize=\"18sp\" android:textStyle=\"bold\" /> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idTVCoursePrice\" android:orientation=\"horizontal\" android:weightSum=\"2\"> <!--button for editing course--> <Button android:id=\"@+id/idBtnEditCourse\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_margin=\"6dp\" android:layout_weight=\"1\" android:text=\"Edit Course\" android:textAllCaps=\"false\" /> <!--button for viewing course details--> <Button android:id=\"@+id/idBtnVIewDetails\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_margin=\"6dp\" android:layout_weight=\"1\" android:text=\"View Details\" android:textAllCaps=\"false\" /> </LinearLayout> </RelativeLayout>", "e": 58802, "s": 55363, "text": null }, { "code": null, "e": 58853, "s": 58802, "text": " Step 20: Working with the MainActivity.java file " }, { "code": null, "e": 59019, "s": 58853, "text": "Navigate to the app > java > your app’s package name > MainActivity.java file and add the below code to it. Comments are added in the code to get to know in detail. " }, { "code": null, "e": 59024, "s": 59019, "text": "Java" }, { "code": "package com.gtappdevelopers.firebasecrudapp; import android.content.Intent;import android.net.Uri;import android.os.Bundle;import android.view.LayoutInflater;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.Button;import android.widget.ImageView;import android.widget.ProgressBar;import android.widget.RelativeLayout;import android.widget.TextView;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.annotation.Nullable;import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView; import com.google.android.material.bottomsheet.BottomSheetDialog;import com.google.android.material.floatingactionbutton.FloatingActionButton;import com.google.firebase.auth.FirebaseAuth;import com.google.firebase.database.ChildEventListener;import com.google.firebase.database.DataSnapshot;import com.google.firebase.database.DatabaseError;import com.google.firebase.database.DatabaseReference;import com.google.firebase.database.FirebaseDatabase;import com.squareup.picasso.Picasso; import java.util.ArrayList; public class MainActivity extends AppCompatActivity implements CourseRVAdapter.CourseClickInterface { // creating variables for fab, firebase database, // progress bar, list, adapter,firebase auth, // recycler view and relative layout. private FloatingActionButton addCourseFAB; FirebaseDatabase firebaseDatabase; DatabaseReference databaseReference; private RecyclerView courseRV; private FirebaseAuth mAuth; private ProgressBar loadingPB; private ArrayList<CourseRVModal> courseRVModalArrayList; private CourseRVAdapter courseRVAdapter; private RelativeLayout homeRL; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing all our variables. courseRV = findViewById(R.id.idRVCourses); homeRL = findViewById(R.id.idRLBSheet); loadingPB = findViewById(R.id.idPBLoading); addCourseFAB = findViewById(R.id.idFABAddCourse); firebaseDatabase = FirebaseDatabase.getInstance(); mAuth = FirebaseAuth.getInstance(); courseRVModalArrayList = new ArrayList<>(); // on below line we are getting database reference. databaseReference = firebaseDatabase.getReference(\"Courses\"); // on below line adding a click listener for our floating action button. addCourseFAB.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // opening a new activity for adding a course. Intent i = new Intent(MainActivity.this, AddCourseActivity.class); startActivity(i); } }); // on below line initializing our adapter class. courseRVAdapter = new CourseRVAdapter(courseRVModalArrayList, this, this::onCourseClick); // setting layout malinger to recycler view on below line. courseRV.setLayoutManager(new LinearLayoutManager(this)); // setting adapter to recycler view on below line. courseRV.setAdapter(courseRVAdapter); // on below line calling a method to fetch courses from database. getCourses(); } private void getCourses() { // on below line clearing our list. courseRVModalArrayList.clear(); // on below line we are calling add child event listener method to read the data. databaseReference.addChildEventListener(new ChildEventListener() { @Override public void onChildAdded(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) { // on below line we are hiding our progress bar. loadingPB.setVisibility(View.GONE); // adding snapshot to our array list on below line. courseRVModalArrayList.add(snapshot.getValue(CourseRVModal.class)); // notifying our adapter that data has changed. courseRVAdapter.notifyDataSetChanged(); } @Override public void onChildChanged(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) { // this method is called when new child is added // we are notifying our adapter and making progress bar // visibility as gone. loadingPB.setVisibility(View.GONE); courseRVAdapter.notifyDataSetChanged(); } @Override public void onChildRemoved(@NonNull DataSnapshot snapshot) { // notifying our adapter when child is removed. courseRVAdapter.notifyDataSetChanged(); loadingPB.setVisibility(View.GONE); } @Override public void onChildMoved(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) { // notifying our adapter when child is moved. courseRVAdapter.notifyDataSetChanged(); loadingPB.setVisibility(View.GONE); } @Override public void onCancelled(@NonNull DatabaseError error) { } }); } @Override public void onCourseClick(int position) { // calling a method to display a bottom sheet on below line. displayBottomSheet(courseRVModalArrayList.get(position)); } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { // adding a click listener for option selected on below line. int id = item.getItemId(); switch (id) { case R.id.idLogOut: // displaying a toast message on user logged out inside on click. Toast.makeText(getApplicationContext(), \"User Logged Out\", Toast.LENGTH_LONG).show(); // on below line we are signing out our user. mAuth.signOut(); // on below line we are opening our login activity. Intent i = new Intent(MainActivity.this, LoginActivity.class); startActivity(i); this.finish(); return true; default: return super.onOptionsItemSelected(item); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // on below line we are inflating our menu // file for displaying our menu options. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } private void displayBottomSheet(CourseRVModal modal) { // on below line we are creating our bottom sheet dialog. final BottomSheetDialog bottomSheetTeachersDialog = new BottomSheetDialog(this, R.style.BottomSheetDialogTheme); // on below line we are inflating our layout file for our bottom sheet. View layout = LayoutInflater.from(this).inflate(R.layout.bottom_sheet_layout, homeRL); // setting content view for bottom sheet on below line. bottomSheetTeachersDialog.setContentView(layout); // on below line we are setting a cancelable bottomSheetTeachersDialog.setCancelable(false); bottomSheetTeachersDialog.setCanceledOnTouchOutside(true); // calling a method to display our bottom sheet. bottomSheetTeachersDialog.show(); // on below line we are creating variables for // our text view and image view inside bottom sheet // and initialing them with their ids. TextView courseNameTV = layout.findViewById(R.id.idTVCourseName); TextView courseDescTV = layout.findViewById(R.id.idTVCourseDesc); TextView suitedForTV = layout.findViewById(R.id.idTVSuitedFor); TextView priceTV = layout.findViewById(R.id.idTVCoursePrice); ImageView courseIV = layout.findViewById(R.id.idIVCourse); // on below line we are setting data to different views on below line. courseNameTV.setText(modal.getCourseName()); courseDescTV.setText(modal.getCourseDescription()); suitedForTV.setText(\"Suited for \" + modal.getBestSuitedFor()); priceTV.setText(\"Rs.\" + modal.getCoursePrice()); Picasso.get().load(modal.getCourseImg()).into(courseIV); Button viewBtn = layout.findViewById(R.id.idBtnVIewDetails); Button editBtn = layout.findViewById(R.id.idBtnEditCourse); // adding on click listener for our edit button. editBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // on below line we are opening our EditCourseActivity on below line. Intent i = new Intent(MainActivity.this, EditCourseActivity.class); // on below line we are passing our course modal i.putExtra(\"course\", modal); startActivity(i); } }); // adding click listener for our view button on below line. viewBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // on below line we are navigating to browser // for displaying course details from its url Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(modal.getCourseLink())); startActivity(i); } }); }}", "e": 68432, "s": 59024, "text": null }, { "code": null, "e": 68488, "s": 68434, "text": " Step 21: Working with activity_edit_course.xml file " }, { "code": null, "e": 68637, "s": 68488, "text": "Navigate to the app > res > layout > activity_edit_course.xml and add the below code to it. Comments are added in the code to get to know in detail." }, { "code": null, "e": 68641, "s": 68637, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><ScrollView xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"@color/black_shade_1\" tools:context=\".EditCourseActivity\"> <RelativeLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\"> <!--edit text for adding a course name--> <com.google.android.material.textfield.TextInputLayout android:id=\"@+id/idTILCourseName\" style=\"@style/LoginTextInputLayoutStyle\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginLeft=\"10dp\" android:layout_marginTop=\"10dp\" android:layout_marginRight=\"10dp\" android:hint=\"Enter Course Name\" android:padding=\"5dp\" android:textColorHint=\"@color/white\" app:hintTextColor=\"@color/white\"> <com.google.android.material.textfield.TextInputEditText android:id=\"@+id/idEdtCourseName\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:ems=\"10\" android:importantForAutofill=\"no\" android:inputType=\"textImeMultiLine|textMultiLine\" android:textColor=\"@color/white\" android:textColorHint=\"@color/white\" android:textSize=\"14sp\" /> </com.google.android.material.textfield.TextInputLayout> <!--edit text for adding a course price--> <com.google.android.material.textfield.TextInputLayout android:id=\"@+id/idTILCoursePrice\" style=\"@style/LoginTextInputLayoutStyle\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginLeft=\"10dp\" android:layout_marginTop=\"10dp\" android:layout_marginRight=\"10dp\" android:hint=\"Enter Course Price\" android:padding=\"5dp\" android:textColorHint=\"@color/white\" app:boxStrokeColor=\"@color/purple_200\" app:hintTextColor=\"@color/white\"> <com.google.android.material.textfield.TextInputEditText android:id=\"@+id/idEdtCoursePrice\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:ems=\"10\" android:importantForAutofill=\"no\" android:inputType=\"phone\" android:textColor=\"@color/white\" android:textColorHint=\"@color/white\" android:textSize=\"14sp\" app:boxStrokeColor=\"@color/purple_200\" /> </com.google.android.material.textfield.TextInputLayout> <!--edit text for adding a course best suited for--> <com.google.android.material.textfield.TextInputLayout android:id=\"@+id/idTILCourseSuitedFor\" style=\"@style/LoginTextInputLayoutStyle\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginLeft=\"10dp\" android:layout_marginTop=\"10dp\" android:layout_marginRight=\"10dp\" android:hint=\"Enter Course Suited For\" android:padding=\"5dp\" android:textColorHint=\"@color/white\" app:hintTextColor=\"@color/white\"> <com.google.android.material.textfield.TextInputEditText android:id=\"@+id/idEdtSuitedFor\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:ems=\"10\" android:importantForAutofill=\"no\" android:inputType=\"textImeMultiLine|textMultiLine\" android:textColor=\"@color/white\" android:textColorHint=\"@color/white\" android:textSize=\"14sp\" /> </com.google.android.material.textfield.TextInputLayout> <!--edit text for adding a course image link--> <com.google.android.material.textfield.TextInputLayout android:id=\"@+id/idTILCourseImageLink\" style=\"@style/LoginTextInputLayoutStyle\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginLeft=\"10dp\" android:layout_marginTop=\"10dp\" android:layout_marginRight=\"10dp\" android:hint=\"Enter Course Image Link\" android:padding=\"5dp\" android:textColorHint=\"@color/white\" app:hintTextColor=\"@color/white\"> <com.google.android.material.textfield.TextInputEditText android:id=\"@+id/idEdtCourseImageLink\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:ems=\"10\" android:importantForAutofill=\"no\" android:inputType=\"textImeMultiLine|textMultiLine\" android:textColor=\"@color/white\" android:textColorHint=\"@color/white\" android:textSize=\"14sp\" /> </com.google.android.material.textfield.TextInputLayout> <!--edit text for adding a course link--> <com.google.android.material.textfield.TextInputLayout android:id=\"@+id/idTILCourseLink\" style=\"@style/LoginTextInputLayoutStyle\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginLeft=\"10dp\" android:layout_marginTop=\"10dp\" android:layout_marginRight=\"10dp\" android:hint=\"Enter Course Link\" android:padding=\"5dp\" android:textColorHint=\"@color/white\" app:hintTextColor=\"@color/white\"> <com.google.android.material.textfield.TextInputEditText android:id=\"@+id/idEdtCourseLink\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:ems=\"10\" android:importantForAutofill=\"no\" android:inputType=\"textImeMultiLine|textMultiLine\" android:textColor=\"@color/white\" android:textColorHint=\"@color/white\" android:textSize=\"14sp\" /> </com.google.android.material.textfield.TextInputLayout> <!--edit text for adding a course description--> <com.google.android.material.textfield.TextInputLayout android:id=\"@+id/idTILCourseDescription\" style=\"@style/LoginTextInputLayoutStyle\" android:layout_width=\"match_parent\" android:layout_height=\"200dp\" android:layout_marginLeft=\"10dp\" android:layout_marginTop=\"10dp\" android:layout_marginRight=\"10dp\" android:hint=\"Enter Course Description\" android:padding=\"5dp\" android:textColorHint=\"@color/white\" app:hintTextColor=\"@color/white\"> <com.google.android.material.textfield.TextInputEditText android:id=\"@+id/idEdtCourseDescription\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:ems=\"10\" android:importantForAutofill=\"no\" android:inputType=\"textImeMultiLine|textMultiLine\" android:textColor=\"@color/white\" android:textColorHint=\"@color/white\" android:textSize=\"14sp\" /> </com.google.android.material.textfield.TextInputLayout> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"horizontal\" android:weightSum=\"2\"> <!--button for updating a new course--> <Button android:id=\"@+id/idBtnAddCourse\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"10dp\" android:layout_marginTop=\"10dp\" android:layout_marginEnd=\"10dp\" android:layout_marginBottom=\"10dp\" android:layout_weight=\"1\" android:background=\"@drawable/button_back\" android:text=\"Update Your \\n Course\" android:textAllCaps=\"false\" /> <!--button for deleting a course--> <Button android:id=\"@+id/idBtnDeleteCourse\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"10dp\" android:layout_marginTop=\"10dp\" android:layout_marginEnd=\"10dp\" android:layout_marginBottom=\"10dp\" android:layout_weight=\"1\" android:background=\"@drawable/button_back\" android:text=\"Delete Your \\n Course\" android:textAllCaps=\"false\" /> </LinearLayout> </LinearLayout> <!--progress bar for displaying a loading indicator--> <ProgressBar android:id=\"@+id/idPBLoading\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:layout_gravity=\"center\" android:layout_marginTop=\"20dp\" android:indeterminate=\"true\" android:indeterminateDrawable=\"@drawable/progress_back\" android:visibility=\"gone\" /> </RelativeLayout> </ScrollView>", "e": 79213, "s": 68641, "text": null }, { "code": null, "e": 79269, "s": 79213, "text": " Step 22: Working with the EditCourseActivity.java file" }, { "code": null, "e": 79446, "s": 79269, "text": "Navigate to the app > java > your app’s package name > EditCourseActivity.java file and add the below code to it. Comments are added in the code to get to know in more detail. " }, { "code": null, "e": 79451, "s": 79446, "text": "Java" }, { "code": "package com.gtappdevelopers.firebasecrudapp; import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.ProgressBar;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity; import com.google.android.material.textfield.TextInputEditText;import com.google.firebase.database.DataSnapshot;import com.google.firebase.database.DatabaseError;import com.google.firebase.database.DatabaseReference;import com.google.firebase.database.FirebaseDatabase;import com.google.firebase.database.ValueEventListener; import java.util.HashMap;import java.util.Map; public class EditCourseActivity extends AppCompatActivity { // creating variables for our edit text, firebase database, // database reference, course rv modal,progress bar. private TextInputEditText courseNameEdt, courseDescEdt, coursePriceEdt, bestSuitedEdt, courseImgEdt, courseLinkEdt; FirebaseDatabase firebaseDatabase; DatabaseReference databaseReference; CourseRVModal courseRVModal; private ProgressBar loadingPB; // creating a string for our course id. private String courseID; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_course); // initializing all our variables on below line. Button addCourseBtn = findViewById(R.id.idBtnAddCourse); courseNameEdt = findViewById(R.id.idEdtCourseName); courseDescEdt = findViewById(R.id.idEdtCourseDescription); coursePriceEdt = findViewById(R.id.idEdtCoursePrice); bestSuitedEdt = findViewById(R.id.idEdtSuitedFor); courseImgEdt = findViewById(R.id.idEdtCourseImageLink); courseLinkEdt = findViewById(R.id.idEdtCourseLink); loadingPB = findViewById(R.id.idPBLoading); firebaseDatabase = FirebaseDatabase.getInstance(); // on below line we are getting our modal class on which we have passed. courseRVModal = getIntent().getParcelableExtra(\"course\"); Button deleteCourseBtn = findViewById(R.id.idBtnDeleteCourse); if (courseRVModal != null) { // on below line we are setting data to our edit text from our modal class. courseNameEdt.setText(courseRVModal.getCourseName()); coursePriceEdt.setText(courseRVModal.getCoursePrice()); bestSuitedEdt.setText(courseRVModal.getBestSuitedFor()); courseImgEdt.setText(courseRVModal.getCourseImg()); courseLinkEdt.setText(courseRVModal.getCourseLink()); courseDescEdt.setText(courseRVModal.getCourseDescription()); courseID = courseRVModal.getCourseId(); } // on below line we are initialing our database reference and we are adding a child as our course id. databaseReference = firebaseDatabase.getReference(\"Courses\").child(courseID); // on below line we are adding click listener for our add course button. addCourseBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // on below line we are making our progress bar as visible. loadingPB.setVisibility(View.VISIBLE); // on below line we are getting data from our edit text. String courseName = courseNameEdt.getText().toString(); String courseDesc = courseDescEdt.getText().toString(); String coursePrice = coursePriceEdt.getText().toString(); String bestSuited = bestSuitedEdt.getText().toString(); String courseImg = courseImgEdt.getText().toString(); String courseLink = courseLinkEdt.getText().toString(); // on below line we are creating a map for // passing a data using key and value pair. Map<String, Object> map = new HashMap<>(); map.put(\"courseName\", courseName); map.put(\"courseDescription\", courseDesc); map.put(\"coursePrice\", coursePrice); map.put(\"bestSuitedFor\", bestSuited); map.put(\"courseImg\", courseImg); map.put(\"courseLink\", courseLink); map.put(\"courseId\", courseID); // on below line we are calling a database reference on // add value event listener and on data change method databaseReference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { // making progress bar visibility as gone. loadingPB.setVisibility(View.GONE); // adding a map to our database. databaseReference.updateChildren(map); // on below line we are displaying a toast message. Toast.makeText(EditCourseActivity.this, \"Course Updated..\", Toast.LENGTH_SHORT).show(); // opening a new activity after updating our coarse. startActivity(new Intent(EditCourseActivity.this, MainActivity.class)); } @Override public void onCancelled(@NonNull DatabaseError error) { // displaying a failure message on toast. Toast.makeText(EditCourseActivity.this, \"Fail to update course..\", Toast.LENGTH_SHORT).show(); } }); } }); // adding a click listener for our delete course button. deleteCourseBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // calling a method to delete a course. deleteCourse(); } }); } private void deleteCourse() { // on below line calling a method to delete the course. databaseReference.removeValue(); // displaying a toast message on below line. Toast.makeText(this, \"Course Deleted..\", Toast.LENGTH_SHORT).show(); // opening a main activity on below line. startActivity(new Intent(EditCourseActivity.this, MainActivity.class)); }}", "e": 85778, "s": 79451, "text": null }, { "code": null, "e": 85928, "s": 85778, "text": "Note: All the drawable used inside the application are present in the app > res > drawable. You can check out the project on the below GitHub link. " }, { "code": null, "e": 85978, "s": 85928, "text": " Now run your app and see the output of the app. " }, { "code": null, "e": 85987, "s": 85978, "text": " Output:" }, { "code": null, "e": 85997, "s": 85987, "text": "ruhelaa48" }, { "code": null, "e": 86014, "s": 85997, "text": "surinderdawra388" }, { "code": null, "e": 86029, "s": 86014, "text": "varshagumber28" }, { "code": null, "e": 86038, "s": 86029, "text": "sweetyty" }, { "code": null, "e": 86046, "s": 86038, "text": "Android" }, { "code": null, "e": 86051, "s": 86046, "text": "Java" }, { "code": null, "e": 86059, "s": 86051, "text": "Project" }, { "code": null, "e": 86064, "s": 86059, "text": "Java" }, { "code": null, "e": 86072, "s": 86064, "text": "Android" }, { "code": null, "e": 86170, "s": 86072, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 86202, "s": 86170, "text": "Android SDK and it's Components" }, { "code": null, "e": 86241, "s": 86202, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 86283, "s": 86241, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 86334, "s": 86283, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 86357, "s": 86334, "text": "Flutter - Stack Widget" }, { "code": null, "e": 86372, "s": 86357, "text": "Arrays in Java" }, { "code": null, "e": 86416, "s": 86372, "text": "Split() String method in Java with examples" }, { "code": null, "e": 86452, "s": 86416, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 86477, "s": 86452, "text": "Reverse a string in Java" } ]
HTML | <button> formaction Attribute
31 May, 2019 The HTML <button> formaction Attribute is used to specify where to send the data of the form. After submission of form the formaction attribute called. The form data is to be sent to the server after submission of form. It overrides the feature of the action attribute of an <form> element. Syntax: <button type="submit" formaction="URL"> Attribute Values: It contains single value URL which is used to specify the URL of the document where the data to be sent after submission of the form. The possible value of URL are: absolute URL: It points to the full address of a page. For example: www.geeksforgeeks.org/data-structure relative URL: It is used to point to a file within in a webpage. For Example: gfg.php Example: <!DOCTYPE html><html> <head> <title> HTML <Button> formAction Attribute </title></head> <body style="text-align:center;"> <h1> GeeksForGeeks </h1> <h2> HTML <button> formAction Attribute </h2> <form action="#" method="get" target="_self"> <input type="submit" id="Geeks" name="myGeeks" value="Submit @ geeksforgeeks" formTarget="_blank" formMethod="post" formAction="test.php"> </form></body> </html> Output: Supported Browsers: The browsers supported by HTML button formaction Attribute are listed below: Google Chrome Internet Explorer Firefox Apple Safari Opera HTML-Attributes 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) HTTP headers | Content-Type Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Roadmap to Learn JavaScript For Beginners Remove elements from a JavaScript Array
[ { "code": null, "e": 28, "s": 0, "text": "\n31 May, 2019" }, { "code": null, "e": 319, "s": 28, "text": "The HTML <button> formaction Attribute is used to specify where to send the data of the form. After submission of form the formaction attribute called. The form data is to be sent to the server after submission of form. It overrides the feature of the action attribute of an <form> element." }, { "code": null, "e": 327, "s": 319, "text": "Syntax:" }, { "code": null, "e": 368, "s": 327, "text": "<button type=\"submit\" formaction=\"URL\"> " }, { "code": null, "e": 520, "s": 368, "text": "Attribute Values: It contains single value URL which is used to specify the URL of the document where the data to be sent after submission of the form." }, { "code": null, "e": 551, "s": 520, "text": "The possible value of URL are:" }, { "code": null, "e": 656, "s": 551, "text": "absolute URL: It points to the full address of a page. For example: www.geeksforgeeks.org/data-structure" }, { "code": null, "e": 742, "s": 656, "text": "relative URL: It is used to point to a file within in a webpage. For Example: gfg.php" }, { "code": null, "e": 751, "s": 742, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML <Button> formAction Attribute </title></head> <body style=\"text-align:center;\"> <h1> GeeksForGeeks </h1> <h2> HTML <button> formAction Attribute </h2> <form action=\"#\" method=\"get\" target=\"_self\"> <input type=\"submit\" id=\"Geeks\" name=\"myGeeks\" value=\"Submit @ geeksforgeeks\" formTarget=\"_blank\" formMethod=\"post\" formAction=\"test.php\"> </form></body> </html>", "e": 1302, "s": 751, "text": null }, { "code": null, "e": 1310, "s": 1302, "text": "Output:" }, { "code": null, "e": 1407, "s": 1310, "text": "Supported Browsers: The browsers supported by HTML button formaction Attribute are listed below:" }, { "code": null, "e": 1421, "s": 1407, "text": "Google Chrome" }, { "code": null, "e": 1439, "s": 1421, "text": "Internet Explorer" }, { "code": null, "e": 1447, "s": 1439, "text": "Firefox" }, { "code": null, "e": 1460, "s": 1447, "text": "Apple Safari" }, { "code": null, "e": 1466, "s": 1460, "text": "Opera" }, { "code": null, "e": 1482, "s": 1466, "text": "HTML-Attributes" }, { "code": null, "e": 1487, "s": 1482, "text": "HTML" }, { "code": null, "e": 1504, "s": 1487, "text": "Web Technologies" }, { "code": null, "e": 1509, "s": 1504, "text": "HTML" }, { "code": null, "e": 1607, "s": 1509, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1655, "s": 1607, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 1679, "s": 1655, "text": "REST API (Introduction)" }, { "code": null, "e": 1729, "s": 1679, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 1766, "s": 1729, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 1794, "s": 1766, "text": "HTTP headers | Content-Type" }, { "code": null, "e": 1827, "s": 1794, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1888, "s": 1827, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1931, "s": 1888, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 1973, "s": 1931, "text": "Roadmap to Learn JavaScript For Beginners" } ]
Python GUI – PyQt VS TKinter
11 Dec, 2020 A GUI toolkit contains widgets that are used to create a graphical interface. Python includes a wide range of Interface implementations available, from TkInter (it comes with Python, ) to a variety of various cross-platform solutions, such as PyQt5, which is known for its more sophisticated widgets and sleek look. PyQt is a toolkit for graphical user interface (GUI) widgets. It is extracted from the library of Qt. PyQt is the product of the combination of the Python language and the Qt library. PyQt is coming with the Qt Builder. We will use it to get the python code from the Qt Creator. With the support of a qt designer, we can build a GUI, and then we can get python code for that GUI. PyQt supports all platforms including Windows, macOS and UNIX. PyQt can be used to create stylish GUIs, a modern and portable python framework. Code: Python3 # Import sys for handle the # exit status of the application.import sys # Importing required widgetsfrom PyQt5.QtWidgets import QApplicationfrom PyQt5.QtWidgets import QLabelfrom PyQt5.QtWidgets import QWidget # To create an instance of QApplication# sys.argv contains the list of# command-line argumentapp = QApplication(sys.argv) # To create an instance of application GUI# root is an instance of QWidget,# it provides all the features to# create the application's windowroot = QWidget() # adding title to windowroot.setWindowTitle('Geeks App') # to place txt at the coordinatesroot.move(60, 15) # to display texttxt = QLabel('Welcome, Geeks!', parent = root) txt.move(60, 15) # Show application's GUIroot.show() # Run application's main loopsys.exit(app.exec_()) Output: A simple app to display text using PyQt. Coding versatility –GUI programming with Qt is built around the idea of signals and slots for creating contact between objects. This allows versatility in dealing with GUI incidents which results in a smoother code base. More than a framework : Qt uses a broad variety of native platform APIs for networking, database development, and more. It provides primary access to them through a special API. Various UI components: Qt provides multiple widgets, such as buttons or menus, all designed with a basic interface for all compatible platforms. Various learning resources: As PyQt is one of the most commonly used UI systems for Python, you can conveniently access a broad variety of documentation. Lack of Python-specific documentation for classes in PyQt5 It takes a lot of time to grasp all the specifics of PyQt, meaning it’s a pretty steep learning curve. If the application is not open-source, you must pay for a commercial license. Tkinter is an open-source Python Graphic User Interface (GUI) library well known for its simplicity. It comes pre-installed in Python, so you don’t even need to think about installing it. These characteristics make it a strong position for beginners and intermediates to begin with. Tkinter cannot be used for larger-scale projects. Code: Python3 # importing the module tkinterimport tkinter as tk # create main window (parent window)root = tk.Tk() # Label() it display box# where you can put any text. txt = tk.Label(root, text="Welcome to GeekForGeeks") # pack() It organizes the widgets# in blocks before placing in the parent widget.txt.pack() # running the main looproot.mainloop() Output: A simple app to display text using tkinter. Tkinter is easy and fast to implement as compared to any other GUI toolkit. Tkinter is more flexible and stable. Tkinter is included in Python, so nothing extra need to download. Tkinter provides a simple syntax. Tkinter is really easy to understand and master. Tkinter provides three geometry managers: place, pack, and grid. That is much more powerful and easy to use. Tkinter does not include advanced widgets. It has no similar tool as Qt Designer for Tkinter. It doesn’t have a reliable UI. Sometime, it is hard to debug in Tkinter. It is not purely Pythonic. PyQt Tkinter Python-gui Python-PyQt Python-tkinter Difference Between Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n11 Dec, 2020" }, { "code": null, "e": 371, "s": 53, "text": " A GUI toolkit contains widgets that are used to create a graphical interface. Python includes a wide range of Interface implementations available, from TkInter (it comes with Python, ) to a variety of various cross-platform solutions, such as PyQt5, which is known for its more sophisticated widgets and sleek look. " }, { "code": null, "e": 896, "s": 371, "text": "PyQt is a toolkit for graphical user interface (GUI) widgets. It is extracted from the library of Qt. PyQt is the product of the combination of the Python language and the Qt library. PyQt is coming with the Qt Builder. We will use it to get the python code from the Qt Creator. With the support of a qt designer, we can build a GUI, and then we can get python code for that GUI. PyQt supports all platforms including Windows, macOS and UNIX. PyQt can be used to create stylish GUIs, a modern and portable python framework. " }, { "code": null, "e": 902, "s": 896, "text": "Code:" }, { "code": null, "e": 910, "s": 902, "text": "Python3" }, { "code": "# Import sys for handle the # exit status of the application.import sys # Importing required widgetsfrom PyQt5.QtWidgets import QApplicationfrom PyQt5.QtWidgets import QLabelfrom PyQt5.QtWidgets import QWidget # To create an instance of QApplication# sys.argv contains the list of# command-line argumentapp = QApplication(sys.argv) # To create an instance of application GUI# root is an instance of QWidget,# it provides all the features to# create the application's windowroot = QWidget() # adding title to windowroot.setWindowTitle('Geeks App') # to place txt at the coordinatesroot.move(60, 15) # to display texttxt = QLabel('Welcome, Geeks!', parent = root) txt.move(60, 15) # Show application's GUIroot.show() # Run application's main loopsys.exit(app.exec_())", "e": 1688, "s": 910, "text": null }, { "code": null, "e": 1696, "s": 1688, "text": "Output:" }, { "code": null, "e": 1737, "s": 1696, "text": "A simple app to display text using PyQt." }, { "code": null, "e": 1958, "s": 1737, "text": "Coding versatility –GUI programming with Qt is built around the idea of signals and slots for creating contact between objects. This allows versatility in dealing with GUI incidents which results in a smoother code base." }, { "code": null, "e": 2136, "s": 1958, "text": "More than a framework : Qt uses a broad variety of native platform APIs for networking, database development, and more. It provides primary access to them through a special API." }, { "code": null, "e": 2282, "s": 2136, "text": "Various UI components: Qt provides multiple widgets, such as buttons or menus, all designed with a basic interface for all compatible platforms." }, { "code": null, "e": 2437, "s": 2282, "text": "Various learning resources: As PyQt is one of the most commonly used UI systems for Python, you can conveniently access a broad variety of documentation." }, { "code": null, "e": 2496, "s": 2437, "text": "Lack of Python-specific documentation for classes in PyQt5" }, { "code": null, "e": 2599, "s": 2496, "text": "It takes a lot of time to grasp all the specifics of PyQt, meaning it’s a pretty steep learning curve." }, { "code": null, "e": 2677, "s": 2599, "text": "If the application is not open-source, you must pay for a commercial license." }, { "code": null, "e": 3010, "s": 2677, "text": "Tkinter is an open-source Python Graphic User Interface (GUI) library well known for its simplicity. It comes pre-installed in Python, so you don’t even need to think about installing it. These characteristics make it a strong position for beginners and intermediates to begin with. Tkinter cannot be used for larger-scale projects." }, { "code": null, "e": 3016, "s": 3010, "text": "Code:" }, { "code": null, "e": 3024, "s": 3016, "text": "Python3" }, { "code": "# importing the module tkinterimport tkinter as tk # create main window (parent window)root = tk.Tk() # Label() it display box# where you can put any text. txt = tk.Label(root, text=\"Welcome to GeekForGeeks\") # pack() It organizes the widgets# in blocks before placing in the parent widget.txt.pack() # running the main looproot.mainloop()", "e": 3382, "s": 3024, "text": null }, { "code": null, "e": 3390, "s": 3382, "text": "Output:" }, { "code": null, "e": 3434, "s": 3390, "text": "A simple app to display text using tkinter." }, { "code": null, "e": 3510, "s": 3434, "text": "Tkinter is easy and fast to implement as compared to any other GUI toolkit." }, { "code": null, "e": 3547, "s": 3510, "text": "Tkinter is more flexible and stable." }, { "code": null, "e": 3613, "s": 3547, "text": "Tkinter is included in Python, so nothing extra need to download." }, { "code": null, "e": 3647, "s": 3613, "text": "Tkinter provides a simple syntax." }, { "code": null, "e": 3696, "s": 3647, "text": "Tkinter is really easy to understand and master." }, { "code": null, "e": 3805, "s": 3696, "text": "Tkinter provides three geometry managers: place, pack, and grid. That is much more powerful and easy to use." }, { "code": null, "e": 3848, "s": 3805, "text": "Tkinter does not include advanced widgets." }, { "code": null, "e": 3899, "s": 3848, "text": "It has no similar tool as Qt Designer for Tkinter." }, { "code": null, "e": 3930, "s": 3899, "text": "It doesn’t have a reliable UI." }, { "code": null, "e": 3972, "s": 3930, "text": "Sometime, it is hard to debug in Tkinter." }, { "code": null, "e": 3999, "s": 3972, "text": "It is not purely Pythonic." }, { "code": null, "e": 4004, "s": 3999, "text": "PyQt" }, { "code": null, "e": 4012, "s": 4004, "text": "Tkinter" }, { "code": null, "e": 4023, "s": 4012, "text": "Python-gui" }, { "code": null, "e": 4035, "s": 4023, "text": "Python-PyQt" }, { "code": null, "e": 4050, "s": 4035, "text": "Python-tkinter" }, { "code": null, "e": 4069, "s": 4050, "text": "Difference Between" }, { "code": null, "e": 4076, "s": 4069, "text": "Python" } ]
Lodash _.flatten() Method
29 Jul, 2020 Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers etc.The Lodash.flatten() method is used to flatten the array to one level deep. Syntax: flatten( array ) Parameter: This method accepts single parameter array that holds simple array or array of arrays. Return Value: The return type of this function is array. Note: Please install lodash module by using command npm install lodash before using the code given below. Example 1: When 2D array of Integers is given. Javascript // Requiring the lodash libraryconst _ = require("lodash"); // Original arraylet array1 = [[1, 2], [4, 5], [7, 8]] // Using _.flatten() methodlet newArray = _.flatten(array1); // Printing original Arrayconsole.log("original Array1: ", array1) // Printing the newArrayconsole.log("new Array: ", newArray) Output: Example 2: When array of arrays of object is given. Javascript // Requiring the lodash libraryconst _ = require("lodash"); // Original arraylet array1 = [[{ "a": 1 }], [{ "b": 2 }, { "c": 3 }]] // using _.flatten() methodlet newArray = _.flatten(array1); // printing original Arrayconsole.log("original Array1: ", array1) // printing the newArrayconsole.log("new Array: ", newArray) Output: Example 3: When empty array of arrays is given. Javascript // Requiring the lodash libraryconst _ = require("lodash"); // Original arraylet array1 = [[], [[[]]], [[]], []] // Using _.flatten() methodlet newArray = lodash.flatten(array1); // Printing original Arrayconsole.log("original Array1: ", array1) // Printing the newArrayconsole.log("new Array: ", newArray) Output: JavaScript-Lodash JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Roadmap to Learn JavaScript For Beginners Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Roadmap to Learn JavaScript For Beginners Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Jul, 2020" }, { "code": null, "e": 242, "s": 28, "text": "Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers etc.The Lodash.flatten() method is used to flatten the array to one level deep." }, { "code": null, "e": 250, "s": 242, "text": "Syntax:" }, { "code": null, "e": 267, "s": 250, "text": "flatten( array )" }, { "code": null, "e": 365, "s": 267, "text": "Parameter: This method accepts single parameter array that holds simple array or array of arrays." }, { "code": null, "e": 422, "s": 365, "text": "Return Value: The return type of this function is array." }, { "code": null, "e": 528, "s": 422, "text": "Note: Please install lodash module by using command npm install lodash before using the code given below." }, { "code": null, "e": 575, "s": 528, "text": "Example 1: When 2D array of Integers is given." }, { "code": null, "e": 586, "s": 575, "text": "Javascript" }, { "code": "// Requiring the lodash libraryconst _ = require(\"lodash\"); // Original arraylet array1 = [[1, 2], [4, 5], [7, 8]] // Using _.flatten() methodlet newArray = _.flatten(array1); // Printing original Arrayconsole.log(\"original Array1: \", array1) // Printing the newArrayconsole.log(\"new Array: \", newArray)", "e": 894, "s": 586, "text": null }, { "code": null, "e": 902, "s": 894, "text": "Output:" }, { "code": null, "e": 954, "s": 902, "text": "Example 2: When array of arrays of object is given." }, { "code": null, "e": 965, "s": 954, "text": "Javascript" }, { "code": "// Requiring the lodash libraryconst _ = require(\"lodash\"); // Original arraylet array1 = [[{ \"a\": 1 }], [{ \"b\": 2 }, { \"c\": 3 }]] // using _.flatten() methodlet newArray = _.flatten(array1); // printing original Arrayconsole.log(\"original Array1: \", array1) // printing the newArrayconsole.log(\"new Array: \", newArray)", "e": 1293, "s": 965, "text": null }, { "code": null, "e": 1302, "s": 1293, "text": "Output: " }, { "code": null, "e": 1350, "s": 1302, "text": "Example 3: When empty array of arrays is given." }, { "code": null, "e": 1361, "s": 1350, "text": "Javascript" }, { "code": "// Requiring the lodash libraryconst _ = require(\"lodash\"); // Original arraylet array1 = [[], [[[]]], [[]], []] // Using _.flatten() methodlet newArray = lodash.flatten(array1); // Printing original Arrayconsole.log(\"original Array1: \", array1) // Printing the newArrayconsole.log(\"new Array: \", newArray)", "e": 1672, "s": 1361, "text": null }, { "code": null, "e": 1680, "s": 1672, "text": "Output:" }, { "code": null, "e": 1698, "s": 1680, "text": "JavaScript-Lodash" }, { "code": null, "e": 1709, "s": 1698, "text": "JavaScript" }, { "code": null, "e": 1726, "s": 1709, "text": "Web Technologies" }, { "code": null, "e": 1824, "s": 1726, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1866, "s": 1824, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 1927, "s": 1866, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1967, "s": 1927, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2039, "s": 1967, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2091, "s": 2039, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 2124, "s": 2091, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2186, "s": 2124, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2228, "s": 2186, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 2289, "s": 2228, "text": "Difference between var, let and const keywords in JavaScript" } ]
PyQt - Using Qt Designer
The PyQt installer comes with a GUI builder tool called Qt Designer. Using its simple drag and drop interface, a GUI interface can be quickly built without having to write the code. It is however, not an IDE such as Visual Studio. Hence, Qt Designer does not have the facility to debug and build the application. Creation of a GUI interface using Qt Designer starts with choosing a top level window for the application. You can then drag and drop required widgets from the widget box on the left pane. You can also assign value to properties of widget laid on the form. The designed form is saved as demo.ui. This ui file contains XML representation of widgets and their properties in the design. This design is translated into Python equivalent by using pyuic4 command line utility. This utility is a wrapper for uic module. The usage of pyuic4 is as follows − pyuic4 –x demo.ui –o demo.py In the above command, -x switch adds a small amount of additional code to the generated XML so that it becomes a self-executable standalone application. if __name__ == "__main__": import sys app = QtGui.QApplication(sys.argv) Dialog = QtGui.QDialog() ui = Ui_Dialog() ui.setupUi(Dialog) Dialog.show() sys.exit(app.exec_()) The resultant python script is executed to show the following dialog box − The user can input data in input fields but clicking on Add button will not generate any action as it is not associated with any function. Reacting to user-generated response is called as event handling. 146 Lectures 22.5 hours ALAA EID Print Add Notes Bookmark this page
[ { "code": null, "e": 2239, "s": 1926, "text": "The PyQt installer comes with a GUI builder tool called Qt Designer. Using its simple drag and drop interface, a GUI interface can be quickly built without having to write the code. It is however, not an IDE such as Visual Studio. Hence, Qt Designer does not have the facility to debug and build the application." }, { "code": null, "e": 2346, "s": 2239, "text": "Creation of a GUI interface using Qt Designer starts with choosing a top level window for the application." }, { "code": null, "e": 2496, "s": 2346, "text": "You can then drag and drop required widgets from the widget box on the left pane. You can also assign value to properties of widget laid on the form." }, { "code": null, "e": 2788, "s": 2496, "text": "The designed form is saved as demo.ui. This ui file contains XML representation of widgets and their properties in the design. This design is translated into Python equivalent by using pyuic4 command line utility. This utility is a wrapper for uic module. The usage of pyuic4 is as follows −" }, { "code": null, "e": 2818, "s": 2788, "text": "pyuic4 –x demo.ui –o demo.py\n" }, { "code": null, "e": 2971, "s": 2818, "text": "In the above command, -x switch adds a small amount of additional code to the generated XML so that it becomes a self-executable standalone application." }, { "code": null, "e": 3162, "s": 2971, "text": "if __name__ == \"__main__\":\n import sys\n app = QtGui.QApplication(sys.argv)\n Dialog = QtGui.QDialog()\n ui = Ui_Dialog()\n ui.setupUi(Dialog)\n Dialog.show()\n sys.exit(app.exec_())" }, { "code": null, "e": 3237, "s": 3162, "text": "The resultant python script is executed to show the following dialog box −" }, { "code": null, "e": 3441, "s": 3237, "text": "The user can input data in input fields but clicking on Add button will not generate any action as it is not associated with any function. Reacting to user-generated response is called as event handling." }, { "code": null, "e": 3478, "s": 3441, "text": "\n 146 Lectures \n 22.5 hours \n" }, { "code": null, "e": 3488, "s": 3478, "text": " ALAA EID" }, { "code": null, "e": 3495, "s": 3488, "text": " Print" }, { "code": null, "e": 3506, "s": 3495, "text": " Add Notes" } ]
Execute a String of Code in Python
There are times when you need the entire block of code as a string and want this code to execute as part of a bigger python program. IN this article we will see how we can pass code as a string to a variable and then use that variable in a wrapper program which will then execute this program as a python code. The exec() function is used to execute the code. The code has to be embedded within three “. code = """ numbers = [11,33,55,39,55,75,37,21,23,41,13] for num in numbers: if num%2 == 0: print ('the list contains an even number') break else: print ('the list doesnot contain even number') """ exec(code) Running the above code gives us the following result − the list does not contain even number.
[ { "code": null, "e": 1373, "s": 1062, "text": "There are times when you need the entire block of code as a string and want this code to execute as part of a bigger python program. IN this article we will see how we can pass code as a string to a variable and then use that variable in a wrapper program which will then execute this program as a python code." }, { "code": null, "e": 1466, "s": 1373, "text": "The exec() function is used to execute the code. The code has to be embedded within three “." }, { "code": null, "e": 1692, "s": 1466, "text": "code = \"\"\"\nnumbers = [11,33,55,39,55,75,37,21,23,41,13]\nfor num in numbers:\n if num%2 == 0:\n print ('the list contains an even number')\n break\nelse:\n print ('the list doesnot contain even number')\n\"\"\"\nexec(code)" }, { "code": null, "e": 1747, "s": 1692, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1786, "s": 1747, "text": "the list does not contain even number." } ]
Highcharts - Basic Line Chart
We have already seen the configuration used to draw this chart in Highcharts Configuration Syntax chapter. Let us now consider the following example to further understand a basic line chart. highcharts_line_basic.htm <html> <head> <title>Highcharts Tutorial</title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script src = "https://code.highcharts.com/highcharts.js"></script> </head> <body> <div id = "container" style = "width: 550px; height: 400px; margin: 0 auto"></div> <script language = "JavaScript"> $(document).ready(function() { var title = { text: 'Average Temperatures of Cities' }; var subtitle = { text: 'Source: worldClimate.com' }; var xAxis = { categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] }; var yAxis = { title: { text: 'Temperature (\xB0C)' }, plotLines: [{ value: 0, width: 1, color: '#808080' }] }; var tooltip = { valueSuffix: '\xB0C' } var legend = { layout: 'vertical', align: 'right', verticalAlign: 'middle', borderWidth: 0 }; var series = [{ name: 'Tokyo', data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6] }, { name: 'New York', data: [-0.2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8, 24.1, 20.1, 14.1, 8.6, 2.5] }, { name: 'London', data: [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8] } ]; var json = {}; json.title = title; json.subtitle = subtitle; json.xAxis = xAxis; json.yAxis = yAxis; json.tooltip = tooltip; json.legend = legend; json.series = series; $('#container').highcharts(json); }); </script> </body> </html> Verify the result. Print Add Notes Bookmark this page
[ { "code": null, "e": 2208, "s": 2017, "text": "We have already seen the configuration used to draw this chart in Highcharts Configuration Syntax chapter. Let us now consider the following example to further understand a basic line chart." }, { "code": null, "e": 2234, "s": 2208, "text": "highcharts_line_basic.htm" }, { "code": null, "e": 4505, "s": 2234, "text": "<html>\n <head>\n <title>Highcharts Tutorial</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n <script src = \"https://code.highcharts.com/highcharts.js\"></script> \n </head>\n \n <body>\n <div id = \"container\" style = \"width: 550px; height: 400px; margin: 0 auto\"></div>\n <script language = \"JavaScript\">\n $(document).ready(function() {\n var title = {\n text: 'Average Temperatures of Cities' \n };\n var subtitle = {\n text: 'Source: worldClimate.com'\n };\n var xAxis = {\n categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',\n 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']\n };\n var yAxis = {\n title: {\n text: 'Temperature (\\xB0C)'\n },\n plotLines: [{\n value: 0,\n width: 1,\n color: '#808080'\n }]\n }; \n var tooltip = {\n valueSuffix: '\\xB0C'\n }\n var legend = {\n layout: 'vertical',\n align: 'right',\n verticalAlign: 'middle',\n borderWidth: 0\n };\n var series = [{\n name: 'Tokyo',\n data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2,\n 26.5, 23.3, 18.3, 13.9, 9.6]\n }, \n {\n name: 'New York',\n data: [-0.2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8,\n 24.1, 20.1, 14.1, 8.6, 2.5]\n }, \n {\n name: 'London',\n data: [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, \n 16.6, 14.2, 10.3, 6.6, 4.8]\n }\n ];\n\n var json = {};\n json.title = title;\n json.subtitle = subtitle;\n json.xAxis = xAxis;\n json.yAxis = yAxis;\n json.tooltip = tooltip;\n json.legend = legend;\n json.series = series;\n \n $('#container').highcharts(json);\n });\n </script>\n </body>\n \n</html>" }, { "code": null, "e": 4524, "s": 4505, "text": "Verify the result." }, { "code": null, "e": 4531, "s": 4524, "text": " Print" }, { "code": null, "e": 4542, "s": 4531, "text": " Add Notes" } ]
SciPy - Ndimage
The SciPy ndimage submodule is dedicated to image processing. Here, ndimage means an n-dimensional image. Some of the most common tasks in image processing are as follows &miuns; Input/Output, displaying images Basic manipulations − Cropping, flipping, rotating, etc. Image filtering − De-noising, sharpening, etc. Image segmentation − Labeling pixels corresponding to different objects Classification Feature extraction Registration Let us discuss how some of these can be achieved using SciPy. The misc package in SciPy comes with some images. We use those images to learn the image manipulations. Let us consider the following example. from scipy import misc f = misc.face() misc.imsave('face.png', f) # uses the Image module (PIL) import matplotlib.pyplot as plt plt.imshow(f) plt.show() The above program will generate the following output. Any images in its raw format is the combination of colors represented by the numbers in the matrix format. A machine understands and manipulates the images based on those numbers only. RGB is a popular way of representation. Let us see the statistical information of the above image. from scipy import misc face = misc.face(gray = False) print face.mean(), face.max(), face.min() The above program will generate the following output. 110.16274388631184, 255, 0 Now, we know that the image is made out of numbers, so any change in the value of the number alters the original image. Let us perform some geometric transformations on the image. The basic geometric operation is cropping from scipy import misc face = misc.face(gray = True) lx, ly = face.shape # Cropping crop_face = face[lx / 4: - lx / 4, ly / 4: - ly / 4] import matplotlib.pyplot as plt plt.imshow(crop_face) plt.show() The above program will generate the following output. We can also perform some basic operations such as turning the image upside down as described below. # up <-> down flip from scipy import misc face = misc.face() flip_ud_face = np.flipud(face) import matplotlib.pyplot as plt plt.imshow(flip_ud_face) plt.show() The above program will generate the following output. Besides this, we have the rotate() function, which rotates the image with a specified angle. # rotation from scipy import misc,ndimage face = misc.face() rotate_face = ndimage.rotate(face, 45) import matplotlib.pyplot as plt plt.imshow(rotate_face) plt.show() The above program will generate the following output. Let us discuss how filters help in image processing. Filtering is a technique for modifying or enhancing an image. For example, you can filter an image to emphasize certain features or remove other features. Image processing operations implemented with filtering include Smoothing, Sharpening, and Edge Enhancement. Filtering is a neighborhood operation, in which the value of any given pixel in the output image is determined by applying some algorithm to the values of the pixels in the neighborhood of the corresponding input pixel. Let us now perform a few operations using SciPy ndimage. Blurring is widely used to reduce the noise in the image. We can perform a filter operation and see the change in the image. Let us consider the following example. from scipy import misc face = misc.face() blurred_face = ndimage.gaussian_filter(face, sigma=3) import matplotlib.pyplot as plt plt.imshow(blurred_face) plt.show() The above program will generate the following output. The sigma value indicates the level of blur on a scale of five. We can see the change on the image quality by tuning the sigma value. For more details of blurring, click on → DIP (Digital Image Processing) Tutorial. Let us discuss how edge detection helps in image processing. Edge detection is an image processing technique for finding the boundaries of objects within images. It works by detecting discontinuities in brightness. Edge detection is used for image segmentation and data extraction in areas such as Image Processing, Computer Vision and Machine Vision. The most commonly used edge detection algorithms include Sobel Canny Prewitt Roberts Fuzzy Logic methods Let us consider the following example. import scipy.ndimage as nd import numpy as np im = np.zeros((256, 256)) im[64:-64, 64:-64] = 1 im[90:-90,90:-90] = 2 im = ndimage.gaussian_filter(im, 8) import matplotlib.pyplot as plt plt.imshow(im) plt.show() The above program will generate the following output. The image looks like a square block of colors. Now, we will detect the edges of those colored blocks. Here, ndimage provides a function called Sobel to carry out this operation. Whereas, NumPy provides the Hypot function to combine the two resultant matrices to one. Let us consider the following example. import scipy.ndimage as nd import matplotlib.pyplot as plt im = np.zeros((256, 256)) im[64:-64, 64:-64] = 1 im[90:-90,90:-90] = 2 im = ndimage.gaussian_filter(im, 8) sx = ndimage.sobel(im, axis = 0, mode = 'constant') sy = ndimage.sobel(im, axis = 1, mode = 'constant') sob = np.hypot(sx, sy) plt.imshow(sob) plt.show() The above program will generate the following output. Print Add Notes Bookmark this page
[ { "code": null, "e": 1993, "s": 1887, "text": "The SciPy ndimage submodule is dedicated to image processing. Here, ndimage means an n-dimensional image." }, { "code": null, "e": 2066, "s": 1993, "text": "Some of the most common tasks in image processing are as follows &miuns;" }, { "code": null, "e": 2098, "s": 2066, "text": "Input/Output, displaying images" }, { "code": null, "e": 2155, "s": 2098, "text": "Basic manipulations − Cropping, flipping, rotating, etc." }, { "code": null, "e": 2202, "s": 2155, "text": "Image filtering − De-noising, sharpening, etc." }, { "code": null, "e": 2274, "s": 2202, "text": "Image segmentation − Labeling pixels corresponding to different objects" }, { "code": null, "e": 2289, "s": 2274, "text": "Classification" }, { "code": null, "e": 2308, "s": 2289, "text": "Feature extraction" }, { "code": null, "e": 2321, "s": 2308, "text": "Registration" }, { "code": null, "e": 2383, "s": 2321, "text": "Let us discuss how some of these can be achieved using SciPy." }, { "code": null, "e": 2526, "s": 2383, "text": "The misc package in SciPy comes with some images. We use those images to learn the image manipulations. Let us consider the following example." }, { "code": null, "e": 2680, "s": 2526, "text": "from scipy import misc\nf = misc.face()\nmisc.imsave('face.png', f) # uses the Image module (PIL)\n\nimport matplotlib.pyplot as plt\nplt.imshow(f)\nplt.show()" }, { "code": null, "e": 2734, "s": 2680, "text": "The above program will generate the following output." }, { "code": null, "e": 2959, "s": 2734, "text": "Any images in its raw format is the combination of colors represented by the numbers in the matrix format. A machine understands and manipulates the images based on those numbers only. RGB is a popular way of representation." }, { "code": null, "e": 3018, "s": 2959, "text": "Let us see the statistical information of the above image." }, { "code": null, "e": 3114, "s": 3018, "text": "from scipy import misc\nface = misc.face(gray = False)\nprint face.mean(), face.max(), face.min()" }, { "code": null, "e": 3168, "s": 3114, "text": "The above program will generate the following output." }, { "code": null, "e": 3196, "s": 3168, "text": "110.16274388631184, 255, 0\n" }, { "code": null, "e": 3418, "s": 3196, "text": "Now, we know that the image is made out of numbers, so any change in the value of the number alters the original image. Let us perform some geometric transformations on the image. The basic geometric operation is cropping" }, { "code": null, "e": 3620, "s": 3418, "text": "from scipy import misc\nface = misc.face(gray = True)\nlx, ly = face.shape\n# Cropping\ncrop_face = face[lx / 4: - lx / 4, ly / 4: - ly / 4]\nimport matplotlib.pyplot as plt\nplt.imshow(crop_face)\nplt.show()" }, { "code": null, "e": 3674, "s": 3620, "text": "The above program will generate the following output." }, { "code": null, "e": 3774, "s": 3674, "text": "We can also perform some basic operations such as turning the image upside down as described below." }, { "code": null, "e": 3936, "s": 3774, "text": "# up <-> down flip\nfrom scipy import misc\nface = misc.face()\nflip_ud_face = np.flipud(face)\n\nimport matplotlib.pyplot as plt\nplt.imshow(flip_ud_face)\nplt.show()\n" }, { "code": null, "e": 3990, "s": 3936, "text": "The above program will generate the following output." }, { "code": null, "e": 4083, "s": 3990, "text": "Besides this, we have the rotate() function, which rotates the image with a specified angle." }, { "code": null, "e": 4251, "s": 4083, "text": "# rotation\nfrom scipy import misc,ndimage\nface = misc.face()\nrotate_face = ndimage.rotate(face, 45)\n\nimport matplotlib.pyplot as plt\nplt.imshow(rotate_face)\nplt.show()" }, { "code": null, "e": 4305, "s": 4251, "text": "The above program will generate the following output." }, { "code": null, "e": 4358, "s": 4305, "text": "Let us discuss how filters help in image processing." }, { "code": null, "e": 4621, "s": 4358, "text": "Filtering is a technique for modifying or enhancing an image. For example, you can filter an image to emphasize certain features or remove other features. Image processing operations implemented with filtering include Smoothing, Sharpening, and Edge Enhancement." }, { "code": null, "e": 4898, "s": 4621, "text": "Filtering is a neighborhood operation, in which the value of any given pixel in the output image is determined by applying some algorithm to the values of the pixels in the neighborhood of the corresponding input pixel. Let us now perform a few operations using SciPy ndimage." }, { "code": null, "e": 5062, "s": 4898, "text": "Blurring is widely used to reduce the noise in the image. We can perform a filter operation and see the change in the image. Let us consider the following example." }, { "code": null, "e": 5226, "s": 5062, "text": "from scipy import misc\nface = misc.face()\nblurred_face = ndimage.gaussian_filter(face, sigma=3)\nimport matplotlib.pyplot as plt\nplt.imshow(blurred_face)\nplt.show()" }, { "code": null, "e": 5280, "s": 5226, "text": "The above program will generate the following output." }, { "code": null, "e": 5496, "s": 5280, "text": "The sigma value indicates the level of blur on a scale of five. We can see the change on the image quality by tuning the sigma value. For more details of blurring, click on → DIP (Digital Image Processing) Tutorial." }, { "code": null, "e": 5557, "s": 5496, "text": "Let us discuss how edge detection helps in image processing." }, { "code": null, "e": 5848, "s": 5557, "text": "Edge detection is an image processing technique for finding the boundaries of objects within images. It works by detecting discontinuities in brightness. Edge detection is used for image segmentation and data extraction in areas such as Image Processing, Computer Vision and Machine Vision." }, { "code": null, "e": 5905, "s": 5848, "text": "The most commonly used edge detection algorithms include" }, { "code": null, "e": 5911, "s": 5905, "text": "Sobel" }, { "code": null, "e": 5917, "s": 5911, "text": "Canny" }, { "code": null, "e": 5925, "s": 5917, "text": "Prewitt" }, { "code": null, "e": 5933, "s": 5925, "text": "Roberts" }, { "code": null, "e": 5953, "s": 5933, "text": "Fuzzy Logic methods" }, { "code": null, "e": 5992, "s": 5953, "text": "Let us consider the following example." }, { "code": null, "e": 6205, "s": 5992, "text": "import scipy.ndimage as nd\nimport numpy as np\n\nim = np.zeros((256, 256))\nim[64:-64, 64:-64] = 1\nim[90:-90,90:-90] = 2\nim = ndimage.gaussian_filter(im, 8)\n\nimport matplotlib.pyplot as plt\nplt.imshow(im)\nplt.show()" }, { "code": null, "e": 6259, "s": 6205, "text": "The above program will generate the following output." }, { "code": null, "e": 6526, "s": 6259, "text": "The image looks like a square block of colors. Now, we will detect the edges of those colored blocks. Here, ndimage provides a function called Sobel to carry out this operation. Whereas, NumPy provides the Hypot function to combine the two resultant matrices to one." }, { "code": null, "e": 6565, "s": 6526, "text": "Let us consider the following example." }, { "code": null, "e": 6888, "s": 6565, "text": "import scipy.ndimage as nd\nimport matplotlib.pyplot as plt\n\nim = np.zeros((256, 256))\nim[64:-64, 64:-64] = 1\nim[90:-90,90:-90] = 2\nim = ndimage.gaussian_filter(im, 8)\n\nsx = ndimage.sobel(im, axis = 0, mode = 'constant')\nsy = ndimage.sobel(im, axis = 1, mode = 'constant')\nsob = np.hypot(sx, sy)\n\nplt.imshow(sob)\nplt.show()" }, { "code": null, "e": 6942, "s": 6888, "text": "The above program will generate the following output." }, { "code": null, "e": 6949, "s": 6942, "text": " Print" }, { "code": null, "e": 6960, "s": 6949, "text": " Add Notes" } ]
A Simple Breakout Trading Strategy in Python | by Sofien Kaabar, CFA | Towards Data Science
Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details. I have just published a new book after the success of New Technical Indicators in Python. It features a more complete description and addition of complex trading strategies with a Github page dedicated to the continuously updated code. If you feel that this interests you, feel free to visit the below link, or if you prefer to buy the PDF version, you could contact me on Linkedin. www.amazon.com Trading is divided into many different strategies that rely on trend-following, mean reversion, volatility, or other factors. Successful strategies rely on the current market state, for example, when markets are strongly trending, mean reversion strategies tend to fail and therefore we always have to adapt our market approach accordingly. Below is a breakout strategy that uses an indicator called the Donchian Channel. The basic idea is to make ranges as objective as we can (i.e. measurable) and then trade on the breakout (i.e. the start of a trend). The goal of the article is therefore to see whether this indicator can add value into our overall trading system or not. Does it provide good signals? Are the triggers to be taken seriously? Created by Richard Donchian, this simple and great indicator is used to identify breakouts and reversals. Just like the Bollinger bands, it is used in an almost similar fashion. Our goal is to determine objectively a range exit by the surpass or break of any of the barriers. The way it is formed is by first calculating the maximum of the last n-period highs and the minimum of the last n-period lows, then calculating the average of them both. This gives us three measures: The Donchian upper band, the lower band, and the middle band. Here’s the mathematical formula followed later by the Python code used on an OHLC data structure. def donchian(Data, low, high, where_up, where_down, median, period): for i in range(len(Data)): try: Data[i, where_up] = max(Data[i - period:i + 1, 1]) except ValueError: pass for i in range(len(Data)): try: Data[i, where_down] = min(Data[i - period:i + 1, 2]) except ValueError: pass for i in range(len(Data)): try: Data[i, median] = (Data[i, where_up] + Data[i, where_down]) / 2 except ValueError: passdonchian(Data, 2, 1, 4, 5, 6, 20)'''plt.plot(Data[-500:, 3], color = 'black')plt.plot(Data[-500:, 4])plt.plot(Data[-500:, 5])plt.plot(Data[-500:, 6])plt.grid()''' Visually, the Donchian channel seems to envelop prices and that is understandable because the it takes into account the current extreme and therefore the market never lies outside of the channel. The basic strategy of the Donchian channel is the breakout strategy. It is intuitive and clear, below are the rules: Buy whenever the market surpasses the last upper channel. Sell (go short) whenever the market breaks the last lower channel. def donchian_signals(Data, onwhat, donch_up, donch_down): for i in range(len(Data)): if Data[i, where_close] > Data[i - 1, donch_up]: Data[i, 6] = 1 elif Data[i, where_close] < Data[i - 1, donch_down]: Data[i, 7] = -1 return Data# Note: The onwhat variable is the closing price We choose the last Donchian level because we want to know when we break our last high or low. Remember, the formula takes into account the current high and low and therefore the current price will never break them. The conditions chosen for the back-test were more of a longer-term breakout in that we are using daily charts with a Donchian period of 60 days. This means that if the market surpasses the upper donchian channel of the last 60 days, then we buy into the trend. I have incorporated a simple stop-loss order of 100 pips over the three tested currency pairs below. I have chosen three major pairs as a proxy for this strategy, they are EURUSD, USDCHF, and GBPUSD. The next charts show the signal charts on the three back-tests. The equity curve following a 0.5 pip per trade on a $10,000 lot size for comparison reasons. The starting balance is $1,000 and hence, a 1:100 leverage. If you are also interested by more technical indicators and using Python to create strategies, then my best-selling book on Technical Indicators may interest you: www.amazon.com Visibly, it needs some improvements and the Donchian channels should have another indicator alongside them to confirm the signals or to add a volatility factor and stabilize the results. There is another strategy that can be employed here. It relies on the middle band. We can try to develop a strategy based on them using the same back-testing conditions as the above. We know from the above introduction that the middle band is simply the average of the upper and lower bands and as such it can be compared to the moving average of the Bollinger bands. If you are interested in knowing more about the Bollinger bands, you can check this article where I provide more back-tests: medium.com The rules of the middle band strategy are therefore: Buy whenever the market surpasses the middle band. Sell (go short) whenever the market breaks the middle band. def donchian_signals_middle(Data, onwhat, donch_middle, buy, sell): for i in range(len(Data)): if Data[i, onwhat] > Data[i, donch_middle] and Data[i - 1, onwhat] < \ Data[i, donch_middle]: Data[i, buy] = 1 elif Data[i, onwhat] < Data[i, donch_middle] and Data[i - 1, onwhat] > \ Data[i, donch_middle]: Data[i, sell] = -1# Note: The buy and sell variables are the triggers (equivalent to column 6 and 7 in the first strategy code) The signal charts of the second strategy are the below: The equity curve is much less impressive. Although the first strategy showed some potential, the second one failed to impress. It is clear that there is much to be done with the Donchian channel but it is good to know that we can attempt to quantify ranges and trade on their breakouts.
[ { "code": null, "e": 471, "s": 171, "text": "Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details." }, { "code": null, "e": 854, "s": 471, "text": "I have just published a new book after the success of New Technical Indicators in Python. It features a more complete description and addition of complex trading strategies with a Github page dedicated to the continuously updated code. If you feel that this interests you, feel free to visit the below link, or if you prefer to buy the PDF version, you could contact me on Linkedin." }, { "code": null, "e": 869, "s": 854, "text": "www.amazon.com" }, { "code": null, "e": 1616, "s": 869, "text": "Trading is divided into many different strategies that rely on trend-following, mean reversion, volatility, or other factors. Successful strategies rely on the current market state, for example, when markets are strongly trending, mean reversion strategies tend to fail and therefore we always have to adapt our market approach accordingly. Below is a breakout strategy that uses an indicator called the Donchian Channel. The basic idea is to make ranges as objective as we can (i.e. measurable) and then trade on the breakout (i.e. the start of a trend). The goal of the article is therefore to see whether this indicator can add value into our overall trading system or not. Does it provide good signals? Are the triggers to be taken seriously?" }, { "code": null, "e": 2252, "s": 1616, "text": "Created by Richard Donchian, this simple and great indicator is used to identify breakouts and reversals. Just like the Bollinger bands, it is used in an almost similar fashion. Our goal is to determine objectively a range exit by the surpass or break of any of the barriers. The way it is formed is by first calculating the maximum of the last n-period highs and the minimum of the last n-period lows, then calculating the average of them both. This gives us three measures: The Donchian upper band, the lower band, and the middle band. Here’s the mathematical formula followed later by the Python code used on an OHLC data structure." }, { "code": null, "e": 2951, "s": 2252, "text": "def donchian(Data, low, high, where_up, where_down, median, period): for i in range(len(Data)): try: Data[i, where_up] = max(Data[i - period:i + 1, 1]) except ValueError: pass for i in range(len(Data)): try: Data[i, where_down] = min(Data[i - period:i + 1, 2]) except ValueError: pass for i in range(len(Data)): try: Data[i, median] = (Data[i, where_up] + Data[i, where_down]) / 2 except ValueError: passdonchian(Data, 2, 1, 4, 5, 6, 20)'''plt.plot(Data[-500:, 3], color = 'black')plt.plot(Data[-500:, 4])plt.plot(Data[-500:, 5])plt.plot(Data[-500:, 6])plt.grid()'''" }, { "code": null, "e": 3147, "s": 2951, "text": "Visually, the Donchian channel seems to envelop prices and that is understandable because the it takes into account the current extreme and therefore the market never lies outside of the channel." }, { "code": null, "e": 3264, "s": 3147, "text": "The basic strategy of the Donchian channel is the breakout strategy. It is intuitive and clear, below are the rules:" }, { "code": null, "e": 3322, "s": 3264, "text": "Buy whenever the market surpasses the last upper channel." }, { "code": null, "e": 3389, "s": 3322, "text": "Sell (go short) whenever the market breaks the last lower channel." }, { "code": null, "e": 3753, "s": 3389, "text": "def donchian_signals(Data, onwhat, donch_up, donch_down): for i in range(len(Data)): if Data[i, where_close] > Data[i - 1, donch_up]: Data[i, 6] = 1 elif Data[i, where_close] < Data[i - 1, donch_down]: Data[i, 7] = -1 return Data# Note: The onwhat variable is the closing price" }, { "code": null, "e": 3968, "s": 3753, "text": "We choose the last Donchian level because we want to know when we break our last high or low. Remember, the formula takes into account the current high and low and therefore the current price will never break them." }, { "code": null, "e": 4493, "s": 3968, "text": "The conditions chosen for the back-test were more of a longer-term breakout in that we are using daily charts with a Donchian period of 60 days. This means that if the market surpasses the upper donchian channel of the last 60 days, then we buy into the trend. I have incorporated a simple stop-loss order of 100 pips over the three tested currency pairs below. I have chosen three major pairs as a proxy for this strategy, they are EURUSD, USDCHF, and GBPUSD. The next charts show the signal charts on the three back-tests." }, { "code": null, "e": 4646, "s": 4493, "text": "The equity curve following a 0.5 pip per trade on a $10,000 lot size for comparison reasons. The starting balance is $1,000 and hence, a 1:100 leverage." }, { "code": null, "e": 4809, "s": 4646, "text": "If you are also interested by more technical indicators and using Python to create strategies, then my best-selling book on Technical Indicators may interest you:" }, { "code": null, "e": 4824, "s": 4809, "text": "www.amazon.com" }, { "code": null, "e": 5011, "s": 4824, "text": "Visibly, it needs some improvements and the Donchian channels should have another indicator alongside them to confirm the signals or to add a volatility factor and stabilize the results." }, { "code": null, "e": 5504, "s": 5011, "text": "There is another strategy that can be employed here. It relies on the middle band. We can try to develop a strategy based on them using the same back-testing conditions as the above. We know from the above introduction that the middle band is simply the average of the upper and lower bands and as such it can be compared to the moving average of the Bollinger bands. If you are interested in knowing more about the Bollinger bands, you can check this article where I provide more back-tests:" }, { "code": null, "e": 5515, "s": 5504, "text": "medium.com" }, { "code": null, "e": 5568, "s": 5515, "text": "The rules of the middle band strategy are therefore:" }, { "code": null, "e": 5619, "s": 5568, "text": "Buy whenever the market surpasses the middle band." }, { "code": null, "e": 5679, "s": 5619, "text": "Sell (go short) whenever the market breaks the middle band." }, { "code": null, "e": 6204, "s": 5679, "text": "def donchian_signals_middle(Data, onwhat, donch_middle, buy, sell): for i in range(len(Data)): if Data[i, onwhat] > Data[i, donch_middle] and Data[i - 1, onwhat] < \\ Data[i, donch_middle]: Data[i, buy] = 1 elif Data[i, onwhat] < Data[i, donch_middle] and Data[i - 1, onwhat] > \\ Data[i, donch_middle]: Data[i, sell] = -1# Note: The buy and sell variables are the triggers (equivalent to column 6 and 7 in the first strategy code)" }, { "code": null, "e": 6260, "s": 6204, "text": "The signal charts of the second strategy are the below:" }, { "code": null, "e": 6302, "s": 6260, "text": "The equity curve is much less impressive." } ]
What are the differences between paint() method and repaint() method in Java?
paint(): This method holds instructions to paint this component. In Java Swing, we can change the paintComponent() method instead of paint() method as paint calls paintBorder(), paintComponent() and paintChildren() methods. We cannot call this method directly instead we can call repaint(). repaint(): This method cannot be overridden. It controls the update() -> paint() cycle. We can call this method to get a component to repaint itself. If we have done anything to change the look of the component but not the size then we can call this method. import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.*; public class PaintRepaintTest extends JPanel implements MouseListener { private Vector v; public PaintRepaintTest() { v = new Vector(); setBackground(Color.white); addMouseListener(this); } public void paint(Graphics g) { // paint() method super.paint(g); g.setColor(Color.black); Enumeration enumeration = v.elements(); while(enumeration.hasMoreElements()) { Point p = (Point)(enumeration.nextElement()); g.drawRect(p.x-20, p.y-20, 40, 40); } } public void mousePressed(MouseEvent me) { v.add(me.getPoint()); repaint(); // call repaint() method } public void mouseClicked(MouseEvent me) {} public void mouseEntered(MouseEvent me) {} public void mouseExited(MouseEvent me) {} public void mouseReleased(MouseEvent me) {} public static void main(String args[]) { JFrame frame = new JFrame(); frame.getContentPane().add(new PaintRepaintTest()); frame.setTitle("PaintRepaint Test"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); frame.setSize(375, 250); frame.setVisible(true); } } In the above program, if we click on the screen able to draw squares. In the mousePressed() method, we can call the repaint() method.
[ { "code": null, "e": 1353, "s": 1062, "text": "paint(): This method holds instructions to paint this component. In Java Swing, we can change the paintComponent() method instead of paint() method as paint calls paintBorder(),\npaintComponent() and paintChildren() methods. We cannot call this method directly instead we can call repaint()." }, { "code": null, "e": 1611, "s": 1353, "text": "repaint(): This method cannot be overridden. It controls the update() -> paint() cycle. We can call this method to get a component to repaint itself. If we have done anything to change the look of the component but not the size then we can call this method." }, { "code": null, "e": 2876, "s": 1611, "text": "import java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\nimport java.util.*;\npublic class PaintRepaintTest extends JPanel implements MouseListener {\n private Vector v;\n public PaintRepaintTest() {\n v = new Vector();\n setBackground(Color.white);\n addMouseListener(this);\n }\n public void paint(Graphics g) { // paint() method\n super.paint(g);\n g.setColor(Color.black);\n Enumeration enumeration = v.elements();\n while(enumeration.hasMoreElements()) {\n Point p = (Point)(enumeration.nextElement());\n g.drawRect(p.x-20, p.y-20, 40, 40);\n }\n }\n public void mousePressed(MouseEvent me) {\n v.add(me.getPoint());\n repaint(); // call repaint() method\n }\n public void mouseClicked(MouseEvent me) {}\n public void mouseEntered(MouseEvent me) {}\n public void mouseExited(MouseEvent me) {}\n public void mouseReleased(MouseEvent me) {}\n public static void main(String args[]) {\n JFrame frame = new JFrame();\n frame.getContentPane().add(new PaintRepaintTest());\n frame.setTitle(\"PaintRepaint Test\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.setLocationRelativeTo(null);\n frame.setSize(375, 250);\n frame.setVisible(true);\n }\n}" }, { "code": null, "e": 3010, "s": 2876, "text": "In the above program, if we click on the screen able to draw squares. In the mousePressed() method, we can call the repaint() method." } ]
HTML <th> colspan Attribute
The colspan attribute of the <th> element is used to set the number of columns a header cell should span. Following is the syntax − <th colspan="num"> Above, num is the count of columns a header cell should span. Let us now see an example to implement the colspan attribute of the <th> element − Live Demo <!DOCTYPE html> <html> <head> <style> table, th, td { border: 2px solid green; } </style> </head> <body> <h2>Product Expenses</h2> <table> <tr> <th colspan="2">Expenses</th> </tr> <tr> <td>Product Development</td> <td>500000</td> </tr> <tr> <td>Marketing</td> <td>500000</td> </tr> <tr> <td>Services</td> <td>100000</td> </tr> <tr> <td>Support</td> <td>100000</td> </tr> <tr> <td>Maintenance</td> <td>100000</td> </tr> <tr> <td colspan="2">Total Budget = INR 1300000</td> </tr> </table> </body> </html> In the above example, we have set the column count to span the header cell − <th colspan="2">Expenses</th> The count is 2, therefore two columns will span the header cell.
[ { "code": null, "e": 1168, "s": 1062, "text": "The colspan attribute of the <th> element is used to set the number of columns a header cell should span." }, { "code": null, "e": 1194, "s": 1168, "text": "Following is the syntax −" }, { "code": null, "e": 1213, "s": 1194, "text": "<th colspan=\"num\">" }, { "code": null, "e": 1275, "s": 1213, "text": "Above, num is the count of columns a header cell should span." }, { "code": null, "e": 1358, "s": 1275, "text": "Let us now see an example to implement the colspan attribute of the <th> element −" }, { "code": null, "e": 1369, "s": 1358, "text": " Live Demo" }, { "code": null, "e": 1989, "s": 1369, "text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\ntable, th, td {\n border: 2px solid green;\n}\n</style>\n</head>\n<body>\n<h2>Product Expenses</h2>\n<table>\n <tr>\n <th colspan=\"2\">Expenses</th>\n </tr>\n <tr>\n <td>Product Development</td>\n <td>500000</td>\n </tr>\n <tr>\n <td>Marketing</td>\n <td>500000</td>\n </tr>\n <tr>\n <td>Services</td>\n <td>100000</td>\n </tr>\n <tr>\n <td>Support</td>\n <td>100000</td>\n </tr>\n <tr>\n <td>Maintenance</td>\n <td>100000</td>\n </tr>\n <tr>\n <td colspan=\"2\">Total Budget = INR 1300000</td>\n </tr>\n</table>\n</body>\n</html>" }, { "code": null, "e": 2066, "s": 1989, "text": "In the above example, we have set the column count to span the header cell −" }, { "code": null, "e": 2096, "s": 2066, "text": "<th colspan=\"2\">Expenses</th>" }, { "code": null, "e": 2161, "s": 2096, "text": "The count is 2, therefore two columns will span the header cell." } ]
Compute the value of Cauchy Quantile Function in R Programming - qcauchy() Function - GeeksforGeeks
25 Jun, 2020 qcauchy() function in R Language is used to calculate the value of cauchy quantile function. It also creates a density plot of cauchy quantile function. Syntax: qcauchy(vec, scale) Parameters:vec: x-values for cauchy functionscale: Scale for plotting Example 1: # R Program to compute value of# cauchy quantile function # Creating vector for x-valuesx <- seq(0, 1, by = 0.2) # Apply qcauchy() Functiony <- qcauchy(x, scale = 4)y Output: [1] -Inf -5.505528 -1.299679 1.299679 5.505528 Inf Example 2: # R Program to compute value of# cauchy quantile function # Creating vector for x-valuesx <- seq(0, 1, by = 0.02) # Apply qcauchy() Functiony <- qcauchy(x, scale = 1) # Plotting the graphplot(y) Output: R-Statistics 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? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? R - if statement How to import an Excel File into R ? Time Series Analysis in R
[ { "code": null, "e": 24851, "s": 24823, "text": "\n25 Jun, 2020" }, { "code": null, "e": 25004, "s": 24851, "text": "qcauchy() function in R Language is used to calculate the value of cauchy quantile function. It also creates a density plot of cauchy quantile function." }, { "code": null, "e": 25032, "s": 25004, "text": "Syntax: qcauchy(vec, scale)" }, { "code": null, "e": 25102, "s": 25032, "text": "Parameters:vec: x-values for cauchy functionscale: Scale for plotting" }, { "code": null, "e": 25113, "s": 25102, "text": "Example 1:" }, { "code": "# R Program to compute value of# cauchy quantile function # Creating vector for x-valuesx <- seq(0, 1, by = 0.2) # Apply qcauchy() Functiony <- qcauchy(x, scale = 4)y", "e": 25282, "s": 25113, "text": null }, { "code": null, "e": 25290, "s": 25282, "text": "Output:" }, { "code": null, "e": 25355, "s": 25290, "text": "[1] -Inf -5.505528 -1.299679 1.299679 5.505528 Inf\n" }, { "code": null, "e": 25366, "s": 25355, "text": "Example 2:" }, { "code": "# R Program to compute value of# cauchy quantile function # Creating vector for x-valuesx <- seq(0, 1, by = 0.02) # Apply qcauchy() Functiony <- qcauchy(x, scale = 1) # Plotting the graphplot(y)", "e": 25564, "s": 25366, "text": null }, { "code": null, "e": 25572, "s": 25564, "text": "Output:" }, { "code": null, "e": 25585, "s": 25572, "text": "R-Statistics" }, { "code": null, "e": 25596, "s": 25585, "text": "R Language" }, { "code": null, "e": 25694, "s": 25596, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25703, "s": 25694, "text": "Comments" }, { "code": null, "e": 25716, "s": 25703, "text": "Old Comments" }, { "code": null, "e": 25768, "s": 25716, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 25806, "s": 25768, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 25841, "s": 25806, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 25899, "s": 25841, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 25942, "s": 25899, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 25991, "s": 25942, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 26041, "s": 25991, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 26058, "s": 26041, "text": "R - if statement" }, { "code": null, "e": 26095, "s": 26058, "text": "How to import an Excel File into R ?" } ]
Renaming and Deleting Files in Python
Python os module provides methods that help you perform file-processing operations, such as renaming and deleting files. To use this module you need to import it first and then you can call any related functions. The rename() method takes two arguments, the current filename and the new filename. os.rename(current_file_name, new_file_name) Following is the example to rename an existing file test1.txt − #!/usr/bin/python import os # Rename a file from test1.txt to test2.txt os.rename( "test1.txt", "test2.txt" ) You can use the remove() method to delete files by supplying the name of the file to be deleted as the argument. os.remove(file_name) Following is the example to delete an existing file test2.txt − #!/usr/bin/python import os # Delete file test2.txt os.remove("text2.txt")
[ { "code": null, "e": 1183, "s": 1062, "text": "Python os module provides methods that help you perform file-processing operations, such as renaming and deleting files." }, { "code": null, "e": 1275, "s": 1183, "text": "To use this module you need to import it first and then you can call any related functions." }, { "code": null, "e": 1359, "s": 1275, "text": "The rename() method takes two arguments, the current filename and the new filename." }, { "code": null, "e": 1403, "s": 1359, "text": "os.rename(current_file_name, new_file_name)" }, { "code": null, "e": 1467, "s": 1403, "text": "Following is the example to rename an existing file test1.txt −" }, { "code": null, "e": 1577, "s": 1467, "text": "#!/usr/bin/python\nimport os\n# Rename a file from test1.txt to test2.txt\nos.rename( \"test1.txt\", \"test2.txt\" )" }, { "code": null, "e": 1690, "s": 1577, "text": "You can use the remove() method to delete files by supplying the name of the file to be deleted as the argument." }, { "code": null, "e": 1712, "s": 1690, "text": "os.remove(file_name)\n" }, { "code": null, "e": 1776, "s": 1712, "text": "Following is the example to delete an existing file test2.txt −" }, { "code": null, "e": 1851, "s": 1776, "text": "#!/usr/bin/python\nimport os\n# Delete file test2.txt\nos.remove(\"text2.txt\")" } ]
Program for subtraction of matrices - GeeksforGeeks
24 Aug, 2021 The below program subtracts of two square matrices of size 4*4, we can change N for different dimension. C++ C Java Python3 C# PHP Javascript // C++ program for subtraction of matrices#include <bits/stdc++.h>using namespace std;#define N 4 // This function subtracts B[][] from A[][], and stores// the result in C[][]void subtract(int A[][N], int B[][N], int C[][N]){ int i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) C[i][j] = A[i][j] - B[i][j];} // Driver codeint main(){ int A[N][N] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int B[N][N] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int C[N][N]; // To store result int i, j; subtract(A, B, C); cout << "Result matrix is " << endl; for (i = 0; i < N; i++) { for (j = 0; j < N; j++) cout << C[i][j] << " "; cout << endl; } return 0;} // This code is contributed by rathbhupendra #include <stdio.h>#define N 4 // This function subtracts B[][] from A[][], and stores// the result in C[][]void subtract(int A[][N], int B[][N], int C[][N]){ int i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) C[i][j] = A[i][j] - B[i][j];} int main(){ int A[N][N] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int B[N][N] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int C[N][N]; // To store result int i, j; subtract(A, B, C); printf("Result matrix is \n"); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) printf("%d ", C[i][j]); printf("\n"); } return 0;} // Java program for subtraction of matrices class GFG{ static final int N=4; // This function subtracts B[][] // from A[][], and stores // the result in C[][] static void subtract(int A[][], int B[][], int C[][]) { int i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) C[i][j] = A[i][j] - B[i][j]; } // Driver code public static void main (String[] args) { int A[][] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int B[][] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; // To store result int C[][]=new int[N][N]; int i, j; subtract(A, B, C); System.out.print("Result matrix is \n"); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) System.out.print(C[i][j] + " "); System.out.print("\n"); } }} // This code is contributed by Anant Agarwal. # Python 3 program for subtraction# of matrices N = 4 # This function returns 1# if A[][] and B[][] are identical# otherwise returns 0def subtract(A, B, C): for i in range(N): for j in range(N): C[i][j] = A[i][j] - B[i][j] # Driver CodeA = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]] B = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]] C = A[:][:] # To store result subtract(A, B, C) print("Result matrix is")for i in range(N): for j in range(N): print(C[i][j], " ", end = '') print() # This code is contributed# by Anant Agarwal. // C# program for subtraction of matricesusing System; class GFG{static int N = 4; // This function subtracts B[][]// from A[][], and stores// the result in C[][]public static void subtract(int[][] A, int[][] B, int[, ] C){ int i, j; for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { C[i, j] = A[i][j] - B[i][j]; } }} // Driver codepublic static void Main(string[] args){ int[][] A = new int[][] { new int[] {1, 1, 1, 1}, new int[] {2, 2, 2, 2}, new int[] {3, 3, 3, 3}, new int[] {4, 4, 4, 4} }; int[][] B = new int[][] { new int[] {1, 1, 1, 1}, new int[] {2, 2, 2, 2}, new int[] {3, 3, 3, 3}, new int[] {4, 4, 4, 4} }; // To store result int[, ] C = new int[N, N]; int i, j; subtract(A, B, C); Console.Write("Result matrix is \n"); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { Console.Write(C[i, j] + " "); } Console.Write("\n"); }}} // This code is contributed by Shrikant13 <?php// This function subtracts B[][]// from A[][], and stores the// result in C[][]function subtract(&$A, &$B, &$C){ $N = 4; for ($i = 0; $i < $N; $i++) for ($j = 0; $j < $N; $j++) $C[$i][$j] = $A[$i][$j] - $B[$i][$j];} // Driver code$N = 4;$A = array(array(1, 1, 1, 1), array(2, 2, 2, 2), array(3, 3, 3, 3), array(4, 4, 4, 4)); $B = array(array(1, 1, 1, 1), array(2, 2, 2, 2), array(3, 3, 3, 3), array(4, 4, 4, 4)); subtract($A, $B, $C); echo "Result matrix is \n";for ($i = 0; $i < $N; $i++){ for ($j = 0; $j < $N; $j++) { echo $C[$i][$j]; echo " "; } echo "\n";} // This code is contributed// by Shivi_Aggarwal?> <script> // Javascript program for subtraction of matricesvar N = 4; // This function subtracts B[][] from A[][], and stores// the result in C[][]function subtract(A, B, C){ var i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) C[i][j] = A[i][j] - B[i][j];} // Driver codevar A = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]];var B = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]];var C = Array.from(Array(N), () => Array(N)); // To store resultvar i, j;subtract(A, B, C);document.write( "Result matrix is " + "<br>");for (i = 0; i < N; i++){ for (j = 0; j < N; j++) document.write( C[i][j] + " "); document.write("<br>");} // This code is contributed by itsok.</script> Output: Result matrix is 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 Note – The number at 0th row and 0th column of first matrix gets subtracted with number at 0th row and 0th column of second matrix. And its subtraction result gets initialized as the the value of 0th row and 0th column of resultant matrix. Same subtraction process applied for all the elements The program can be extended for rectangular matrices. The following post can be useful for extending this program. How to pass a 2D array as a parameter in C?The time complexity of the above program is O(n2). The auxiliary space of the above program is O(n2).Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Shivi_Aggarwal shrikanth13 rathbhupendra ASHUTOSH_GUPTA subhammahato348 itsok gargr0109 Matrix School Programming Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Efficiently compute sums of diagonals of a matrix Flood fill Algorithm - how to implement fill() in paint? Check for possible path in 2D matrix Zigzag (or diagonal) traversal of Matrix Mathematics | L U Decomposition of a System of Linear Equations Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 26166, "s": 26138, "text": "\n24 Aug, 2021" }, { "code": null, "e": 26272, "s": 26166, "text": "The below program subtracts of two square matrices of size 4*4, we can change N for different dimension. " }, { "code": null, "e": 26276, "s": 26272, "text": "C++" }, { "code": null, "e": 26278, "s": 26276, "text": "C" }, { "code": null, "e": 26283, "s": 26278, "text": "Java" }, { "code": null, "e": 26291, "s": 26283, "text": "Python3" }, { "code": null, "e": 26294, "s": 26291, "text": "C#" }, { "code": null, "e": 26298, "s": 26294, "text": "PHP" }, { "code": null, "e": 26309, "s": 26298, "text": "Javascript" }, { "code": "// C++ program for subtraction of matrices#include <bits/stdc++.h>using namespace std;#define N 4 // This function subtracts B[][] from A[][], and stores// the result in C[][]void subtract(int A[][N], int B[][N], int C[][N]){ int i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) C[i][j] = A[i][j] - B[i][j];} // Driver codeint main(){ int A[N][N] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int B[N][N] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int C[N][N]; // To store result int i, j; subtract(A, B, C); cout << \"Result matrix is \" << endl; for (i = 0; i < N; i++) { for (j = 0; j < N; j++) cout << C[i][j] << \" \"; cout << endl; } return 0;} // This code is contributed by rathbhupendra", "e": 27232, "s": 26309, "text": null }, { "code": "#include <stdio.h>#define N 4 // This function subtracts B[][] from A[][], and stores// the result in C[][]void subtract(int A[][N], int B[][N], int C[][N]){ int i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) C[i][j] = A[i][j] - B[i][j];} int main(){ int A[N][N] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int B[N][N] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int C[N][N]; // To store result int i, j; subtract(A, B, C); printf(\"Result matrix is \\n\"); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) printf(\"%d \", C[i][j]); printf(\"\\n\"); } return 0;}", "e": 28025, "s": 27232, "text": null }, { "code": "// Java program for subtraction of matrices class GFG{ static final int N=4; // This function subtracts B[][] // from A[][], and stores // the result in C[][] static void subtract(int A[][], int B[][], int C[][]) { int i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) C[i][j] = A[i][j] - B[i][j]; } // Driver code public static void main (String[] args) { int A[][] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int B[][] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; // To store result int C[][]=new int[N][N]; int i, j; subtract(A, B, C); System.out.print(\"Result matrix is \\n\"); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) System.out.print(C[i][j] + \" \"); System.out.print(\"\\n\"); } }} // This code is contributed by Anant Agarwal.", "e": 29157, "s": 28025, "text": null }, { "code": "# Python 3 program for subtraction# of matrices N = 4 # This function returns 1# if A[][] and B[][] are identical# otherwise returns 0def subtract(A, B, C): for i in range(N): for j in range(N): C[i][j] = A[i][j] - B[i][j] # Driver CodeA = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]] B = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]] C = A[:][:] # To store result subtract(A, B, C) print(\"Result matrix is\")for i in range(N): for j in range(N): print(C[i][j], \" \", end = '') print() # This code is contributed# by Anant Agarwal.", "e": 29809, "s": 29157, "text": null }, { "code": "// C# program for subtraction of matricesusing System; class GFG{static int N = 4; // This function subtracts B[][]// from A[][], and stores// the result in C[][]public static void subtract(int[][] A, int[][] B, int[, ] C){ int i, j; for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { C[i, j] = A[i][j] - B[i][j]; } }} // Driver codepublic static void Main(string[] args){ int[][] A = new int[][] { new int[] {1, 1, 1, 1}, new int[] {2, 2, 2, 2}, new int[] {3, 3, 3, 3}, new int[] {4, 4, 4, 4} }; int[][] B = new int[][] { new int[] {1, 1, 1, 1}, new int[] {2, 2, 2, 2}, new int[] {3, 3, 3, 3}, new int[] {4, 4, 4, 4} }; // To store result int[, ] C = new int[N, N]; int i, j; subtract(A, B, C); Console.Write(\"Result matrix is \\n\"); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { Console.Write(C[i, j] + \" \"); } Console.Write(\"\\n\"); }}} // This code is contributed by Shrikant13", "e": 30936, "s": 29809, "text": null }, { "code": "<?php// This function subtracts B[][]// from A[][], and stores the// result in C[][]function subtract(&$A, &$B, &$C){ $N = 4; for ($i = 0; $i < $N; $i++) for ($j = 0; $j < $N; $j++) $C[$i][$j] = $A[$i][$j] - $B[$i][$j];} // Driver code$N = 4;$A = array(array(1, 1, 1, 1), array(2, 2, 2, 2), array(3, 3, 3, 3), array(4, 4, 4, 4)); $B = array(array(1, 1, 1, 1), array(2, 2, 2, 2), array(3, 3, 3, 3), array(4, 4, 4, 4)); subtract($A, $B, $C); echo \"Result matrix is \\n\";for ($i = 0; $i < $N; $i++){ for ($j = 0; $j < $N; $j++) { echo $C[$i][$j]; echo \" \"; } echo \"\\n\";} // This code is contributed// by Shivi_Aggarwal?>", "e": 31691, "s": 30936, "text": null }, { "code": "<script> // Javascript program for subtraction of matricesvar N = 4; // This function subtracts B[][] from A[][], and stores// the result in C[][]function subtract(A, B, C){ var i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) C[i][j] = A[i][j] - B[i][j];} // Driver codevar A = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]];var B = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]];var C = Array.from(Array(N), () => Array(N)); // To store resultvar i, j;subtract(A, B, C);document.write( \"Result matrix is \" + \"<br>\");for (i = 0; i < N; i++){ for (j = 0; j < N; j++) document.write( C[i][j] + \" \"); document.write(\"<br>\");} // This code is contributed by itsok.</script>", "e": 32516, "s": 31691, "text": null }, { "code": null, "e": 32525, "s": 32516, "text": "Output: " }, { "code": null, "e": 32574, "s": 32525, "text": "Result matrix is\n0 0 0 0\n0 0 0 0\n0 0 0 0\n0 0 0 0" }, { "code": null, "e": 32868, "s": 32574, "text": "Note – The number at 0th row and 0th column of first matrix gets subtracted with number at 0th row and 0th column of second matrix. And its subtraction result gets initialized as the the value of 0th row and 0th column of resultant matrix. Same subtraction process applied for all the elements" }, { "code": null, "e": 33078, "s": 32868, "text": "The program can be extended for rectangular matrices. The following post can be useful for extending this program. How to pass a 2D array as a parameter in C?The time complexity of the above program is O(n2). " }, { "code": null, "e": 33253, "s": 33078, "text": "The auxiliary space of the above program is O(n2).Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 33268, "s": 33253, "text": "Shivi_Aggarwal" }, { "code": null, "e": 33280, "s": 33268, "text": "shrikanth13" }, { "code": null, "e": 33294, "s": 33280, "text": "rathbhupendra" }, { "code": null, "e": 33309, "s": 33294, "text": "ASHUTOSH_GUPTA" }, { "code": null, "e": 33325, "s": 33309, "text": "subhammahato348" }, { "code": null, "e": 33331, "s": 33325, "text": "itsok" }, { "code": null, "e": 33341, "s": 33331, "text": "gargr0109" }, { "code": null, "e": 33348, "s": 33341, "text": "Matrix" }, { "code": null, "e": 33367, "s": 33348, "text": "School Programming" }, { "code": null, "e": 33374, "s": 33367, "text": "Matrix" }, { "code": null, "e": 33472, "s": 33374, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33522, "s": 33472, "text": "Efficiently compute sums of diagonals of a matrix" }, { "code": null, "e": 33579, "s": 33522, "text": "Flood fill Algorithm - how to implement fill() in paint?" }, { "code": null, "e": 33616, "s": 33579, "text": "Check for possible path in 2D matrix" }, { "code": null, "e": 33657, "s": 33616, "text": "Zigzag (or diagonal) traversal of Matrix" }, { "code": null, "e": 33721, "s": 33657, "text": "Mathematics | L U Decomposition of a System of Linear Equations" }, { "code": null, "e": 33739, "s": 33721, "text": "Python Dictionary" }, { "code": null, "e": 33755, "s": 33739, "text": "Arrays in C/C++" }, { "code": null, "e": 33774, "s": 33755, "text": "Inheritance in C++" }, { "code": null, "e": 33799, "s": 33774, "text": "Reverse a string in Java" } ]
Find Exponential of a column in Pandas-Python - GeeksforGeeks
02 Jul, 2021 Let’s see how to find Exponential of a column in Pandas Dataframe. First, let’s create a Dataframe: Python3 # importing pandas and# numpy librariesimport pandas as pdimport numpy as np # creating and initializing a listvalues= [ ['Rohan', 5, 50.59], ['Elvish', 2, 90.57], ['Deepak', 10, 98.51], ['Soni', 4, 40.24], ['Radhika', 1, 99.05], ['Vansh', 15, 85.56] ] # creating a pandas dataframedf = pd.DataFrame(values, columns = ['Name', 'University_Rank', 'University_Marks']) # displaying the data framedf Output: The exponential of any column is found out by using numpy.exp() function. This function calculates the exponential of the input array/Series. Syntax: numpy.exp(array, out = None, where = True, casting = ‘same_kind’, order = ‘K’, dtype = None) Return: An array with exponential of all elements of input array/Series. Example 1: Finding exponential of the single column (integer values). Python3 # importing pandas and# numpy librariesimport pandas as pdimport numpy as np # creating and initializing a listvalues= [ ['Rohan', 5, 50.59], ['Elvish', 2, 90.57], ['Deepak', 10, 98.51], ['Soni', 4, 40.24], ['Radhika', 1, 99.05], ['Vansh', 15, 85.56] ] # creating a pandas dataframedf = pd.DataFrame(values, columns = ['Name', 'University_Rank', 'University_Marks']) # finding the exponential value# of column using np.exp() functiondf['exp_value'] = np.exp(df['University_Rank']) # displaying the data framedf Output: Example 2: Finding exponential of the single column (Float values). Python3 # importing pandas and# numpy librariesimport pandas as pdimport numpy as np # creating and initializing a listvalues= [ ['Rohan', 5, 50.59], ['Elvish', 2, 90.57], ['Deepak', 10, 98.51], ['Soni', 4, 40.24], ['Radhika', 1, 99.05], ['Vansh', 15, 85.56] ] # creating a pandas dataframedf = pd.DataFrame(values, columns = ['Name', 'University_Rank', 'University_Marks']) # finding the exponential value# of column using np.exp() functiondf['exp_value'] = np.exp(df['University_Marks']) # displaying the data framedf Output: surinderdawra388 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 ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n02 Jul, 2021" }, { "code": null, "e": 25637, "s": 25537, "text": "Let’s see how to find Exponential of a column in Pandas Dataframe. First, let’s create a Dataframe:" }, { "code": null, "e": 25645, "s": 25637, "text": "Python3" }, { "code": "# importing pandas and# numpy librariesimport pandas as pdimport numpy as np # creating and initializing a listvalues= [ ['Rohan', 5, 50.59], ['Elvish', 2, 90.57], ['Deepak', 10, 98.51], ['Soni', 4, 40.24], ['Radhika', 1, 99.05], ['Vansh', 15, 85.56] ] # creating a pandas dataframedf = pd.DataFrame(values, columns = ['Name', 'University_Rank', 'University_Marks']) # displaying the data framedf", "e": 26131, "s": 25645, "text": null }, { "code": null, "e": 26143, "s": 26135, "text": "Output:" }, { "code": null, "e": 26290, "s": 26147, "text": " The exponential of any column is found out by using numpy.exp() function. This function calculates the exponential of the input array/Series." }, { "code": null, "e": 26395, "s": 26292, "text": "Syntax: numpy.exp(array, out = None, where = True, casting = ‘same_kind’, order = ‘K’, dtype = None) " }, { "code": null, "e": 26470, "s": 26395, "text": "Return: An array with exponential of all elements of input array/Series. " }, { "code": null, "e": 26542, "s": 26472, "text": "Example 1: Finding exponential of the single column (integer values)." }, { "code": null, "e": 26552, "s": 26544, "text": "Python3" }, { "code": "# importing pandas and# numpy librariesimport pandas as pdimport numpy as np # creating and initializing a listvalues= [ ['Rohan', 5, 50.59], ['Elvish', 2, 90.57], ['Deepak', 10, 98.51], ['Soni', 4, 40.24], ['Radhika', 1, 99.05], ['Vansh', 15, 85.56] ] # creating a pandas dataframedf = pd.DataFrame(values, columns = ['Name', 'University_Rank', 'University_Marks']) # finding the exponential value# of column using np.exp() functiondf['exp_value'] = np.exp(df['University_Rank']) # displaying the data framedf", "e": 27152, "s": 26552, "text": null }, { "code": null, "e": 27164, "s": 27156, "text": "Output:" }, { "code": null, "e": 27236, "s": 27168, "text": "Example 2: Finding exponential of the single column (Float values)." }, { "code": null, "e": 27246, "s": 27238, "text": "Python3" }, { "code": "# importing pandas and# numpy librariesimport pandas as pdimport numpy as np # creating and initializing a listvalues= [ ['Rohan', 5, 50.59], ['Elvish', 2, 90.57], ['Deepak', 10, 98.51], ['Soni', 4, 40.24], ['Radhika', 1, 99.05], ['Vansh', 15, 85.56] ] # creating a pandas dataframedf = pd.DataFrame(values, columns = ['Name', 'University_Rank', 'University_Marks']) # finding the exponential value# of column using np.exp() functiondf['exp_value'] = np.exp(df['University_Marks']) # displaying the data framedf", "e": 27848, "s": 27246, "text": null }, { "code": null, "e": 27860, "s": 27852, "text": "Output:" }, { "code": null, "e": 27881, "s": 27864, "text": "surinderdawra388" }, { "code": null, "e": 27905, "s": 27881, "text": "Python pandas-dataFrame" }, { "code": null, "e": 27928, "s": 27905, "text": "Python Pandas-exercise" }, { "code": null, "e": 27942, "s": 27928, "text": "Python-pandas" }, { "code": null, "e": 27949, "s": 27942, "text": "Python" }, { "code": null, "e": 28047, "s": 27949, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28079, "s": 28047, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28121, "s": 28079, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28163, "s": 28121, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28190, "s": 28163, "text": "Python Classes and Objects" }, { "code": null, "e": 28246, "s": 28190, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28268, "s": 28246, "text": "Defaultdict in Python" }, { "code": null, "e": 28307, "s": 28268, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28338, "s": 28307, "text": "Python | os.path.join() method" }, { "code": null, "e": 28367, "s": 28338, "text": "Create a directory in Python" } ]
K maximum sum combinations from two arrays - GeeksforGeeks
02 Jul, 2021 Given two equally sized arrays (A, B) and N (size of both arrays). A sum combination is made by adding one element from array A and another element of array B. Display the maximum K valid sum combinations from all the possible sum combinations. Examples: Input : A[] : {3, 2} B[] : {1, 4} K : 2 [Number of maximum sum combinations to be printed] Output : 7 // (A : 3) + (B : 4) 6 // (A : 2) + (B : 4) Input : A[] : {4, 2, 5, 1} B[] : {8, 0, 3, 5} K : 3 Output : 13 // (A : 5) + (B : 8) 12 // (A : 4) + (B : 8) 10 // (A : 2) + (B : 8) Approach 1 (Naive Algorithm) : We can use Brute force through all the possible combinations that can be made by taking one element from array A and another from array B and inserting them to a max heap. In a max heap maximum element is at the root node so whenever we pop from max heap we get the maximum element present in the heap. After inserting all the sum combinations we take out K elements from max heap and display it.Below is the implementation of the above approach. C++ Java Python 3 C# Javascript // A simple C++ program to find N maximum// combinations from two arrays,#include <bits/stdc++.h>using namespace std; // function to display first N maximum sum// combinationsvoid KMaxCombinations(int A[], int B[], int N, int K){ // max heap. priority_queue<int> pq; // insert all the possible combinations // in max heap. for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) pq.push(A[i] + B[j]); // pop first N elements from max heap // and display them. int count = 0; while (count < K) { cout << pq.top() << endl; pq.pop(); count++; }} // Driver Code.int main(){ int A[] = { 4, 2, 5, 1 }; int B[] = { 8, 0, 5, 3 }; int N = sizeof(A) / sizeof(A[0]); int K = 3; // Function call KMaxCombinations(A, B, N, K); return 0;} // Java program to find K// maximum combinations// from two arrays,import java.io.*;import java.util.*; class GFG { // function to display first K // maximum sum combinations static void KMaxCombinations(int A[], int B[], int N, int K) { // max heap. PriorityQueue<Integer> pq = new PriorityQueue<Integer>( Collections.reverseOrder()); // Insert all the possible // combinations in max heap. for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) pq.add(A[i] + B[j]); // Pop first N elements // from max heap and // display them. int count = 0; while (count < K) { System.out.println(pq.peek()); pq.remove(); count++; } } // Driver Code public static void main(String[] args) { int A[] = { 4, 2, 5, 1 }; int B[] = { 8, 0, 5, 3 }; int N = A.length; int K = 3; // Function Call KMaxCombinations(A, B, N, K); }} // This code is contributed by Mayank Tyagi # Python program to find# K maximum combinations# from two arraysimport mathfrom queue import PriorityQueue # Function to display first K# maximum sum combinations def KMaxCombinations(A, B, N, K): # Max heap. pq = PriorityQueue() # Insert all the possible # combinations in max heap. for i in range(0, N): for j in range(0, N): a = A[i] + B[j] pq.put((-a, a)) # Pop first N elements from # max heap and display them. count = 0 while (count < K): print(pq.get()[1]) count = count + 1 # Driver methodA = [4, 2, 5, 1]B = [8, 0, 5, 3]N = len(A)K = 3 # Function callKMaxCombinations(A, B, N, K) # This code is contributed# by Gitanjali. // C# program to find K// maximum combinations// from two arrays,using System;using System.Collections.Generic;public class GFG{ // function to display first K // maximum sum combinations static void KMaxCombinations(int []A, int []B, int N, int K) { // max heap. List<int> pq = new List<int>(); // Insert all the possible // combinations in max heap. for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) pq.Add(A[i] + B[j]); // Pop first N elements // from max heap and // display them. int count = 0; pq.Sort(); pq.Reverse(); while (count < K) { Console.WriteLine(pq[0]); pq.RemoveAt(0); count++; } } // Driver Code public static void Main(String[] args) { int []A = { 4, 2, 5, 1 }; int []B = { 8, 0, 5, 3 }; int N = A.Length; int K = 3; // Function Call KMaxCombinations(A, B, N, K); }} // This code is contributed by Rajput-Ji <script>// Javascript program to find K// maximum combinations// from two arrays, // function to display first K// maximum sum combinationsfunction KMaxCombinations(A, B, N, K){ // max heap. let pq = []; // Insert all the possible // combinations in max heap. for (let i = 0; i < N; i++) for (let j = 0; j < N; j++) pq.push(A[i] + B[j]); // Pop first N elements // from max heap and // display them. let count = 0; pq.sort((a, b) => a - b).reverse(); while (count < K) { document.write(pq[0] + "<br>"); pq.shift(); count++; }} // Driver Code let A = [ 4, 2, 5, 1 ]; let B = [ 8, 0, 5, 3 ]; let N = A.length; let K = 3; // Function Call KMaxCombinations(A, B, N, K); // This code is contributed by gfgking</script> 13 12 10 Time Complexity: O(N2) Approach 2 (Sorting, Max heap, Map) : Instead of brute-forcing through all the possible sum combinations, we should find a way to limit our search space to possible candidate sum combinations. Sort both arrays array A and array B.Create a max heap i.e priority_queue in C++ to store the sum combinations along with the indices of elements from both arrays A and B which make up the sum. Heap is ordered by the sum.Initialize the heap with the maximum possible sum combination i.e (A[N – 1] + B[N – 1] where N is the size of array) and with the indices of elements from both arrays (N – 1, N – 1). The tuple inside max heap will be (A[N-1] + B[N – 1], N – 1, N – 1). Heap is ordered by first value i.e sum of both elements.Pop the heap to get the current largest sum and along with the indices of the element that make up the sum. Let the tuple be (sum, i, j).Next insert (A[i – 1] + B[j], i – 1, j) and (A[i] + B[j – 1], i, j – 1) into the max heap but make sure that the pair of indices i.e (i – 1, j) and (i, j – 1) are not already present in the max heap. To check this we can use set in C++.Go back to 4 until K times. Sort both arrays array A and array B. Create a max heap i.e priority_queue in C++ to store the sum combinations along with the indices of elements from both arrays A and B which make up the sum. Heap is ordered by the sum. Initialize the heap with the maximum possible sum combination i.e (A[N – 1] + B[N – 1] where N is the size of array) and with the indices of elements from both arrays (N – 1, N – 1). The tuple inside max heap will be (A[N-1] + B[N – 1], N – 1, N – 1). Heap is ordered by first value i.e sum of both elements. Pop the heap to get the current largest sum and along with the indices of the element that make up the sum. Let the tuple be (sum, i, j).Next insert (A[i – 1] + B[j], i – 1, j) and (A[i] + B[j – 1], i, j – 1) into the max heap but make sure that the pair of indices i.e (i – 1, j) and (i, j – 1) are not already present in the max heap. To check this we can use set in C++.Go back to 4 until K times. Next insert (A[i – 1] + B[j], i – 1, j) and (A[i] + B[j – 1], i, j – 1) into the max heap but make sure that the pair of indices i.e (i – 1, j) and (i, j – 1) are not already present in the max heap. To check this we can use set in C++.Go back to 4 until K times. Next insert (A[i – 1] + B[j], i – 1, j) and (A[i] + B[j – 1], i, j – 1) into the max heap but make sure that the pair of indices i.e (i – 1, j) and (i, j – 1) are not already present in the max heap. To check this we can use set in C++. Go back to 4 until K times. Below is the implementation of the above approach: CPP Java // An efficient C++ program to find top K elements// from two arrays.#include <bits/stdc++.h>using namespace std; // Function prints k maximum possible combinationsvoid KMaxCombinations(vector<int>& A, vector<int>& B, int K){ // sort both arrays A and B sort(A.begin(), A.end()); sort(B.begin(), B.end()); int N = A.size(); // Max heap which contains tuple of the format // (sum, (i, j)) i and j are the indices // of the elements from array A // and array B which make up the sum. priority_queue<pair<int, pair<int, int> > > pq; // my_set is used to store the indices of // the pair(i, j) we use my_set to make sure // the indices doe not repeat inside max heap. set<pair<int, int> > my_set; // initialize the heap with the maximum sum // combination ie (A[N - 1] + B[N - 1]) // and also push indices (N - 1, N - 1) along // with sum. pq.push(make_pair(A[N - 1] + B[N - 1], make_pair(N - 1, N - 1))); my_set.insert(make_pair(N - 1, N - 1)); // iterate upto K for (int count = 0; count < K; count++) { // tuple format (sum, (i, j)). pair<int, pair<int, int> > temp = pq.top(); pq.pop(); cout << temp.first << endl; int i = temp.second.first; int j = temp.second.second; int sum = A[i - 1] + B[j]; // insert (A[i - 1] + B[j], (i - 1, j)) // into max heap. pair<int, int> temp1 = make_pair(i - 1, j); // insert only if the pair (i - 1, j) is // not already present inside the map i.e. // no repeating pair should be present inside // the heap. if (my_set.find(temp1) == my_set.end()) { pq.push(make_pair(sum, temp1)); my_set.insert(temp1); } // insert (A[i] + B[j - 1], (i, j - 1)) // into max heap. sum = A[i] + B[j - 1]; temp1 = make_pair(i, j - 1); // insert only if the pair (i, j - 1) // is not present inside the heap. if (my_set.find(temp1) == my_set.end()) { pq.push(make_pair(sum, temp1)); my_set.insert(temp1); } }} // Driver Code.int main(){ vector<int> A = { 1, 4, 2, 3 }; vector<int> B = { 2, 5, 1, 6 }; int K = 4; // Function call KMaxCombinations(A, B, K); return 0;} // An efficient Java program to find// top K elements from two arrays. import java.io.*;import java.util.*; class GFG { public static void MaxPairSum(Integer[] A, Integer[] B, int N, int K) { // sort both arrays A and B Arrays.sort(A); Arrays.sort(B); // Max heap which contains Pair of // the format (sum, (i, j)) i and j are // the indices of the elements from // array A and array B which make up the sum. PriorityQueue<PairSum> sums = new PriorityQueue<PairSum>(); // pairs is used to store the indices of // the Pair(i, j) we use pairs to make sure // the indices doe not repeat inside max heap. HashSet<Pair> pairs = new HashSet<Pair>(); // initialize the heap with the maximum sum // combination ie (A[N - 1] + B[N - 1]) // and also push indices (N - 1, N - 1) along // with sum. int l = N - 1; int m = N - 1; pairs.add(new Pair(l, m)); sums.add(new PairSum(A[l] + B[m], l, m)); // iterate upto K for (int i = 0; i < K; i++) { // Poll the element from the // maxheap in theformat (sum, (l,m)) PairSum max = sums.poll(); System.out.println(max.sum); l = max.l - 1; m = max.m; // insert only if l and m are greater // than 0 and the pair (l, m) is // not already present inside set i.e. // no repeating pair should be // present inside the heap. if (l >= 0 && m >= 0 && !pairs.contains(new Pair(l, m))) { // insert (A[l]+B[m], (l, m)) // in the heap sums.add(new PairSum(A[l] + B[m], l, m)); pairs.add(new Pair(l, m)); } l = max.l; m = max.m - 1; // insert only if l and m are // greater than 0 and // the pair (l, m) is not // already present inside // set i.e. no repeating pair // should be present // inside the heap. if (l >= 0 && m >= 0 && !pairs.contains(new Pair(l, m))) { // insert (A[i1]+B[i2], (i1, i2)) // in the heap sums.add(new PairSum(A[l] + B[m], l, m)); pairs.add(new Pair(l, m)); } } } // Driver Code public static void main(String[] args) { Integer A[] = { 1, 4, 2, 3 }; Integer B[] = { 2, 5, 1, 6 }; int N = A.length; int K = 4; // Function Call MaxPairSum(A, B, N, K); } public static class Pair { public Pair(int l, int m) { this.l = l; this.m = m; } int l; int m; @Override public boolean equals(Object o) { if (o == null) { return false; } if (!(o instanceof Pair)) { return false; } Pair obj = (Pair)o; return (l == obj.l && m == obj.m); } @Override public int hashCode() { return Objects.hash(l, m); } } public static class PairSum implements Comparable<PairSum> { public PairSum(int sum, int l, int m) { this.sum = sum; this.l = l; this.m = m; } int sum; int l; int m; @Override public int compareTo(PairSum o) { return Integer.compare(o.sum, sum); } }} 10 9 9 8 Time Complexity : O(N log N) assuming K <= N nikhil741 UmangSingh1 rhlkmr089 mayanktyagi1709 Rajput-Ji gfgking Order-Statistics Arrays Heap Arrays Heap Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Arrays Linked List vs Array Search an element in a sorted and rotated array Queue | Set 1 (Introduction and Array Implementation) Find the Missing Number HeapSort Binary Heap Huffman Coding | Greedy Algo-3 k largest(or smallest) elements in an array Building Heap from Array
[ { "code": null, "e": 26299, "s": 26271, "text": "\n02 Jul, 2021" }, { "code": null, "e": 26545, "s": 26299, "text": "Given two equally sized arrays (A, B) and N (size of both arrays). A sum combination is made by adding one element from array A and another element of array B. Display the maximum K valid sum combinations from all the possible sum combinations. " }, { "code": null, "e": 26556, "s": 26545, "text": "Examples: " }, { "code": null, "e": 26930, "s": 26556, "text": "Input : A[] : {3, 2} \n B[] : {1, 4}\n K : 2 [Number of maximum sum\n combinations to be printed]\nOutput : 7 // (A : 3) + (B : 4)\n 6 // (A : 2) + (B : 4)\n\nInput : A[] : {4, 2, 5, 1}\n B[] : {8, 0, 3, 5}\n K : 3\nOutput : 13 // (A : 5) + (B : 8)\n 12 // (A : 4) + (B : 8)\n 10 // (A : 2) + (B : 8)" }, { "code": null, "e": 27409, "s": 26930, "text": "Approach 1 (Naive Algorithm) : We can use Brute force through all the possible combinations that can be made by taking one element from array A and another from array B and inserting them to a max heap. In a max heap maximum element is at the root node so whenever we pop from max heap we get the maximum element present in the heap. After inserting all the sum combinations we take out K elements from max heap and display it.Below is the implementation of the above approach. " }, { "code": null, "e": 27413, "s": 27409, "text": "C++" }, { "code": null, "e": 27418, "s": 27413, "text": "Java" }, { "code": null, "e": 27427, "s": 27418, "text": "Python 3" }, { "code": null, "e": 27430, "s": 27427, "text": "C#" }, { "code": null, "e": 27441, "s": 27430, "text": "Javascript" }, { "code": "// A simple C++ program to find N maximum// combinations from two arrays,#include <bits/stdc++.h>using namespace std; // function to display first N maximum sum// combinationsvoid KMaxCombinations(int A[], int B[], int N, int K){ // max heap. priority_queue<int> pq; // insert all the possible combinations // in max heap. for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) pq.push(A[i] + B[j]); // pop first N elements from max heap // and display them. int count = 0; while (count < K) { cout << pq.top() << endl; pq.pop(); count++; }} // Driver Code.int main(){ int A[] = { 4, 2, 5, 1 }; int B[] = { 8, 0, 5, 3 }; int N = sizeof(A) / sizeof(A[0]); int K = 3; // Function call KMaxCombinations(A, B, N, K); return 0;}", "e": 28282, "s": 27441, "text": null }, { "code": "// Java program to find K// maximum combinations// from two arrays,import java.io.*;import java.util.*; class GFG { // function to display first K // maximum sum combinations static void KMaxCombinations(int A[], int B[], int N, int K) { // max heap. PriorityQueue<Integer> pq = new PriorityQueue<Integer>( Collections.reverseOrder()); // Insert all the possible // combinations in max heap. for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) pq.add(A[i] + B[j]); // Pop first N elements // from max heap and // display them. int count = 0; while (count < K) { System.out.println(pq.peek()); pq.remove(); count++; } } // Driver Code public static void main(String[] args) { int A[] = { 4, 2, 5, 1 }; int B[] = { 8, 0, 5, 3 }; int N = A.length; int K = 3; // Function Call KMaxCombinations(A, B, N, K); }} // This code is contributed by Mayank Tyagi", "e": 29405, "s": 28282, "text": null }, { "code": "# Python program to find# K maximum combinations# from two arraysimport mathfrom queue import PriorityQueue # Function to display first K# maximum sum combinations def KMaxCombinations(A, B, N, K): # Max heap. pq = PriorityQueue() # Insert all the possible # combinations in max heap. for i in range(0, N): for j in range(0, N): a = A[i] + B[j] pq.put((-a, a)) # Pop first N elements from # max heap and display them. count = 0 while (count < K): print(pq.get()[1]) count = count + 1 # Driver methodA = [4, 2, 5, 1]B = [8, 0, 5, 3]N = len(A)K = 3 # Function callKMaxCombinations(A, B, N, K) # This code is contributed# by Gitanjali.", "e": 30113, "s": 29405, "text": null }, { "code": "// C# program to find K// maximum combinations// from two arrays,using System;using System.Collections.Generic;public class GFG{ // function to display first K // maximum sum combinations static void KMaxCombinations(int []A, int []B, int N, int K) { // max heap. List<int> pq = new List<int>(); // Insert all the possible // combinations in max heap. for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) pq.Add(A[i] + B[j]); // Pop first N elements // from max heap and // display them. int count = 0; pq.Sort(); pq.Reverse(); while (count < K) { Console.WriteLine(pq[0]); pq.RemoveAt(0); count++; } } // Driver Code public static void Main(String[] args) { int []A = { 4, 2, 5, 1 }; int []B = { 8, 0, 5, 3 }; int N = A.Length; int K = 3; // Function Call KMaxCombinations(A, B, N, K); }} // This code is contributed by Rajput-Ji", "e": 31084, "s": 30113, "text": null }, { "code": "<script>// Javascript program to find K// maximum combinations// from two arrays, // function to display first K// maximum sum combinationsfunction KMaxCombinations(A, B, N, K){ // max heap. let pq = []; // Insert all the possible // combinations in max heap. for (let i = 0; i < N; i++) for (let j = 0; j < N; j++) pq.push(A[i] + B[j]); // Pop first N elements // from max heap and // display them. let count = 0; pq.sort((a, b) => a - b).reverse(); while (count < K) { document.write(pq[0] + \"<br>\"); pq.shift(); count++; }} // Driver Code let A = [ 4, 2, 5, 1 ]; let B = [ 8, 0, 5, 3 ]; let N = A.length; let K = 3; // Function Call KMaxCombinations(A, B, N, K); // This code is contributed by gfgking</script>", "e": 31879, "s": 31084, "text": null }, { "code": null, "e": 31888, "s": 31879, "text": "13\n12\n10" }, { "code": null, "e": 31911, "s": 31888, "text": "Time Complexity: O(N2)" }, { "code": null, "e": 32105, "s": 31911, "text": "Approach 2 (Sorting, Max heap, Map) : Instead of brute-forcing through all the possible sum combinations, we should find a way to limit our search space to possible candidate sum combinations. " }, { "code": null, "e": 33035, "s": 32105, "text": "Sort both arrays array A and array B.Create a max heap i.e priority_queue in C++ to store the sum combinations along with the indices of elements from both arrays A and B which make up the sum. Heap is ordered by the sum.Initialize the heap with the maximum possible sum combination i.e (A[N – 1] + B[N – 1] where N is the size of array) and with the indices of elements from both arrays (N – 1, N – 1). The tuple inside max heap will be (A[N-1] + B[N – 1], N – 1, N – 1). Heap is ordered by first value i.e sum of both elements.Pop the heap to get the current largest sum and along with the indices of the element that make up the sum. Let the tuple be (sum, i, j).Next insert (A[i – 1] + B[j], i – 1, j) and (A[i] + B[j – 1], i, j – 1) into the max heap but make sure that the pair of indices i.e (i – 1, j) and (i, j – 1) are not already present in the max heap. To check this we can use set in C++.Go back to 4 until K times." }, { "code": null, "e": 33073, "s": 33035, "text": "Sort both arrays array A and array B." }, { "code": null, "e": 33258, "s": 33073, "text": "Create a max heap i.e priority_queue in C++ to store the sum combinations along with the indices of elements from both arrays A and B which make up the sum. Heap is ordered by the sum." }, { "code": null, "e": 33567, "s": 33258, "text": "Initialize the heap with the maximum possible sum combination i.e (A[N – 1] + B[N – 1] where N is the size of array) and with the indices of elements from both arrays (N – 1, N – 1). The tuple inside max heap will be (A[N-1] + B[N – 1], N – 1, N – 1). Heap is ordered by first value i.e sum of both elements." }, { "code": null, "e": 33968, "s": 33567, "text": "Pop the heap to get the current largest sum and along with the indices of the element that make up the sum. Let the tuple be (sum, i, j).Next insert (A[i – 1] + B[j], i – 1, j) and (A[i] + B[j – 1], i, j – 1) into the max heap but make sure that the pair of indices i.e (i – 1, j) and (i, j – 1) are not already present in the max heap. To check this we can use set in C++.Go back to 4 until K times." }, { "code": null, "e": 34232, "s": 33968, "text": "Next insert (A[i – 1] + B[j], i – 1, j) and (A[i] + B[j – 1], i, j – 1) into the max heap but make sure that the pair of indices i.e (i – 1, j) and (i, j – 1) are not already present in the max heap. To check this we can use set in C++.Go back to 4 until K times." }, { "code": null, "e": 34469, "s": 34232, "text": "Next insert (A[i – 1] + B[j], i – 1, j) and (A[i] + B[j – 1], i, j – 1) into the max heap but make sure that the pair of indices i.e (i – 1, j) and (i, j – 1) are not already present in the max heap. To check this we can use set in C++." }, { "code": null, "e": 34497, "s": 34469, "text": "Go back to 4 until K times." }, { "code": null, "e": 34548, "s": 34497, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 34552, "s": 34548, "text": "CPP" }, { "code": null, "e": 34557, "s": 34552, "text": "Java" }, { "code": "// An efficient C++ program to find top K elements// from two arrays.#include <bits/stdc++.h>using namespace std; // Function prints k maximum possible combinationsvoid KMaxCombinations(vector<int>& A, vector<int>& B, int K){ // sort both arrays A and B sort(A.begin(), A.end()); sort(B.begin(), B.end()); int N = A.size(); // Max heap which contains tuple of the format // (sum, (i, j)) i and j are the indices // of the elements from array A // and array B which make up the sum. priority_queue<pair<int, pair<int, int> > > pq; // my_set is used to store the indices of // the pair(i, j) we use my_set to make sure // the indices doe not repeat inside max heap. set<pair<int, int> > my_set; // initialize the heap with the maximum sum // combination ie (A[N - 1] + B[N - 1]) // and also push indices (N - 1, N - 1) along // with sum. pq.push(make_pair(A[N - 1] + B[N - 1], make_pair(N - 1, N - 1))); my_set.insert(make_pair(N - 1, N - 1)); // iterate upto K for (int count = 0; count < K; count++) { // tuple format (sum, (i, j)). pair<int, pair<int, int> > temp = pq.top(); pq.pop(); cout << temp.first << endl; int i = temp.second.first; int j = temp.second.second; int sum = A[i - 1] + B[j]; // insert (A[i - 1] + B[j], (i - 1, j)) // into max heap. pair<int, int> temp1 = make_pair(i - 1, j); // insert only if the pair (i - 1, j) is // not already present inside the map i.e. // no repeating pair should be present inside // the heap. if (my_set.find(temp1) == my_set.end()) { pq.push(make_pair(sum, temp1)); my_set.insert(temp1); } // insert (A[i] + B[j - 1], (i, j - 1)) // into max heap. sum = A[i] + B[j - 1]; temp1 = make_pair(i, j - 1); // insert only if the pair (i, j - 1) // is not present inside the heap. if (my_set.find(temp1) == my_set.end()) { pq.push(make_pair(sum, temp1)); my_set.insert(temp1); } }} // Driver Code.int main(){ vector<int> A = { 1, 4, 2, 3 }; vector<int> B = { 2, 5, 1, 6 }; int K = 4; // Function call KMaxCombinations(A, B, K); return 0;}", "e": 36910, "s": 34557, "text": null }, { "code": "// An efficient Java program to find// top K elements from two arrays. import java.io.*;import java.util.*; class GFG { public static void MaxPairSum(Integer[] A, Integer[] B, int N, int K) { // sort both arrays A and B Arrays.sort(A); Arrays.sort(B); // Max heap which contains Pair of // the format (sum, (i, j)) i and j are // the indices of the elements from // array A and array B which make up the sum. PriorityQueue<PairSum> sums = new PriorityQueue<PairSum>(); // pairs is used to store the indices of // the Pair(i, j) we use pairs to make sure // the indices doe not repeat inside max heap. HashSet<Pair> pairs = new HashSet<Pair>(); // initialize the heap with the maximum sum // combination ie (A[N - 1] + B[N - 1]) // and also push indices (N - 1, N - 1) along // with sum. int l = N - 1; int m = N - 1; pairs.add(new Pair(l, m)); sums.add(new PairSum(A[l] + B[m], l, m)); // iterate upto K for (int i = 0; i < K; i++) { // Poll the element from the // maxheap in theformat (sum, (l,m)) PairSum max = sums.poll(); System.out.println(max.sum); l = max.l - 1; m = max.m; // insert only if l and m are greater // than 0 and the pair (l, m) is // not already present inside set i.e. // no repeating pair should be // present inside the heap. if (l >= 0 && m >= 0 && !pairs.contains(new Pair(l, m))) { // insert (A[l]+B[m], (l, m)) // in the heap sums.add(new PairSum(A[l] + B[m], l, m)); pairs.add(new Pair(l, m)); } l = max.l; m = max.m - 1; // insert only if l and m are // greater than 0 and // the pair (l, m) is not // already present inside // set i.e. no repeating pair // should be present // inside the heap. if (l >= 0 && m >= 0 && !pairs.contains(new Pair(l, m))) { // insert (A[i1]+B[i2], (i1, i2)) // in the heap sums.add(new PairSum(A[l] + B[m], l, m)); pairs.add(new Pair(l, m)); } } } // Driver Code public static void main(String[] args) { Integer A[] = { 1, 4, 2, 3 }; Integer B[] = { 2, 5, 1, 6 }; int N = A.length; int K = 4; // Function Call MaxPairSum(A, B, N, K); } public static class Pair { public Pair(int l, int m) { this.l = l; this.m = m; } int l; int m; @Override public boolean equals(Object o) { if (o == null) { return false; } if (!(o instanceof Pair)) { return false; } Pair obj = (Pair)o; return (l == obj.l && m == obj.m); } @Override public int hashCode() { return Objects.hash(l, m); } } public static class PairSum implements Comparable<PairSum> { public PairSum(int sum, int l, int m) { this.sum = sum; this.l = l; this.m = m; } int sum; int l; int m; @Override public int compareTo(PairSum o) { return Integer.compare(o.sum, sum); } }}", "e": 40672, "s": 36910, "text": null }, { "code": null, "e": 40681, "s": 40672, "text": "10\n9\n9\n8" }, { "code": null, "e": 40726, "s": 40681, "text": "Time Complexity : O(N log N) assuming K <= N" }, { "code": null, "e": 40736, "s": 40726, "text": "nikhil741" }, { "code": null, "e": 40748, "s": 40736, "text": "UmangSingh1" }, { "code": null, "e": 40758, "s": 40748, "text": "rhlkmr089" }, { "code": null, "e": 40774, "s": 40758, "text": "mayanktyagi1709" }, { "code": null, "e": 40784, "s": 40774, "text": "Rajput-Ji" }, { "code": null, "e": 40792, "s": 40784, "text": "gfgking" }, { "code": null, "e": 40809, "s": 40792, "text": "Order-Statistics" }, { "code": null, "e": 40816, "s": 40809, "text": "Arrays" }, { "code": null, "e": 40821, "s": 40816, "text": "Heap" }, { "code": null, "e": 40828, "s": 40821, "text": "Arrays" }, { "code": null, "e": 40833, "s": 40828, "text": "Heap" }, { "code": null, "e": 40931, "s": 40833, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40954, "s": 40931, "text": "Introduction to Arrays" }, { "code": null, "e": 40975, "s": 40954, "text": "Linked List vs Array" }, { "code": null, "e": 41023, "s": 40975, "text": "Search an element in a sorted and rotated array" }, { "code": null, "e": 41077, "s": 41023, "text": "Queue | Set 1 (Introduction and Array Implementation)" }, { "code": null, "e": 41101, "s": 41077, "text": "Find the Missing Number" }, { "code": null, "e": 41110, "s": 41101, "text": "HeapSort" }, { "code": null, "e": 41122, "s": 41110, "text": "Binary Heap" }, { "code": null, "e": 41153, "s": 41122, "text": "Huffman Coding | Greedy Algo-3" }, { "code": null, "e": 41197, "s": 41153, "text": "k largest(or smallest) elements in an array" } ]
ArrayList trimToSize() in Java with example - GeeksforGeeks
26 Nov, 2018 The trimToSize() method of ArrayList in Java trims the capacity of an ArrayList instance to be the list’s current size. This method is used to trim an ArrayList instance to the number of elements it contains. Syntax: trimToSize() Parameter: It does not accepts any parameter. Return Value: It does not returns any value. It trims the capacity of this ArrayList instance to the number of the element it contains. Errors and Exceptions: It does not have any errors and exceptions. Below program illustrate the trimTosize() method: // Java code to demonstrate the working of// trimTosize() method in ArrayList // for ArrayList functionsimport java.util.ArrayList; public class GFG { public static void main(String[] args) { // creating an Empty Integer ArrayList ArrayList<Integer> arr = new ArrayList<Integer>(9); // using add(), add 5 values arr.add(2); arr.add(4); arr.add(5); arr.add(6); arr.add(11); // trims the size to the number of elements arr.trimToSize(); System.out.println("The List elements are:"); // prints all the elements for (Integer number : arr) { System.out.println("Number = " + number); } }} Output: The List elements are: Number = 2 Number = 4 Number = 5 Number = 6 Number = 11 Java - util package Java-ArrayList Java-Collections Java-Functions java-list Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. HashMap in Java with Examples Stream In Java Interfaces in Java Initialize an ArrayList in Java Stack Class in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java Multithreading in Java Collections in Java
[ { "code": null, "e": 25752, "s": 25724, "text": "\n26 Nov, 2018" }, { "code": null, "e": 25961, "s": 25752, "text": "The trimToSize() method of ArrayList in Java trims the capacity of an ArrayList instance to be the list’s current size. This method is used to trim an ArrayList instance to the number of elements it contains." }, { "code": null, "e": 25969, "s": 25961, "text": "Syntax:" }, { "code": null, "e": 25982, "s": 25969, "text": "trimToSize()" }, { "code": null, "e": 26028, "s": 25982, "text": "Parameter: It does not accepts any parameter." }, { "code": null, "e": 26164, "s": 26028, "text": "Return Value: It does not returns any value. It trims the capacity of this ArrayList instance to the number of the element it contains." }, { "code": null, "e": 26231, "s": 26164, "text": "Errors and Exceptions: It does not have any errors and exceptions." }, { "code": null, "e": 26281, "s": 26231, "text": "Below program illustrate the trimTosize() method:" }, { "code": "// Java code to demonstrate the working of// trimTosize() method in ArrayList // for ArrayList functionsimport java.util.ArrayList; public class GFG { public static void main(String[] args) { // creating an Empty Integer ArrayList ArrayList<Integer> arr = new ArrayList<Integer>(9); // using add(), add 5 values arr.add(2); arr.add(4); arr.add(5); arr.add(6); arr.add(11); // trims the size to the number of elements arr.trimToSize(); System.out.println(\"The List elements are:\"); // prints all the elements for (Integer number : arr) { System.out.println(\"Number = \" + number); } }}", "e": 26995, "s": 26281, "text": null }, { "code": null, "e": 27003, "s": 26995, "text": "Output:" }, { "code": null, "e": 27083, "s": 27003, "text": "The List elements are:\nNumber = 2\nNumber = 4\nNumber = 5\nNumber = 6\nNumber = 11\n" }, { "code": null, "e": 27103, "s": 27083, "text": "Java - util package" }, { "code": null, "e": 27118, "s": 27103, "text": "Java-ArrayList" }, { "code": null, "e": 27135, "s": 27118, "text": "Java-Collections" }, { "code": null, "e": 27150, "s": 27135, "text": "Java-Functions" }, { "code": null, "e": 27160, "s": 27150, "text": "java-list" }, { "code": null, "e": 27165, "s": 27160, "text": "Java" }, { "code": null, "e": 27170, "s": 27165, "text": "Java" }, { "code": null, "e": 27187, "s": 27170, "text": "Java-Collections" }, { "code": null, "e": 27285, "s": 27187, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27315, "s": 27285, "text": "HashMap in Java with Examples" }, { "code": null, "e": 27330, "s": 27315, "text": "Stream In Java" }, { "code": null, "e": 27349, "s": 27330, "text": "Interfaces in Java" }, { "code": null, "e": 27381, "s": 27349, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 27401, "s": 27381, "text": "Stack Class in Java" }, { "code": null, "e": 27425, "s": 27401, "text": "Singleton Class in Java" }, { "code": null, "e": 27457, "s": 27425, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 27469, "s": 27457, "text": "Set in Java" }, { "code": null, "e": 27492, "s": 27469, "text": "Multithreading in Java" } ]
PHP | xml_parse_into_struct() Function - GeeksforGeeks
07 Aug, 2021 The xml_parse_into_struct() function is an inbuilt function in PHP which is used to parse XML data into an array structure. The XML data are parsed into two parallel array structures, first one is index array that contains pointers to the location of the values in the value array and second one is value array that contains the data from the parsed XML. Syntax: int xml_parse_into_struct( resource $xml_parser, string $data, array $values, array $index ) Parameters: This function accepts four parameters as mentioned above and described below: $xml_parser: It is required parameter. It holds the reference of XML parser. $data: It is required parameter. It holds the string which contains XML data. $values: It is required parameter. It holds the array containing the values of the XML data. $index: It is optional parameter. It specifies an array with pointers to the location of the values in $values. Return Value: This function returns 1 on success and 0 on failure. It is not same as True and False. Note: This function is available for PHP 4.0.0 and newer version. These examples may not work on online IDE. So, try to run it on local server or php hosted servers. gfg.xml file: XML <?xml version="1.0" encoding="utf-8"?><user> <username> user123 </username> <name> firstname lastname </name> <phone> +91-9876543210 </phone> <detail> I am John Doe. Live in Kolkata, India. </detail></user> Program 1: PHP <?php // Create an xml parser$xml_parser = xml_parser_create(); // Opening xml file in file stream$filePointer = fopen("sample.xml", "r"); // Reading XML data from the// specified XML file$xml_data = fread($filePointer, 4096); // Parsing XML data into an// array structurexml_parse_into_struct($xml_parser, $xml_data, $values); // Free to xml parsexml_parser_free($xml_parser); // Display array structured XML dataprint_r($values); // Closing the XML filefclose($filePointer); ?> Output: Array ( [0] => Array ( [tag] => USER [type] => open [level] => 1 [value] => ) [1] => Array ( [tag] => USERNAME [type] => complete [level] => 2 [value] => user123 ) [2] => Array ( [tag] => USER [value] => [type] => cdata [level] => 1 ) [3] => Array ( [tag] => NAME [type] => complete [level] => 2 [value] => firstname lastname ) [4] => Array ( [tag] => USER [value] => [type] => cdata [level] => 1 ) [5] => Array ( [tag] => PHONE [type] => complete [level] => 2 [value] => +91-9876543210 ) [6] => Array ( [tag] => USER [value] => [type] => cdata [level] => 1 ) [7] => Array ( [tag] => DETAIL [type] => complete [level] => 2 [value] => I am John Doe. Live in Kolkata, India. ) [8] => Array ( [tag] => USER [value] => [type] => cdata [level] => 1 ) [9] => Array ( [tag] => USER [type] => close [level] => 1 ) ) geeks.xml file: XML <?xml version="1.0"?><atoms> <atom> <name>Carbon</name> <symbol>C</symbol> <atomic_no>6</atomic_no> </atom> <atom> <name>Hydrogen</name> <symbol>H</symbol> <atomic_no>1</atomic_no> </atom> <atom> <name>Helium</name> <symbol>He</symbol> <atomic_no>2</atomic_no> </atom> <atom> <name>Iron</name> <symbol>Fe</symbol> <atomic_no>26</atomic_no> </atom></atoms> Program 2: PHP <?php class Atom { var $name; // Name of the element var $symbol; // Symbol for the atom var $atomic_no; // Atomic number // Constructor for Atom class function __construct( $aa ) { // Initializing or setting the values // to the field of the Atom class foreach ($aa as $k=>$v) $this->$k = $aa[$k]; }} function read_data($filename) { // Read the XML database of atoms $xml_data = implode("", file($filename)); // Creating an xml parser $xml_parser = xml_parser_create(); xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, 0); xml_parser_set_option($xml_parser, XML_OPTION_SKIP_WHITE, 1); xml_parse_into_struct($xml_parser, $xml_data, $values, $tags); // Free to xml parser xml_parser_free($xml_parser); // Iterating through the structures foreach ($tags as $key=>$val) { if ($key == "atom") { $atom_ranges = $val; // Each contiguous pair of array entries // are the lower and upper range for // each molecule definition for($i = 0; $i < count($atom_ranges); $i += 2) { $offset = $atom_ranges[$i] + 1; $len = $atom_ranges[$i + 1] - $offset; // Parsing atom data $tdb[] = parseAtoms(array_slice($values, $offset, $len)); } } else { continue; } } return $tdb;} // parseAtoms function to parse atomfunction parseAtoms($mvalues) { for ($i = 0; $i < count($mvalues); $i++) { $ato[$mvalues[$i]["tag"]] = $mvalues[$i]["value"]; } return new Atom($ato);} $db = read_data("atoms.xml");echo "Database of atoms objects:\n";print_r($db); ?> Output: Database of atoms objects: Array ( [0] => Atom Object ( [name] => Carbon [symbol] => C [atomic_no] => 6 ) [1] => Atom Object ( [name] => Hydrogen [symbol] => H [atomic_no] => 1 ) [2] => Atom Object ( [name] => Helium [symbol] => He [atomic_no] => 2 ) [3] => Atom Object ( [name] => Iron [symbol] => Fe [atomic_no] => 26 ) ) Reference: https://www.php.net/manual/en/function.xml-parse-into-struct.php anikaseth98 PHP-function PHP-XML PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to fetch data from localserver database and display on HTML table using PHP ? How to create admin login page using PHP? PHP str_replace() Function How to pass form variables from one page to other page in PHP ? Create a drop-down list that options fetched from a MySQL database in PHP Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 26243, "s": 26215, "text": "\n07 Aug, 2021" }, { "code": null, "e": 26598, "s": 26243, "text": "The xml_parse_into_struct() function is an inbuilt function in PHP which is used to parse XML data into an array structure. The XML data are parsed into two parallel array structures, first one is index array that contains pointers to the location of the values in the value array and second one is value array that contains the data from the parsed XML." }, { "code": null, "e": 26607, "s": 26598, "text": "Syntax: " }, { "code": null, "e": 26740, "s": 26607, "text": "int xml_parse_into_struct( resource $xml_parser, string $data,\n array $values, array $index )" }, { "code": null, "e": 26832, "s": 26740, "text": "Parameters: This function accepts four parameters as mentioned above and described below: " }, { "code": null, "e": 26909, "s": 26832, "text": "$xml_parser: It is required parameter. It holds the reference of XML parser." }, { "code": null, "e": 26987, "s": 26909, "text": "$data: It is required parameter. It holds the string which contains XML data." }, { "code": null, "e": 27080, "s": 26987, "text": "$values: It is required parameter. It holds the array containing the values of the XML data." }, { "code": null, "e": 27192, "s": 27080, "text": "$index: It is optional parameter. It specifies an array with pointers to the location of the values in $values." }, { "code": null, "e": 27293, "s": 27192, "text": "Return Value: This function returns 1 on success and 0 on failure. It is not same as True and False." }, { "code": null, "e": 27301, "s": 27293, "text": "Note: " }, { "code": null, "e": 27361, "s": 27301, "text": "This function is available for PHP 4.0.0 and newer version." }, { "code": null, "e": 27461, "s": 27361, "text": "These examples may not work on online IDE. So, try to run it on local server or php hosted servers." }, { "code": null, "e": 27477, "s": 27461, "text": "gfg.xml file: " }, { "code": null, "e": 27481, "s": 27477, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><user> <username> user123 </username> <name> firstname lastname </name> <phone> +91-9876543210 </phone> <detail> I am John Doe. Live in Kolkata, India. </detail></user>", "e": 27700, "s": 27481, "text": null }, { "code": null, "e": 27712, "s": 27700, "text": "Program 1: " }, { "code": null, "e": 27716, "s": 27712, "text": "PHP" }, { "code": "<?php // Create an xml parser$xml_parser = xml_parser_create(); // Opening xml file in file stream$filePointer = fopen(\"sample.xml\", \"r\"); // Reading XML data from the// specified XML file$xml_data = fread($filePointer, 4096); // Parsing XML data into an// array structurexml_parse_into_struct($xml_parser, $xml_data, $values); // Free to xml parsexml_parser_free($xml_parser); // Display array structured XML dataprint_r($values); // Closing the XML filefclose($filePointer); ?>", "e": 28212, "s": 27716, "text": null }, { "code": null, "e": 28221, "s": 28212, "text": "Output: " }, { "code": null, "e": 29710, "s": 28221, "text": "Array\n(\n [0] => Array\n (\n [tag] => USER\n [type] => open\n [level] => 1\n [value] => \n )\n [1] => Array\n (\n [tag] => USERNAME\n [type] => complete\n [level] => 2\n [value] => user123 \n )\n [2] => Array\n (\n [tag] => USER\n [value] => \n [type] => cdata\n [level] => 1\n )\n [3] => Array\n (\n [tag] => NAME\n [type] => complete\n [level] => 2\n [value] => firstname lastname \n )\n [4] => Array\n (\n [tag] => USER\n [value] => \n [type] => cdata\n [level] => 1\n )\n [5] => Array\n (\n [tag] => PHONE\n [type] => complete\n [level] => 2\n [value] => +91-9876543210 \n )\n [6] => Array\n (\n [tag] => USER\n [value] => \n [type] => cdata\n [level] => 1\n )\n [7] => Array\n (\n [tag] => DETAIL\n [type] => complete\n [level] => 2\n [value] => I am John Doe. Live in Kolkata, India. \n )\n [8] => Array\n (\n [tag] => USER\n [value] => \n [type] => cdata\n [level] => 1\n )\n [9] => Array\n (\n [tag] => USER\n [type] => close\n [level] => 1\n )\n)" }, { "code": null, "e": 29727, "s": 29710, "text": "geeks.xml file: " }, { "code": null, "e": 29731, "s": 29727, "text": "XML" }, { "code": "<?xml version=\"1.0\"?><atoms> <atom> <name>Carbon</name> <symbol>C</symbol> <atomic_no>6</atomic_no> </atom> <atom> <name>Hydrogen</name> <symbol>H</symbol> <atomic_no>1</atomic_no> </atom> <atom> <name>Helium</name> <symbol>He</symbol> <atomic_no>2</atomic_no> </atom> <atom> <name>Iron</name> <symbol>Fe</symbol> <atomic_no>26</atomic_no> </atom></atoms>", "e": 30195, "s": 29731, "text": null }, { "code": null, "e": 30207, "s": 30195, "text": "Program 2: " }, { "code": null, "e": 30211, "s": 30207, "text": "PHP" }, { "code": "<?php class Atom { var $name; // Name of the element var $symbol; // Symbol for the atom var $atomic_no; // Atomic number // Constructor for Atom class function __construct( $aa ) { // Initializing or setting the values // to the field of the Atom class foreach ($aa as $k=>$v) $this->$k = $aa[$k]; }} function read_data($filename) { // Read the XML database of atoms $xml_data = implode(\"\", file($filename)); // Creating an xml parser $xml_parser = xml_parser_create(); xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, 0); xml_parser_set_option($xml_parser, XML_OPTION_SKIP_WHITE, 1); xml_parse_into_struct($xml_parser, $xml_data, $values, $tags); // Free to xml parser xml_parser_free($xml_parser); // Iterating through the structures foreach ($tags as $key=>$val) { if ($key == \"atom\") { $atom_ranges = $val; // Each contiguous pair of array entries // are the lower and upper range for // each molecule definition for($i = 0; $i < count($atom_ranges); $i += 2) { $offset = $atom_ranges[$i] + 1; $len = $atom_ranges[$i + 1] - $offset; // Parsing atom data $tdb[] = parseAtoms(array_slice($values, $offset, $len)); } } else { continue; } } return $tdb;} // parseAtoms function to parse atomfunction parseAtoms($mvalues) { for ($i = 0; $i < count($mvalues); $i++) { $ato[$mvalues[$i][\"tag\"]] = $mvalues[$i][\"value\"]; } return new Atom($ato);} $db = read_data(\"atoms.xml\");echo \"Database of atoms objects:\\n\";print_r($db); ?>", "e": 32013, "s": 30211, "text": null }, { "code": null, "e": 32022, "s": 32013, "text": "Output: " }, { "code": null, "e": 32570, "s": 32022, "text": "Database of atoms objects:\nArray\n(\n [0] => Atom Object\n (\n [name] => Carbon\n [symbol] => C\n [atomic_no] => 6\n )\n [1] => Atom Object\n (\n [name] => Hydrogen\n [symbol] => H\n [atomic_no] => 1\n )\n [2] => Atom Object\n (\n [name] => Helium\n [symbol] => He\n [atomic_no] => 2\n )\n [3] => Atom Object\n (\n [name] => Iron\n [symbol] => Fe\n [atomic_no] => 26\n )\n)" }, { "code": null, "e": 32647, "s": 32570, "text": "Reference: https://www.php.net/manual/en/function.xml-parse-into-struct.php " }, { "code": null, "e": 32659, "s": 32647, "text": "anikaseth98" }, { "code": null, "e": 32672, "s": 32659, "text": "PHP-function" }, { "code": null, "e": 32680, "s": 32672, "text": "PHP-XML" }, { "code": null, "e": 32684, "s": 32680, "text": "PHP" }, { "code": null, "e": 32701, "s": 32684, "text": "Web Technologies" }, { "code": null, "e": 32705, "s": 32701, "text": "PHP" }, { "code": null, "e": 32803, "s": 32705, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32885, "s": 32803, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 32927, "s": 32885, "text": "How to create admin login page using PHP?" }, { "code": null, "e": 32954, "s": 32927, "text": "PHP str_replace() Function" }, { "code": null, "e": 33018, "s": 32954, "text": "How to pass form variables from one page to other page in PHP ?" }, { "code": null, "e": 33092, "s": 33018, "text": "Create a drop-down list that options fetched from a MySQL database in PHP" }, { "code": null, "e": 33132, "s": 33092, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 33165, "s": 33132, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 33210, "s": 33165, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 33253, "s": 33210, "text": "How to fetch data from an API in ReactJS ?" } ]
Load Factor and Rehashing - GeeksforGeeks
24 Apr, 2022 Prerequisites: Hashing Introduction and Collision handling by separate chaining For insertion of a key(K) – value(V) pair into a hash map, 2 steps are required: K is converted into a small integer (called its hash code) using a hash function.The hash code is used to find an index (hashCode % arrSize) and the entire linked list at that index(Separate chaining) is first searched for the presence of the K already.If found, it’s value is updated and if not, the K-V pair is stored as a new node in the list. K is converted into a small integer (called its hash code) using a hash function. The hash code is used to find an index (hashCode % arrSize) and the entire linked list at that index(Separate chaining) is first searched for the presence of the K already. If found, it’s value is updated and if not, the K-V pair is stored as a new node in the list. For the first step, time taken depends on the K and the hash function. For example, if the key is a string “abcd”, then it’s hash function may depend on the length of the string. But for very large values of n, the number of entries into the map, length of the keys is almost negligible in comparison to n so hash computation can be considered to take place in constant time, i.e, O(1). For the second step, traversal of the list of K-V pairs present at that index needs to be done. For this, the worst case may be that all the n entries are at the same index. So, time complexity would be O(n). But, enough research has been done to make hash functions uniformly distribute the keys in the array so this almost never happens. So, on an average, if there are n entries and b is the size of the array there would be n/b entries on each index. This value n/b is called the load factor that represents the load that is there on our map. This Load Factor needs to be kept low, so that number of entries at one index is less and so is the complexity almost constant, i.e., O(1). As the name suggests, rehashing means hashing again. Basically, when the load factor increases to more than its pre-defined value (default value of load factor is 0.75), the complexity increases. So to overcome this, the size of the array is increased (doubled) and all the values are hashed again and stored in the new double sized array to maintain a low load factor and low complexity. Why rehashing? Rehashing is done because whenever key value pairs are inserted into the map, the load factor increases, which implies that the time complexity also increases as explained above. This might not give the required time complexity of O(1). Hence, rehash must be done, increasing the size of the bucketArray so as to reduce the load factor and the time complexity. How Rehashing is done? Rehashing can be done as follows: For each addition of a new entry to the map, check the load factor. If it’s greater than its pre-defined value (or default value of 0.75 if not given), then Rehash. For Rehash, make a new array of double the previous size and make it the new bucketarray. Then traverse to each element in the old bucketArray and call the insert() for each so as to insert it into the new larger bucket array. Java Python3 // Java program to implement Rehashing import java.util.ArrayList; class Map<K, V> { class MapNode<K, V> { K key; V value; MapNode<K, V> next; public MapNode(K key, V value) { this.key = key; this.value = value; next = null; } } // The bucket array where // the nodes containing K-V pairs are stored ArrayList<MapNode<K, V> > buckets; // No. of pairs stored - n int size; // Size of the bucketArray - b int numBuckets; // Default loadFactor final double DEFAULT_LOAD_FACTOR = 0.75; public Map() { numBuckets = 5; buckets = new ArrayList<>(numBuckets); for (int i = 0; i < numBuckets; i++) { // Initialising to null buckets.add(null); } System.out.println("HashMap created"); System.out.println("Number of pairs in the Map: " + size); System.out.println("Size of Map: " + numBuckets); System.out.println("Default Load Factor : " + DEFAULT_LOAD_FACTOR + "\n"); } private int getBucketInd(K key) { // Using the inbuilt function from the object class int hashCode = key.hashCode(); // array index = hashCode%numBuckets return (hashCode % numBuckets); } public void insert(K key, V value) { // Getting the index at which it needs to be inserted int bucketInd = getBucketInd(key); // The first node at that index MapNode<K, V> head = buckets.get(bucketInd); // First, loop through all the nodes present at that index // to check if the key already exists while (head != null) { // If already present the value is updated if (head.key.equals(key)) { head.value = value; return; } head = head.next; } // new node with the K and V MapNode<K, V> newElementNode = new MapNode<K, V>(key, value); // The head node at the index head = buckets.get(bucketInd); // the new node is inserted // by making it the head // and it's next is the previous head newElementNode.next = head; buckets.set(bucketInd, newElementNode); System.out.println("Pair(" + key + ", " + value + ") inserted successfully.\n"); // Incrementing size // as new K-V pair is added to the map size++; // Load factor calculated double loadFactor = (1.0 * size) / numBuckets; System.out.println("Current Load factor = " + loadFactor); // If the load factor is > 0.75, rehashing is done if (loadFactor > DEFAULT_LOAD_FACTOR) { System.out.println(loadFactor + " is greater than " + DEFAULT_LOAD_FACTOR); System.out.println("Therefore Rehashing will be done.\n"); // Rehash rehash(); System.out.println("New Size of Map: " + numBuckets + "\n"); } System.out.println("Number of pairs in the Map: " + size); System.out.println("Size of Map: " + numBuckets + "\n"); } private void rehash() { System.out.println("\n***Rehashing Started***\n"); // The present bucket list is made temp ArrayList<MapNode<K, V> > temp = buckets; // New bucketList of double the old size is created buckets = new ArrayList<MapNode<K, V> >(2 * numBuckets); for (int i = 0; i < 2 * numBuckets; i++) { // Initialised to null buckets.add(null); } // Now size is made zero // and we loop through all the nodes in the original bucket list(temp) // and insert it into the new list size = 0; numBuckets *= 2; for (int i = 0; i < temp.size(); i++) { // head of the chain at that index MapNode<K, V> head = temp.get(i); while (head != null) { K key = head.key; V val = head.value; // calling the insert function for each node in temp // as the new list is now the bucketArray insert(key, val); head = head.next; } } System.out.println("\n***Rehashing Ended***\n"); } public void printMap() { // The present bucket list is made temp ArrayList<MapNode<K, V> > temp = buckets; System.out.println("Current HashMap:"); // loop through all the nodes and print them for (int i = 0; i < temp.size(); i++) { // head of the chain at that index MapNode<K, V> head = temp.get(i); while (head != null) { System.out.println("key = " + head.key + ", val = " + head.value); head = head.next; } } System.out.println(); } //Function to get an element from Map public V getValue(K key){ //Get actual index of the key int actualIndex = getBucketInd(key); MapNode<K,V> temp = buckets.get(actualIndex); //Search for key in list while(temp != null){ if(temp.key == key){ return temp.value; } temp = temp.next; } return null; }} public class GFG { public static void main(String[] args) { // Creating the Map Map<Integer, String> map = new Map<Integer, String>(); // Inserting elements map.insert(1, "Geeks"); map.printMap(); map.insert(2, "forGeeks"); map.printMap(); map.insert(3, "A"); map.printMap(); map.insert(4, "Computer"); map.printMap(); map.insert(5, "Portal"); map.printMap(); //Get element from Map int key = 4; String value = map.getValue(key); System.out.println("Value at key "+ key +" is: "+ value); }} # Python3 program to implement Rehashing class Map: class MapNode: def __init__(self,key,value): self.key=key self.value=value self.next=None # The bucket array where # the nodes containing K-V pairs are stored buckets=list() # No. of pairs stored - n size=0 # Size of the bucketArray - b numBuckets=0 # Default loadFactor DEFAULT_LOAD_FACTOR = 0.75 def __init__(self): Map.numBuckets = 5 Map.buckets = [None]*Map.numBuckets print("HashMap created") print("Number of pairs in the Map: " + str(Map.size)) print("Size of Map: " + str(Map.numBuckets)) print("Default Load Factor : " + str(Map.DEFAULT_LOAD_FACTOR) + "\n") def getBucketInd(self,key): # Using the inbuilt function from the object class hashCode = hash(key) # array index = hashCode%numBuckets return (hashCode % Map.numBuckets) def insert(self,key,value): # Getting the index at which it needs to be inserted bucketInd = self.getBucketInd(key) # The first node at that index head = Map.buckets[bucketInd] # First, loop through all the nodes present at that index # to check if the key already exists while (head != None): # If already present the value is updated if (head.key==key): head.value = value return head = head.next # new node with the K and V newElementNode = Map.MapNode(key, value) # The head node at the index head = Map.buckets[bucketInd] # the new node is inserted # by making it the head # and it's next is the previous head newElementNode.next = head Map.buckets[bucketInd]= newElementNode print("Pair(\" {} \", \" {} \") inserted successfully.".format(key,value)) # Incrementing size # as new K-V pair is added to the map Map.size+=1 # Load factor calculated loadFactor = (1* Map.size) / Map.numBuckets print("Current Load factor = " + str(loadFactor)) # If the load factor is > 0.75, rehashing is done if (loadFactor > Map.DEFAULT_LOAD_FACTOR): print(str(loadFactor) + " is greater than " + str(Map.DEFAULT_LOAD_FACTOR)) print("Therefore Rehashing will be done.") # Rehash self.rehash() print("New Size of Map: " + str(Map.numBuckets)) print("Number of pairs in the Map: " + str(Map.size)) print("Size of Map: " + str(Map.numBuckets)) def rehash(self): print("\n***Rehashing Started***\n") # The present bucket list is made temp temp = Map.buckets # New bucketList of double the old size is created buckets =(2 * Map.numBuckets) for i in range(2 * Map.numBuckets): # Initialised to null Map.buckets.append(None) # Now size is made zero # and we loop through all the nodes in the original bucket list(temp) # and insert it into the new list Map.size = 0 Map.numBuckets *= 2 for i in range(len(temp)): # head of the chain at that index head = temp[i] while (head != None): key = head.key val = head.value # calling the insert function for each node in temp # as the new list is now the bucketArray self.insert(key, val) head = head.next print("\n***Rehashing Ended***") def printMap(self): # The present bucket list is made temp temp = Map.buckets print("Current HashMap:") # loop through all the nodes and print them for i in range(len(temp)): # head of the chain at that index head = temp[i] while (head != None): print("key = \" {} \", val = {}" .format(head.key,head.value)) head = head.next print() if __name__ == '__main__': # Creating the Map map = Map() # Inserting elements map.insert(1, "Geeks") map.printMap() map.insert(2, "forGeeks") map.printMap() map.insert(3, "A") map.printMap() map.insert(4, "Computer") map.printMap() map.insert(5, "Portal") map.printMap() # This code is contributed by Amartya Ghosh HashMap created Number of pairs in the Map: 0 Size of Map: 5 Default Load Factor : 0.75 Pair(1, Geeks) inserted successfully. Current Load factor = 0.2 Number of pairs in the Map: 1 Size of Map: 5 Current HashMap: key = 1, val = Geeks Pair(2, forGeeks) inserted successfully. Current Load factor = 0.4 Number of pairs in the Map: 2 Size of Map: 5 Current HashMap: key = 1, val = Geeks key = 2, val = forGeeks Pair(3, A) inserted successfully. Current Load factor = 0.6 Number of pairs in the Map: 3 Size of Map: 5 Current HashMap: key = 1, val = Geeks key = 2, val = forGeeks key = 3, val = A Pair(4, Computer) inserted successfully. Current Load factor = 0.8 0.8 is greater than 0.75 Therefore Rehashing will be done. ***Rehashing Started*** Pair(1, Geeks) inserted successfully. Current Load factor = 0.1 Number of pairs in the Map: 1 Size of Map: 10 Pair(2, forGeeks) inserted successfully. Current Load factor = 0.2 Number of pairs in the Map: 2 Size of Map: 10 Pair(3, A) inserted successfully. Current Load factor = 0.3 Number of pairs in the Map: 3 Size of Map: 10 Pair(4, Computer) inserted successfully. Current Load factor = 0.4 Number of pairs in the Map: 4 Size of Map: 10 ***Rehashing Ended*** New Size of Map: 10 Number of pairs in the Map: 4 Size of Map: 10 Current HashMap: key = 1, val = Geeks key = 2, val = forGeeks key = 3, val = A key = 4, val = Computer Pair(5, Portal) inserted successfully. Current Load factor = 0.5 Number of pairs in the Map: 5 Size of Map: 10 Current HashMap: key = 1, val = Geeks key = 2, val = forGeeks key = 3, val = A key = 4, val = Computer key = 5, val = Portal amartyaghoshgfg kushalgandhi2601 Hash Java - util package Data Structures Hash Data Structures Hash Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar How to Start Learning DSA? Hash Map in Python Introduction to Tree Data Structure Time complexities of different data structures Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Internal Working of HashMap in Java Count pairs with given sum Hashing | Set 1 (Introduction) Sort string of characters
[ { "code": null, "e": 26057, "s": 26029, "text": "\n24 Apr, 2022" }, { "code": null, "e": 26138, "s": 26057, "text": "Prerequisites: Hashing Introduction and Collision handling by separate chaining " }, { "code": null, "e": 26221, "s": 26138, "text": "For insertion of a key(K) – value(V) pair into a hash map, 2 steps are required: " }, { "code": null, "e": 26568, "s": 26221, "text": "K is converted into a small integer (called its hash code) using a hash function.The hash code is used to find an index (hashCode % arrSize) and the entire linked list at that index(Separate chaining) is first searched for the presence of the K already.If found, it’s value is updated and if not, the K-V pair is stored as a new node in the list." }, { "code": null, "e": 26650, "s": 26568, "text": "K is converted into a small integer (called its hash code) using a hash function." }, { "code": null, "e": 26823, "s": 26650, "text": "The hash code is used to find an index (hashCode % arrSize) and the entire linked list at that index(Separate chaining) is first searched for the presence of the K already." }, { "code": null, "e": 26917, "s": 26823, "text": "If found, it’s value is updated and if not, the K-V pair is stored as a new node in the list." }, { "code": null, "e": 27308, "s": 26921, "text": "For the first step, time taken depends on the K and the hash function. For example, if the key is a string “abcd”, then it’s hash function may depend on the length of the string. But for very large values of n, the number of entries into the map, length of the keys is almost negligible in comparison to n so hash computation can be considered to take place in constant time, i.e, O(1)." }, { "code": null, "e": 27648, "s": 27308, "text": "For the second step, traversal of the list of K-V pairs present at that index needs to be done. For this, the worst case may be that all the n entries are at the same index. So, time complexity would be O(n). But, enough research has been done to make hash functions uniformly distribute the keys in the array so this almost never happens." }, { "code": null, "e": 27855, "s": 27648, "text": "So, on an average, if there are n entries and b is the size of the array there would be n/b entries on each index. This value n/b is called the load factor that represents the load that is there on our map." }, { "code": null, "e": 27995, "s": 27855, "text": "This Load Factor needs to be kept low, so that number of entries at one index is less and so is the complexity almost constant, i.e., O(1)." }, { "code": null, "e": 28387, "s": 27997, "text": "As the name suggests, rehashing means hashing again. Basically, when the load factor increases to more than its pre-defined value (default value of load factor is 0.75), the complexity increases. So to overcome this, the size of the array is increased (doubled) and all the values are hashed again and stored in the new double sized array to maintain a low load factor and low complexity. " }, { "code": null, "e": 28402, "s": 28387, "text": "Why rehashing?" }, { "code": null, "e": 28764, "s": 28402, "text": "Rehashing is done because whenever key value pairs are inserted into the map, the load factor increases, which implies that the time complexity also increases as explained above. This might not give the required time complexity of O(1). Hence, rehash must be done, increasing the size of the bucketArray so as to reduce the load factor and the time complexity. " }, { "code": null, "e": 28787, "s": 28764, "text": "How Rehashing is done?" }, { "code": null, "e": 28822, "s": 28787, "text": "Rehashing can be done as follows: " }, { "code": null, "e": 28890, "s": 28822, "text": "For each addition of a new entry to the map, check the load factor." }, { "code": null, "e": 28987, "s": 28890, "text": "If it’s greater than its pre-defined value (or default value of 0.75 if not given), then Rehash." }, { "code": null, "e": 29077, "s": 28987, "text": "For Rehash, make a new array of double the previous size and make it the new bucketarray." }, { "code": null, "e": 29214, "s": 29077, "text": "Then traverse to each element in the old bucketArray and call the insert() for each so as to insert it into the new larger bucket array." }, { "code": null, "e": 29223, "s": 29218, "text": "Java" }, { "code": null, "e": 29231, "s": 29223, "text": "Python3" }, { "code": "// Java program to implement Rehashing import java.util.ArrayList; class Map<K, V> { class MapNode<K, V> { K key; V value; MapNode<K, V> next; public MapNode(K key, V value) { this.key = key; this.value = value; next = null; } } // The bucket array where // the nodes containing K-V pairs are stored ArrayList<MapNode<K, V> > buckets; // No. of pairs stored - n int size; // Size of the bucketArray - b int numBuckets; // Default loadFactor final double DEFAULT_LOAD_FACTOR = 0.75; public Map() { numBuckets = 5; buckets = new ArrayList<>(numBuckets); for (int i = 0; i < numBuckets; i++) { // Initialising to null buckets.add(null); } System.out.println(\"HashMap created\"); System.out.println(\"Number of pairs in the Map: \" + size); System.out.println(\"Size of Map: \" + numBuckets); System.out.println(\"Default Load Factor : \" + DEFAULT_LOAD_FACTOR + \"\\n\"); } private int getBucketInd(K key) { // Using the inbuilt function from the object class int hashCode = key.hashCode(); // array index = hashCode%numBuckets return (hashCode % numBuckets); } public void insert(K key, V value) { // Getting the index at which it needs to be inserted int bucketInd = getBucketInd(key); // The first node at that index MapNode<K, V> head = buckets.get(bucketInd); // First, loop through all the nodes present at that index // to check if the key already exists while (head != null) { // If already present the value is updated if (head.key.equals(key)) { head.value = value; return; } head = head.next; } // new node with the K and V MapNode<K, V> newElementNode = new MapNode<K, V>(key, value); // The head node at the index head = buckets.get(bucketInd); // the new node is inserted // by making it the head // and it's next is the previous head newElementNode.next = head; buckets.set(bucketInd, newElementNode); System.out.println(\"Pair(\" + key + \", \" + value + \") inserted successfully.\\n\"); // Incrementing size // as new K-V pair is added to the map size++; // Load factor calculated double loadFactor = (1.0 * size) / numBuckets; System.out.println(\"Current Load factor = \" + loadFactor); // If the load factor is > 0.75, rehashing is done if (loadFactor > DEFAULT_LOAD_FACTOR) { System.out.println(loadFactor + \" is greater than \" + DEFAULT_LOAD_FACTOR); System.out.println(\"Therefore Rehashing will be done.\\n\"); // Rehash rehash(); System.out.println(\"New Size of Map: \" + numBuckets + \"\\n\"); } System.out.println(\"Number of pairs in the Map: \" + size); System.out.println(\"Size of Map: \" + numBuckets + \"\\n\"); } private void rehash() { System.out.println(\"\\n***Rehashing Started***\\n\"); // The present bucket list is made temp ArrayList<MapNode<K, V> > temp = buckets; // New bucketList of double the old size is created buckets = new ArrayList<MapNode<K, V> >(2 * numBuckets); for (int i = 0; i < 2 * numBuckets; i++) { // Initialised to null buckets.add(null); } // Now size is made zero // and we loop through all the nodes in the original bucket list(temp) // and insert it into the new list size = 0; numBuckets *= 2; for (int i = 0; i < temp.size(); i++) { // head of the chain at that index MapNode<K, V> head = temp.get(i); while (head != null) { K key = head.key; V val = head.value; // calling the insert function for each node in temp // as the new list is now the bucketArray insert(key, val); head = head.next; } } System.out.println(\"\\n***Rehashing Ended***\\n\"); } public void printMap() { // The present bucket list is made temp ArrayList<MapNode<K, V> > temp = buckets; System.out.println(\"Current HashMap:\"); // loop through all the nodes and print them for (int i = 0; i < temp.size(); i++) { // head of the chain at that index MapNode<K, V> head = temp.get(i); while (head != null) { System.out.println(\"key = \" + head.key + \", val = \" + head.value); head = head.next; } } System.out.println(); } //Function to get an element from Map public V getValue(K key){ //Get actual index of the key int actualIndex = getBucketInd(key); MapNode<K,V> temp = buckets.get(actualIndex); //Search for key in list while(temp != null){ if(temp.key == key){ return temp.value; } temp = temp.next; } return null; }} public class GFG { public static void main(String[] args) { // Creating the Map Map<Integer, String> map = new Map<Integer, String>(); // Inserting elements map.insert(1, \"Geeks\"); map.printMap(); map.insert(2, \"forGeeks\"); map.printMap(); map.insert(3, \"A\"); map.printMap(); map.insert(4, \"Computer\"); map.printMap(); map.insert(5, \"Portal\"); map.printMap(); //Get element from Map int key = 4; String value = map.getValue(key); System.out.println(\"Value at key \"+ key +\" is: \"+ value); }}", "e": 35110, "s": 29231, "text": null }, { "code": "# Python3 program to implement Rehashing class Map: class MapNode: def __init__(self,key,value): self.key=key self.value=value self.next=None # The bucket array where # the nodes containing K-V pairs are stored buckets=list() # No. of pairs stored - n size=0 # Size of the bucketArray - b numBuckets=0 # Default loadFactor DEFAULT_LOAD_FACTOR = 0.75 def __init__(self): Map.numBuckets = 5 Map.buckets = [None]*Map.numBuckets print(\"HashMap created\") print(\"Number of pairs in the Map: \" + str(Map.size)) print(\"Size of Map: \" + str(Map.numBuckets)) print(\"Default Load Factor : \" + str(Map.DEFAULT_LOAD_FACTOR) + \"\\n\") def getBucketInd(self,key): # Using the inbuilt function from the object class hashCode = hash(key) # array index = hashCode%numBuckets return (hashCode % Map.numBuckets) def insert(self,key,value): # Getting the index at which it needs to be inserted bucketInd = self.getBucketInd(key) # The first node at that index head = Map.buckets[bucketInd] # First, loop through all the nodes present at that index # to check if the key already exists while (head != None): # If already present the value is updated if (head.key==key): head.value = value return head = head.next # new node with the K and V newElementNode = Map.MapNode(key, value) # The head node at the index head = Map.buckets[bucketInd] # the new node is inserted # by making it the head # and it's next is the previous head newElementNode.next = head Map.buckets[bucketInd]= newElementNode print(\"Pair(\\\" {} \\\", \\\" {} \\\") inserted successfully.\".format(key,value)) # Incrementing size # as new K-V pair is added to the map Map.size+=1 # Load factor calculated loadFactor = (1* Map.size) / Map.numBuckets print(\"Current Load factor = \" + str(loadFactor)) # If the load factor is > 0.75, rehashing is done if (loadFactor > Map.DEFAULT_LOAD_FACTOR): print(str(loadFactor) + \" is greater than \" + str(Map.DEFAULT_LOAD_FACTOR)) print(\"Therefore Rehashing will be done.\") # Rehash self.rehash() print(\"New Size of Map: \" + str(Map.numBuckets)) print(\"Number of pairs in the Map: \" + str(Map.size)) print(\"Size of Map: \" + str(Map.numBuckets)) def rehash(self): print(\"\\n***Rehashing Started***\\n\") # The present bucket list is made temp temp = Map.buckets # New bucketList of double the old size is created buckets =(2 * Map.numBuckets) for i in range(2 * Map.numBuckets): # Initialised to null Map.buckets.append(None) # Now size is made zero # and we loop through all the nodes in the original bucket list(temp) # and insert it into the new list Map.size = 0 Map.numBuckets *= 2 for i in range(len(temp)): # head of the chain at that index head = temp[i] while (head != None): key = head.key val = head.value # calling the insert function for each node in temp # as the new list is now the bucketArray self.insert(key, val) head = head.next print(\"\\n***Rehashing Ended***\") def printMap(self): # The present bucket list is made temp temp = Map.buckets print(\"Current HashMap:\") # loop through all the nodes and print them for i in range(len(temp)): # head of the chain at that index head = temp[i] while (head != None): print(\"key = \\\" {} \\\", val = {}\" .format(head.key,head.value)) head = head.next print() if __name__ == '__main__': # Creating the Map map = Map() # Inserting elements map.insert(1, \"Geeks\") map.printMap() map.insert(2, \"forGeeks\") map.printMap() map.insert(3, \"A\") map.printMap() map.insert(4, \"Computer\") map.printMap() map.insert(5, \"Portal\") map.printMap() # This code is contributed by Amartya Ghosh", "e": 39504, "s": 35110, "text": null }, { "code": null, "e": 41145, "s": 39504, "text": "HashMap created\nNumber of pairs in the Map: 0\nSize of Map: 5\nDefault Load Factor : 0.75\n\nPair(1, Geeks) inserted successfully.\n\nCurrent Load factor = 0.2\nNumber of pairs in the Map: 1\nSize of Map: 5\n\nCurrent HashMap:\nkey = 1, val = Geeks\n\nPair(2, forGeeks) inserted successfully.\n\nCurrent Load factor = 0.4\nNumber of pairs in the Map: 2\nSize of Map: 5\n\nCurrent HashMap:\nkey = 1, val = Geeks\nkey = 2, val = forGeeks\n\nPair(3, A) inserted successfully.\n\nCurrent Load factor = 0.6\nNumber of pairs in the Map: 3\nSize of Map: 5\n\nCurrent HashMap:\nkey = 1, val = Geeks\nkey = 2, val = forGeeks\nkey = 3, val = A\n\nPair(4, Computer) inserted successfully.\n\nCurrent Load factor = 0.8\n0.8 is greater than 0.75\nTherefore Rehashing will be done.\n\n\n***Rehashing Started***\n\nPair(1, Geeks) inserted successfully.\n\nCurrent Load factor = 0.1\nNumber of pairs in the Map: 1\nSize of Map: 10\n\nPair(2, forGeeks) inserted successfully.\n\nCurrent Load factor = 0.2\nNumber of pairs in the Map: 2\nSize of Map: 10\n\nPair(3, A) inserted successfully.\n\nCurrent Load factor = 0.3\nNumber of pairs in the Map: 3\nSize of Map: 10\n\nPair(4, Computer) inserted successfully.\n\nCurrent Load factor = 0.4\nNumber of pairs in the Map: 4\nSize of Map: 10\n\n\n***Rehashing Ended***\n\nNew Size of Map: 10\n\nNumber of pairs in the Map: 4\nSize of Map: 10\n\nCurrent HashMap:\nkey = 1, val = Geeks\nkey = 2, val = forGeeks\nkey = 3, val = A\nkey = 4, val = Computer\n\nPair(5, Portal) inserted successfully.\n\nCurrent Load factor = 0.5\nNumber of pairs in the Map: 5\nSize of Map: 10\n\nCurrent HashMap:\nkey = 1, val = Geeks\nkey = 2, val = forGeeks\nkey = 3, val = A\nkey = 4, val = Computer\nkey = 5, val = Portal" }, { "code": null, "e": 41163, "s": 41147, "text": "amartyaghoshgfg" }, { "code": null, "e": 41180, "s": 41163, "text": "kushalgandhi2601" }, { "code": null, "e": 41185, "s": 41180, "text": "Hash" }, { "code": null, "e": 41205, "s": 41185, "text": "Java - util package" }, { "code": null, "e": 41221, "s": 41205, "text": "Data Structures" }, { "code": null, "e": 41226, "s": 41221, "text": "Hash" }, { "code": null, "e": 41242, "s": 41226, "text": "Data Structures" }, { "code": null, "e": 41247, "s": 41242, "text": "Hash" }, { "code": null, "e": 41345, "s": 41247, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41370, "s": 41345, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 41397, "s": 41370, "text": "How to Start Learning DSA?" }, { "code": null, "e": 41416, "s": 41397, "text": "Hash Map in Python" }, { "code": null, "e": 41452, "s": 41416, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 41499, "s": 41452, "text": "Time complexities of different data structures" }, { "code": null, "e": 41584, "s": 41499, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 41620, "s": 41584, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 41647, "s": 41620, "text": "Count pairs with given sum" }, { "code": null, "e": 41678, "s": 41647, "text": "Hashing | Set 1 (Introduction)" } ]
Python | Pandas Series.clip() - GeeksforGeeks
11 Oct, 2018 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Python Series.clip() is used to clip value below and above to passed Least and Max value. This method comes in use when doing operations like Signal processing. As we know there are only two values in Digital signal, either High or Low. Pandas Series.clip() can be used to restrict the value to a Specific Range. Syntax: Series.clip(lower=None, upper=None, axis=None, inplace=False) Parameters:lower: Sets Least value of range. Any values below this are made equal to lower.upper: Sets Max value of range. Any values above this are made equal to upper.axis: 0 or ‘index’ to apply method by rows and 1 or ‘columns’ to apply by columnsinplace: Make changes in the caller series itself. (Overwrite with new values) Return type: Series with updated values To download the data set used in following example, click here.In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below. ExampleIn this example, the .clip() method is called on Age column of data. A minimum value of 22 is passed to lower parameter and 25 to upper parameter. The returned series is then stored in a new column ‘New Age’. Before doing any operations, Null rows were dropped using .dropna() to avoid errors. # importing pandas module import pandas as pd # importing regex moduleimport re # making data frame data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") # removing null values to avoid errors data.dropna(inplace = True) # lower value of rangelower = 22 # upper value of rangeupper = 25 # passing values to new columndata["New Age"]= data["Age"].clip(lower = lower, upper = upper) # displaydata Output:As shown in the output image, the New Age column has least value of 22 and max value of 25. All values are restricted to this range. Values below 22 were made equal to 22 and values above 25 were made equal to 25. Python pandas-series Python pandas-series-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Create a directory in Python Python | Get unique values from a list Python | Pandas dataframe.groupby() Defaultdict in Python
[ { "code": null, "e": 25555, "s": 25527, "text": "\n11 Oct, 2018" }, { "code": null, "e": 25769, "s": 25555, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 26082, "s": 25769, "text": "Python Series.clip() is used to clip value below and above to passed Least and Max value. This method comes in use when doing operations like Signal processing. As we know there are only two values in Digital signal, either High or Low. Pandas Series.clip() can be used to restrict the value to a Specific Range." }, { "code": null, "e": 26152, "s": 26082, "text": "Syntax: Series.clip(lower=None, upper=None, axis=None, inplace=False)" }, { "code": null, "e": 26481, "s": 26152, "text": "Parameters:lower: Sets Least value of range. Any values below this are made equal to lower.upper: Sets Max value of range. Any values above this are made equal to upper.axis: 0 or ‘index’ to apply method by rows and 1 or ‘columns’ to apply by columnsinplace: Make changes in the caller series itself. (Overwrite with new values)" }, { "code": null, "e": 26521, "s": 26481, "text": "Return type: Series with updated values" }, { "code": null, "e": 26731, "s": 26521, "text": "To download the data set used in following example, click here.In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below." }, { "code": null, "e": 27032, "s": 26731, "text": "ExampleIn this example, the .clip() method is called on Age column of data. A minimum value of 22 is passed to lower parameter and 25 to upper parameter. The returned series is then stored in a new column ‘New Age’. Before doing any operations, Null rows were dropped using .dropna() to avoid errors." }, { "code": "# importing pandas module import pandas as pd # importing regex moduleimport re # making data frame data = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") # removing null values to avoid errors data.dropna(inplace = True) # lower value of rangelower = 22 # upper value of rangeupper = 25 # passing values to new columndata[\"New Age\"]= data[\"Age\"].clip(lower = lower, upper = upper) # displaydata", "e": 27468, "s": 27032, "text": null }, { "code": null, "e": 27689, "s": 27468, "text": "Output:As shown in the output image, the New Age column has least value of 22 and max value of 25. All values are restricted to this range. Values below 22 were made equal to 22 and values above 25 were made equal to 25." }, { "code": null, "e": 27710, "s": 27689, "text": "Python pandas-series" }, { "code": null, "e": 27739, "s": 27710, "text": "Python pandas-series-methods" }, { "code": null, "e": 27753, "s": 27739, "text": "Python-pandas" }, { "code": null, "e": 27760, "s": 27753, "text": "Python" }, { "code": null, "e": 27858, "s": 27760, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27890, "s": 27858, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27932, "s": 27890, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27974, "s": 27932, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28030, "s": 27974, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28057, "s": 28030, "text": "Python Classes and Objects" }, { "code": null, "e": 28088, "s": 28057, "text": "Python | os.path.join() method" }, { "code": null, "e": 28117, "s": 28088, "text": "Create a directory in Python" }, { "code": null, "e": 28156, "s": 28117, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28192, "s": 28156, "text": "Python | Pandas dataframe.groupby()" } ]
Decode a string recursively encoded as count followed by substring - GeeksforGeeks
05 Jan, 2022 An encoded string (s) is given, the task is to decode it. The pattern in which the strings are encoded is as follows. <count>[sub_str] ==> The substring 'sub_str' appears count times. Examples: Input : str[] = "1[b]" Output : b Input : str[] = "2[ab]" Output : abab Input : str[] = "2[a2[b]]" Output : abbabb Input : str[] = "3[b2[ca]]" Output : bcacabcacabcaca The idea is to use two stacks, one for integers and another for characters. Now, traverse the string, Whenever we encounter any number, push it into the integer stack and in case of any alphabet (a to z) or open bracket (‘[‘), push it onto the character stack.Whenever any close bracket (‘]’) is encounter pop the character from the character stack until open bracket (‘[‘) is not found in the character stack. Also, pop the top element from the integer stack, say n. Now make a string repeating the popped character n number of time. Now, push all character of the string in the stack. Whenever we encounter any number, push it into the integer stack and in case of any alphabet (a to z) or open bracket (‘[‘), push it onto the character stack. Whenever any close bracket (‘]’) is encounter pop the character from the character stack until open bracket (‘[‘) is not found in the character stack. Also, pop the top element from the integer stack, say n. Now make a string repeating the popped character n number of time. Now, push all character of the string in the stack. Below is the implementation of this approach: C++ Java Python3 C# Javascript // C++ program to decode a string recursively// encoded as count followed substring#include<bits/stdc++.h>using namespace std; // Returns decoded string for 'str'string decode(string str){ stack<int> integerstack; stack<char> stringstack; string temp = "", result = ""; // Traversing the string for (int i = 0; i < str.length(); i++) { int count = 0; // If number, convert it into number // and push it into integerstack. if (str[i] >= '0' && str[i] <='9') { while (str[i] >= '0' && str[i] <= '9') { count = count * 10 + str[i] - '0'; i++; } i--; integerstack.push(count); } // If closing bracket ']', pop element until // '[' opening bracket is not found in the // character stack. else if (str[i] == ']') { temp = ""; count = 0; if (! integerstack.empty()) { count = integerstack.top(); integerstack.pop(); } while (! stringstack.empty() && stringstack.top()!='[' ) { temp = stringstack.top() + temp; stringstack.pop(); } if (! stringstack.empty() && stringstack.top() == '[') stringstack.pop(); // Repeating the popped string 'temo' count // number of times. for (int j = 0; j < count; j++) result = result + temp; // Push it in the character stack. for (int j = 0; j < result.length(); j++) stringstack.push(result[j]); result = ""; } // If '[' opening bracket, push it into character stack. else if (str[i] == '[') { if (str[i-1] >= '0' && str[i-1] <= '9') stringstack.push(str[i]); else { stringstack.push(str[i]); integerstack.push(1); } } else stringstack.push(str[i]); } // Pop all the element, make a string and return. while (! stringstack.empty()) { result = stringstack.top() + result; stringstack.pop(); } return result;} // Driven Programint main(){ string str = "3[b2[ca]]"; cout << decode(str) << endl; return 0;} // Java program to decode a string recursively// encoded as count followed substring import java.util.Stack; class Test{ // Returns decoded string for 'str' static String decode(String str) { Stack<Integer> integerstack = new Stack<>(); Stack<Character> stringstack = new Stack<>(); String temp = "", result = ""; // Traversing the string for (int i = 0; i < str.length(); i++) { int count = 0; // If number, convert it into number // and push it into integerstack. if (Character.isDigit(str.charAt(i))) { while (Character.isDigit(str.charAt(i))) { count = count * 10 + str.charAt(i) - '0'; i++; } i--; integerstack.push(count); } // If closing bracket ']', pop element until // '[' opening bracket is not found in the // character stack. else if (str.charAt(i) == ']') { temp = ""; count = 0; if (!integerstack.isEmpty()) { count = integerstack.peek(); integerstack.pop(); } while (!stringstack.isEmpty() && stringstack.peek()!='[' ) { temp = stringstack.peek() + temp; stringstack.pop(); } if (!stringstack.empty() && stringstack.peek() == '[') stringstack.pop(); // Repeating the popped string 'temo' count // number of times. for (int j = 0; j < count; j++) result = result + temp; // Push it in the character stack. for (int j = 0; j < result.length(); j++) stringstack.push(result.charAt(j)); result = ""; } // If '[' opening bracket, push it into character stack. else if (str.charAt(i) == '[') { if (Character.isDigit(str.charAt(i-1))) stringstack.push(str.charAt(i)); else { stringstack.push(str.charAt(i)); integerstack.push(1); } } else stringstack.push(str.charAt(i)); } // Pop all the element, make a string and return. while (!stringstack.isEmpty()) { result = stringstack.peek() + result; stringstack.pop(); } return result; } // Driver method public static void main(String args[]) { String str = "3[b2[ca]]"; System.out.println(decode(str)); }} # Python program to decode a string recursively# encoded as count followed substring # Returns decoded string for 'str'def decode(Str): integerstack = [] stringstack = [] temp = "" result = "" i = 0 # Traversing the string while i < len(Str): count = 0 # If number, convert it into number # and push it into integerstack. if (Str[i] >= '0' and Str[i] <='9'): while (Str[i] >= '0' and Str[i] <= '9'): count = count * 10 + ord(Str[i]) - ord('0') i += 1 i -= 1 integerstack.append(count) # If closing bracket ']', pop element until # '[' opening bracket is not found in the # character stack. elif (Str[i] == ']'): temp = "" count = 0 if (len(integerstack) != 0): count = integerstack[-1] integerstack.pop() while (len(stringstack) != 0 and stringstack[-1] !='[' ): temp = stringstack[-1] + temp stringstack.pop() if (len(stringstack) != 0 and stringstack[-1] == '['): stringstack.pop() # Repeating the popped string 'temo' count # number of times. for j in range(count): result = result + temp # Push it in the character stack. for j in range(len(result)): stringstack.append(result[j]) result = "" # If '[' opening bracket, push it into character stack. elif (Str[i] == '['): if (Str[i-1] >= '0' and Str[i-1] <= '9'): stringstack.append(Str[i]) else: stringstack.append(Str[i]) integerstack.append(1) else: stringstack.append(Str[i]) i += 1 # Pop all the element, make a string and return. while len(stringstack) != 0: result = stringstack[-1] + result stringstack.pop() return result # Driven codeif __name__ == '__main__': Str = "3[b2[ca]]" print(decode(Str)) # This code is contributed by PranchalK. // C# program to decode a string recursively// encoded as count followed substringusing System;using System.Collections.Generic; class GFG{// Returns decoded string for 'str'public static string decode(string str){ Stack<int> integerstack = new Stack<int>(); Stack<char> stringstack = new Stack<char>(); string temp = "", result = ""; // Traversing the string for (int i = 0; i < str.Length; i++) { int count = 0; // If number, convert it into number // and push it into integerstack. if (char.IsDigit(str[i])) { while (char.IsDigit(str[i])) { count = count * 10 + str[i] - '0'; i++; } i--; integerstack.Push(count); } // If closing bracket ']', pop element // until '[' opening bracket is not found // in the character stack. else if (str[i] == ']') { temp = ""; count = 0; if (integerstack.Count > 0) { count = integerstack.Peek(); integerstack.Pop(); } while (stringstack.Count > 0 && stringstack.Peek() != '[') { temp = stringstack.Peek() + temp; stringstack.Pop(); } if (stringstack.Count > 0 && stringstack.Peek() == '[') { stringstack.Pop(); } // Repeating the popped string 'temo' // count number of times. for (int j = 0; j < count; j++) { result = result + temp; } // Push it in the character stack. for (int j = 0; j < result.Length; j++) { stringstack.Push(result[j]); } result = ""; } // If '[' opening bracket, push it // into character stack. else if (str[i] == '[') { if (char.IsDigit(str[i - 1])) { stringstack.Push(str[i]); } else { stringstack.Push(str[i]); integerstack.Push(1); } } else { stringstack.Push(str[i]); } } // Pop all the element, make a // string and return. while (stringstack.Count > 0) { result = stringstack.Peek() + result; stringstack.Pop(); } return result;} // Driver Codepublic static void Main(string[] args){ string str = "3[b2[ca]]"; Console.WriteLine(decode(str));}} // This code is contributed by Shrikant13 <script> // Javascript program to decode a string recursively // encoded as count followed substring // Returns decoded string for 'str' function decode(str) { let integerstack = []; let stringstack = []; let temp = "", result = ""; // Traversing the string for (let i = 0; i < str.length; i++) { let count = 0; // If number, convert it into number // and push it into integerstack. if (str[i] >= '0' && str[i] <='9') { while (str[i] >= '0' && str[i] <='9') { count = count * 10 + str[i] - '0'; i++; } i--; integerstack.push(count); } // If closing bracket ']', pop element // until '[' opening bracket is not found // in the character stack. else if (str[i] == ']') { temp = ""; count = 0; if (integerstack.length > 0) { count = integerstack[integerstack.length - 1]; integerstack.pop(); } while (stringstack.length > 0 && stringstack[stringstack.length - 1] != '[') { temp = stringstack[stringstack.length - 1] + temp; stringstack.pop(); } if (stringstack.length > 0 && stringstack[stringstack.length - 1] == '[') { stringstack.pop(); } // Repeating the popped string 'temo' // count number of times. for (let j = 0; j < count; j++) { result = result + temp; } // Push it in the character stack. for (let j = 0; j < result.length; j++) { stringstack.push(result[j]); } result = ""; } // If '[' opening bracket, push it // into character stack. else if (str[i] == '[') { if (str[i - 1] >= '0' && str[i - 1] <='9') { stringstack.push(str[i]); } else { stringstack.push(str[i]); integerstack.push(1); } } else { stringstack.push(str[i]); } } // Pop all the element, make a // string and return. while (stringstack.length > 0) { result = stringstack[stringstack.length - 1] + result; stringstack.pop(); } return result; } let str = "3[b2[ca]]"; document.write(decode(str)); // This code is contributed by divyeshrabadiy07.</script> bcacabcacabcaca <!—-Illustration of above code for “3[b2[ca]]”> Algorithm: Loop through the characters of the string If the character is not ‘]’, add it to the stack If the character is ‘]’: While top of the stack doesn’t contain ‘[‘, pop the characters from the stack and store it in a string temp(Make sure the string isn’t in reverse order) Pop ‘[‘ from the stack While the top of the stack contains a digit, pop it and store it in dig Concatenate the string temp for dig number of times and store it in a string repeat Add the string repeat to the stack Pop all the characters from the stack(also make the string isn’t in reverse order) Below is the implementation of this approach: C++ Java Python3 C# Javascript #include <iostream>#include <stack>using namespace std; string decodeString(string s){ stack<char> st; for (int i = 0; i < s.length(); i++) { // When ']' is encountered, we need to start // decoding if (s[i] == ']') { string temp; while (!st.empty() && st.top() != '[') { // st.top() + temp makes sure that the // string won't be in reverse order eg, if // the stack contains 12[abc temp = c + "" => // temp = b + "c" => temp = a + "bc" temp = st.top() + temp; st.pop(); } // remove the '[' from the stack st.pop(); string num; // remove the digits from the stack while (!st.empty() && isdigit(st.top())) { num = st.top() + num; st.pop(); } int number = stoi(num); string repeat; for (int j = 0; j < number; j++) repeat += temp; for (char c : repeat) st.push(c); } // if s[i] is not ']', simply push s[i] to the stack else st.push(s[i]); } string res; while (!st.empty()) { res = st.top() + res; st.pop(); } return res;}// driver codeint main(){ string str = "3[b2[ca]]"; cout << decodeString(str); return 0;} import java.util.*;public class Main{ static String decodeString(String s) { Vector<Character> st = new Vector<Character>(); for(int i = 0; i < s.length(); i++) { // When ']' is encountered, we need to // start decoding if (s.charAt(i) == ']') { String temp = ""; while (st.size() > 0 && st.get(st.size() - 1) != '[') { // st.top() + temp makes sure that the // string won't be in reverse order eg, if // the stack contains 12[abc temp = c + "" => // temp = b + "c" => temp = a + "bc" temp = st.get(st.size() - 1) + temp; st.remove(st.size() - 1); } // Remove the '[' from the stack st.remove(st.size() - 1); String num = ""; // Remove the digits from the stack while (st.size() > 0 && st.get(st.size() - 1) >= 48 && st.get(st.size() - 1) <= 57) { num = st.get(st.size() - 1) + num; st.remove(st.size() - 1); } int number = Integer.parseInt(num); String repeat = ""; for(int j = 0; j < number; j++) repeat += temp; for(int c = 0; c < repeat.length(); c++) st.add(repeat.charAt(c)); } // If s[i] is not ']', simply push // s[i] to the stack else st.add(s.charAt(i)); } String res = ""; while (st.size() > 0) { res = st.get(st.size() - 1) + res; st.remove(st.size() - 1); } return res; } public static void main(String[] args) { String str = "3[b2[ca]]"; System.out.print(decodeString(str)); }} // This code is contributed by suresh07. def decodeString(s): st = [] for i in range(len(s)): # When ']' is encountered, we need to start decoding if s[i] == ']': temp = "" while len(st) > 0 and st[-1] != '[': # st.top() + temp makes sure that the # string won't be in reverse order eg, if # the stack contains 12[abc temp = c + "" => # temp = b + "c" => temp = a + "bc" temp = st[-1] + temp st.pop() # remove the '[' from the stack st.pop() num = "" # remove the digits from the stack while len(st) > 0 and ord(st[-1]) >= 48 and ord(st[-1]) <= 57: num = st[-1] + num st.pop() number = int(num) repeat = "" for j in range(number): repeat += temp for c in range(len(repeat)): st.append(repeat) # if s[i] is not ']', simply push s[i] to the stack else: st.append(s[i]) res = "bcacabcacabcaca" while len(st) < 0: res = st[-1] + res st.pop() return res Str = "3[b2[ca]]"print(decodeString(Str)) # This code is contributed by mukesh07. using System;using System.Collections.Generic; class GFG{ static string decodeString(string s){ List<char> st = new List<char>(); for(int i = 0; i < s.Length; i++) { // When ']' is encountered, we need to // start decoding if (s[i] == ']') { string temp = ""; while (st.Count > 0 && st[st.Count - 1] != '[') { // st.top() + temp makes sure that the // string won't be in reverse order eg, if // the stack contains 12[abc temp = c + "" => // temp = b + "c" => temp = a + "bc" temp = st[st.Count - 1] + temp; st.RemoveAt(st.Count - 1); } // Remove the '[' from the stack st.RemoveAt(st.Count - 1); string num = ""; // Remove the digits from the stack while (st.Count > 0 && st[st.Count - 1] >= 48 && st[st.Count - 1] <= 57) { num = st[st.Count - 1] + num; st.RemoveAt(st.Count - 1); } int number = int.Parse(num); string repeat = ""; for(int j = 0; j < number; j++) repeat += temp; foreach(char c in repeat) st.Add(c); } // If s[i] is not ']', simply push // s[i] to the stack else st.Add(s[i]); } string res = ""; while (st.Count > 0) { res = st[st.Count - 1] + res; st.RemoveAt(st.Count - 1); } return res;} // Driver codestatic void Main(){ string str = "3[b2[ca]]"; Console.Write(decodeString(str));}} // This code is contributed by decode2207 <script> function decodeString(s) { let st = []; for (let i = 0; i < s.length; i++) { // When ']' is encountered, we need to start // decoding if (s[i] == ']') { let temp = ""; while (st.length > 0 && st[st.length - 1] != '[') { // st.top() + temp makes sure that the // string won't be in reverse order eg, if // the stack contains 12[abc temp = c + "" => // temp = b + "c" => temp = a + "bc" temp = st[st.length - 1] + temp; st.pop(); } // remove the '[' from the stack st.pop(); let num = ""; // remove the digits from the stack while (st.length > 0 && st[st.length - 1].charCodeAt() >= 48 && st[st.length - 1].charCodeAt() <= 57) { num = st[st.length - 1] + num; st.pop(); } let number = parseInt(num); let repeat = ""; for (let j = 0; j < number; j++) repeat += temp; for (let c = 0; c < repeat.length; c++) st.push(repeat); } // if s[i] is not ']', simply push s[i] to the stack else st.push(s[i]); } let res = ""; while (st.length > 0) { res = st[st.length - 1] + res; st.pop(); } return res; } let str = "3[b2[ca]]"; document.write(decodeString(str)); // This code is contributed by divyesh072019.</script> bcacabcacabcaca This article is contributed by Anuj Chauhan and Gobinath A L. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. shrikanth13 PranchalKatiyar Vipul Mehra divyeshrabadiya07 surindertarika1234 surinderdawra388 gobial divyesh072019 mukesh07 decode2207 suresh07 Facebook Recursion Stack Strings Facebook Strings Recursion Stack Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Backtracking | Introduction Print all possible combinations of r elements in a given array of size n Recursive Practice Problems with Solutions Write a program to reverse digits of a number Print all subsequences of a string Stack Data Structure (Introduction and Program) Stack Class in Java Stack in Python Check for Balanced Brackets in an expression (well-formedness) using Stack Stack | Set 2 (Infix to Postfix)
[ { "code": null, "e": 26457, "s": 26429, "text": "\n05 Jan, 2022" }, { "code": null, "e": 26576, "s": 26457, "text": "An encoded string (s) is given, the task is to decode it. The pattern in which the strings are encoded is as follows. " }, { "code": null, "e": 26665, "s": 26576, "text": "<count>[sub_str] ==> The substring 'sub_str' \n appears count times." }, { "code": null, "e": 26677, "s": 26665, "text": "Examples: " }, { "code": null, "e": 26848, "s": 26677, "text": "Input : str[] = \"1[b]\"\nOutput : b\n\nInput : str[] = \"2[ab]\"\nOutput : abab\n\nInput : str[] = \"2[a2[b]]\"\nOutput : abbabb\n\nInput : str[] = \"3[b2[ca]]\"\nOutput : bcacabcacabcaca" }, { "code": null, "e": 26951, "s": 26848, "text": "The idea is to use two stacks, one for integers and another for characters. Now, traverse the string, " }, { "code": null, "e": 27436, "s": 26951, "text": "Whenever we encounter any number, push it into the integer stack and in case of any alphabet (a to z) or open bracket (‘[‘), push it onto the character stack.Whenever any close bracket (‘]’) is encounter pop the character from the character stack until open bracket (‘[‘) is not found in the character stack. Also, pop the top element from the integer stack, say n. Now make a string repeating the popped character n number of time. Now, push all character of the string in the stack." }, { "code": null, "e": 27595, "s": 27436, "text": "Whenever we encounter any number, push it into the integer stack and in case of any alphabet (a to z) or open bracket (‘[‘), push it onto the character stack." }, { "code": null, "e": 27922, "s": 27595, "text": "Whenever any close bracket (‘]’) is encounter pop the character from the character stack until open bracket (‘[‘) is not found in the character stack. Also, pop the top element from the integer stack, say n. Now make a string repeating the popped character n number of time. Now, push all character of the string in the stack." }, { "code": null, "e": 27970, "s": 27922, "text": "Below is the implementation of this approach: " }, { "code": null, "e": 27974, "s": 27970, "text": "C++" }, { "code": null, "e": 27979, "s": 27974, "text": "Java" }, { "code": null, "e": 27987, "s": 27979, "text": "Python3" }, { "code": null, "e": 27990, "s": 27987, "text": "C#" }, { "code": null, "e": 28001, "s": 27990, "text": "Javascript" }, { "code": "// C++ program to decode a string recursively// encoded as count followed substring#include<bits/stdc++.h>using namespace std; // Returns decoded string for 'str'string decode(string str){ stack<int> integerstack; stack<char> stringstack; string temp = \"\", result = \"\"; // Traversing the string for (int i = 0; i < str.length(); i++) { int count = 0; // If number, convert it into number // and push it into integerstack. if (str[i] >= '0' && str[i] <='9') { while (str[i] >= '0' && str[i] <= '9') { count = count * 10 + str[i] - '0'; i++; } i--; integerstack.push(count); } // If closing bracket ']', pop element until // '[' opening bracket is not found in the // character stack. else if (str[i] == ']') { temp = \"\"; count = 0; if (! integerstack.empty()) { count = integerstack.top(); integerstack.pop(); } while (! stringstack.empty() && stringstack.top()!='[' ) { temp = stringstack.top() + temp; stringstack.pop(); } if (! stringstack.empty() && stringstack.top() == '[') stringstack.pop(); // Repeating the popped string 'temo' count // number of times. for (int j = 0; j < count; j++) result = result + temp; // Push it in the character stack. for (int j = 0; j < result.length(); j++) stringstack.push(result[j]); result = \"\"; } // If '[' opening bracket, push it into character stack. else if (str[i] == '[') { if (str[i-1] >= '0' && str[i-1] <= '9') stringstack.push(str[i]); else { stringstack.push(str[i]); integerstack.push(1); } } else stringstack.push(str[i]); } // Pop all the element, make a string and return. while (! stringstack.empty()) { result = stringstack.top() + result; stringstack.pop(); } return result;} // Driven Programint main(){ string str = \"3[b2[ca]]\"; cout << decode(str) << endl; return 0;}", "e": 30380, "s": 28001, "text": null }, { "code": "// Java program to decode a string recursively// encoded as count followed substring import java.util.Stack; class Test{ // Returns decoded string for 'str' static String decode(String str) { Stack<Integer> integerstack = new Stack<>(); Stack<Character> stringstack = new Stack<>(); String temp = \"\", result = \"\"; // Traversing the string for (int i = 0; i < str.length(); i++) { int count = 0; // If number, convert it into number // and push it into integerstack. if (Character.isDigit(str.charAt(i))) { while (Character.isDigit(str.charAt(i))) { count = count * 10 + str.charAt(i) - '0'; i++; } i--; integerstack.push(count); } // If closing bracket ']', pop element until // '[' opening bracket is not found in the // character stack. else if (str.charAt(i) == ']') { temp = \"\"; count = 0; if (!integerstack.isEmpty()) { count = integerstack.peek(); integerstack.pop(); } while (!stringstack.isEmpty() && stringstack.peek()!='[' ) { temp = stringstack.peek() + temp; stringstack.pop(); } if (!stringstack.empty() && stringstack.peek() == '[') stringstack.pop(); // Repeating the popped string 'temo' count // number of times. for (int j = 0; j < count; j++) result = result + temp; // Push it in the character stack. for (int j = 0; j < result.length(); j++) stringstack.push(result.charAt(j)); result = \"\"; } // If '[' opening bracket, push it into character stack. else if (str.charAt(i) == '[') { if (Character.isDigit(str.charAt(i-1))) stringstack.push(str.charAt(i)); else { stringstack.push(str.charAt(i)); integerstack.push(1); } } else stringstack.push(str.charAt(i)); } // Pop all the element, make a string and return. while (!stringstack.isEmpty()) { result = stringstack.peek() + result; stringstack.pop(); } return result; } // Driver method public static void main(String args[]) { String str = \"3[b2[ca]]\"; System.out.println(decode(str)); }}", "e": 33267, "s": 30380, "text": null }, { "code": "# Python program to decode a string recursively# encoded as count followed substring # Returns decoded string for 'str'def decode(Str): integerstack = [] stringstack = [] temp = \"\" result = \"\" i = 0 # Traversing the string while i < len(Str): count = 0 # If number, convert it into number # and push it into integerstack. if (Str[i] >= '0' and Str[i] <='9'): while (Str[i] >= '0' and Str[i] <= '9'): count = count * 10 + ord(Str[i]) - ord('0') i += 1 i -= 1 integerstack.append(count) # If closing bracket ']', pop element until # '[' opening bracket is not found in the # character stack. elif (Str[i] == ']'): temp = \"\" count = 0 if (len(integerstack) != 0): count = integerstack[-1] integerstack.pop() while (len(stringstack) != 0 and stringstack[-1] !='[' ): temp = stringstack[-1] + temp stringstack.pop() if (len(stringstack) != 0 and stringstack[-1] == '['): stringstack.pop() # Repeating the popped string 'temo' count # number of times. for j in range(count): result = result + temp # Push it in the character stack. for j in range(len(result)): stringstack.append(result[j]) result = \"\" # If '[' opening bracket, push it into character stack. elif (Str[i] == '['): if (Str[i-1] >= '0' and Str[i-1] <= '9'): stringstack.append(Str[i]) else: stringstack.append(Str[i]) integerstack.append(1) else: stringstack.append(Str[i]) i += 1 # Pop all the element, make a string and return. while len(stringstack) != 0: result = stringstack[-1] + result stringstack.pop() return result # Driven codeif __name__ == '__main__': Str = \"3[b2[ca]]\" print(decode(Str)) # This code is contributed by PranchalK.", "e": 35396, "s": 33267, "text": null }, { "code": "// C# program to decode a string recursively// encoded as count followed substringusing System;using System.Collections.Generic; class GFG{// Returns decoded string for 'str'public static string decode(string str){ Stack<int> integerstack = new Stack<int>(); Stack<char> stringstack = new Stack<char>(); string temp = \"\", result = \"\"; // Traversing the string for (int i = 0; i < str.Length; i++) { int count = 0; // If number, convert it into number // and push it into integerstack. if (char.IsDigit(str[i])) { while (char.IsDigit(str[i])) { count = count * 10 + str[i] - '0'; i++; } i--; integerstack.Push(count); } // If closing bracket ']', pop element // until '[' opening bracket is not found // in the character stack. else if (str[i] == ']') { temp = \"\"; count = 0; if (integerstack.Count > 0) { count = integerstack.Peek(); integerstack.Pop(); } while (stringstack.Count > 0 && stringstack.Peek() != '[') { temp = stringstack.Peek() + temp; stringstack.Pop(); } if (stringstack.Count > 0 && stringstack.Peek() == '[') { stringstack.Pop(); } // Repeating the popped string 'temo' // count number of times. for (int j = 0; j < count; j++) { result = result + temp; } // Push it in the character stack. for (int j = 0; j < result.Length; j++) { stringstack.Push(result[j]); } result = \"\"; } // If '[' opening bracket, push it // into character stack. else if (str[i] == '[') { if (char.IsDigit(str[i - 1])) { stringstack.Push(str[i]); } else { stringstack.Push(str[i]); integerstack.Push(1); } } else { stringstack.Push(str[i]); } } // Pop all the element, make a // string and return. while (stringstack.Count > 0) { result = stringstack.Peek() + result; stringstack.Pop(); } return result;} // Driver Codepublic static void Main(string[] args){ string str = \"3[b2[ca]]\"; Console.WriteLine(decode(str));}} // This code is contributed by Shrikant13", "e": 38042, "s": 35396, "text": null }, { "code": "<script> // Javascript program to decode a string recursively // encoded as count followed substring // Returns decoded string for 'str' function decode(str) { let integerstack = []; let stringstack = []; let temp = \"\", result = \"\"; // Traversing the string for (let i = 0; i < str.length; i++) { let count = 0; // If number, convert it into number // and push it into integerstack. if (str[i] >= '0' && str[i] <='9') { while (str[i] >= '0' && str[i] <='9') { count = count * 10 + str[i] - '0'; i++; } i--; integerstack.push(count); } // If closing bracket ']', pop element // until '[' opening bracket is not found // in the character stack. else if (str[i] == ']') { temp = \"\"; count = 0; if (integerstack.length > 0) { count = integerstack[integerstack.length - 1]; integerstack.pop(); } while (stringstack.length > 0 && stringstack[stringstack.length - 1] != '[') { temp = stringstack[stringstack.length - 1] + temp; stringstack.pop(); } if (stringstack.length > 0 && stringstack[stringstack.length - 1] == '[') { stringstack.pop(); } // Repeating the popped string 'temo' // count number of times. for (let j = 0; j < count; j++) { result = result + temp; } // Push it in the character stack. for (let j = 0; j < result.length; j++) { stringstack.push(result[j]); } result = \"\"; } // If '[' opening bracket, push it // into character stack. else if (str[i] == '[') { if (str[i - 1] >= '0' && str[i - 1] <='9') { stringstack.push(str[i]); } else { stringstack.push(str[i]); integerstack.push(1); } } else { stringstack.push(str[i]); } } // Pop all the element, make a // string and return. while (stringstack.length > 0) { result = stringstack[stringstack.length - 1] + result; stringstack.pop(); } return result; } let str = \"3[b2[ca]]\"; document.write(decode(str)); // This code is contributed by divyeshrabadiy07.</script>", "e": 41018, "s": 38042, "text": null }, { "code": null, "e": 41034, "s": 41018, "text": "bcacabcacabcaca" }, { "code": null, "e": 41083, "s": 41034, "text": "<!—-Illustration of above code for “3[b2[ca]]”> " }, { "code": null, "e": 41094, "s": 41083, "text": "Algorithm:" }, { "code": null, "e": 41136, "s": 41094, "text": "Loop through the characters of the string" }, { "code": null, "e": 41185, "s": 41136, "text": "If the character is not ‘]’, add it to the stack" }, { "code": null, "e": 41210, "s": 41185, "text": "If the character is ‘]’:" }, { "code": null, "e": 41366, "s": 41210, "text": " While top of the stack doesn’t contain ‘[‘, pop the characters from the stack and store it in a string temp(Make sure the string isn’t in reverse order)" }, { "code": null, "e": 41392, "s": 41366, "text": " Pop ‘[‘ from the stack" }, { "code": null, "e": 41467, "s": 41392, "text": " While the top of the stack contains a digit, pop it and store it in dig" }, { "code": null, "e": 41554, "s": 41467, "text": " Concatenate the string temp for dig number of times and store it in a string repeat" }, { "code": null, "e": 41592, "s": 41554, "text": " Add the string repeat to the stack" }, { "code": null, "e": 41676, "s": 41592, "text": "Pop all the characters from the stack(also make the string isn’t in reverse order) " }, { "code": null, "e": 41723, "s": 41676, "text": "Below is the implementation of this approach: " }, { "code": null, "e": 41727, "s": 41723, "text": "C++" }, { "code": null, "e": 41732, "s": 41727, "text": "Java" }, { "code": null, "e": 41740, "s": 41732, "text": "Python3" }, { "code": null, "e": 41743, "s": 41740, "text": "C#" }, { "code": null, "e": 41754, "s": 41743, "text": "Javascript" }, { "code": "#include <iostream>#include <stack>using namespace std; string decodeString(string s){ stack<char> st; for (int i = 0; i < s.length(); i++) { // When ']' is encountered, we need to start // decoding if (s[i] == ']') { string temp; while (!st.empty() && st.top() != '[') { // st.top() + temp makes sure that the // string won't be in reverse order eg, if // the stack contains 12[abc temp = c + \"\" => // temp = b + \"c\" => temp = a + \"bc\" temp = st.top() + temp; st.pop(); } // remove the '[' from the stack st.pop(); string num; // remove the digits from the stack while (!st.empty() && isdigit(st.top())) { num = st.top() + num; st.pop(); } int number = stoi(num); string repeat; for (int j = 0; j < number; j++) repeat += temp; for (char c : repeat) st.push(c); } // if s[i] is not ']', simply push s[i] to the stack else st.push(s[i]); } string res; while (!st.empty()) { res = st.top() + res; st.pop(); } return res;}// driver codeint main(){ string str = \"3[b2[ca]]\"; cout << decodeString(str); return 0;}", "e": 43154, "s": 41754, "text": null }, { "code": "import java.util.*;public class Main{ static String decodeString(String s) { Vector<Character> st = new Vector<Character>(); for(int i = 0; i < s.length(); i++) { // When ']' is encountered, we need to // start decoding if (s.charAt(i) == ']') { String temp = \"\"; while (st.size() > 0 && st.get(st.size() - 1) != '[') { // st.top() + temp makes sure that the // string won't be in reverse order eg, if // the stack contains 12[abc temp = c + \"\" => // temp = b + \"c\" => temp = a + \"bc\" temp = st.get(st.size() - 1) + temp; st.remove(st.size() - 1); } // Remove the '[' from the stack st.remove(st.size() - 1); String num = \"\"; // Remove the digits from the stack while (st.size() > 0 && st.get(st.size() - 1) >= 48 && st.get(st.size() - 1) <= 57) { num = st.get(st.size() - 1) + num; st.remove(st.size() - 1); } int number = Integer.parseInt(num); String repeat = \"\"; for(int j = 0; j < number; j++) repeat += temp; for(int c = 0; c < repeat.length(); c++) st.add(repeat.charAt(c)); } // If s[i] is not ']', simply push // s[i] to the stack else st.add(s.charAt(i)); } String res = \"\"; while (st.size() > 0) { res = st.get(st.size() - 1) + res; st.remove(st.size() - 1); } return res; } public static void main(String[] args) { String str = \"3[b2[ca]]\"; System.out.print(decodeString(str)); }} // This code is contributed by suresh07.", "e": 45293, "s": 43154, "text": null }, { "code": "def decodeString(s): st = [] for i in range(len(s)): # When ']' is encountered, we need to start decoding if s[i] == ']': temp = \"\" while len(st) > 0 and st[-1] != '[': # st.top() + temp makes sure that the # string won't be in reverse order eg, if # the stack contains 12[abc temp = c + \"\" => # temp = b + \"c\" => temp = a + \"bc\" temp = st[-1] + temp st.pop() # remove the '[' from the stack st.pop() num = \"\" # remove the digits from the stack while len(st) > 0 and ord(st[-1]) >= 48 and ord(st[-1]) <= 57: num = st[-1] + num st.pop() number = int(num) repeat = \"\" for j in range(number): repeat += temp for c in range(len(repeat)): st.append(repeat) # if s[i] is not ']', simply push s[i] to the stack else: st.append(s[i]) res = \"bcacabcacabcaca\" while len(st) < 0: res = st[-1] + res st.pop() return res Str = \"3[b2[ca]]\"print(decodeString(Str)) # This code is contributed by mukesh07.", "e": 46583, "s": 45293, "text": null }, { "code": "using System;using System.Collections.Generic; class GFG{ static string decodeString(string s){ List<char> st = new List<char>(); for(int i = 0; i < s.Length; i++) { // When ']' is encountered, we need to // start decoding if (s[i] == ']') { string temp = \"\"; while (st.Count > 0 && st[st.Count - 1] != '[') { // st.top() + temp makes sure that the // string won't be in reverse order eg, if // the stack contains 12[abc temp = c + \"\" => // temp = b + \"c\" => temp = a + \"bc\" temp = st[st.Count - 1] + temp; st.RemoveAt(st.Count - 1); } // Remove the '[' from the stack st.RemoveAt(st.Count - 1); string num = \"\"; // Remove the digits from the stack while (st.Count > 0 && st[st.Count - 1] >= 48 && st[st.Count - 1] <= 57) { num = st[st.Count - 1] + num; st.RemoveAt(st.Count - 1); } int number = int.Parse(num); string repeat = \"\"; for(int j = 0; j < number; j++) repeat += temp; foreach(char c in repeat) st.Add(c); } // If s[i] is not ']', simply push // s[i] to the stack else st.Add(s[i]); } string res = \"\"; while (st.Count > 0) { res = st[st.Count - 1] + res; st.RemoveAt(st.Count - 1); } return res;} // Driver codestatic void Main(){ string str = \"3[b2[ca]]\"; Console.Write(decodeString(str));}} // This code is contributed by decode2207", "e": 48390, "s": 46583, "text": null }, { "code": "<script> function decodeString(s) { let st = []; for (let i = 0; i < s.length; i++) { // When ']' is encountered, we need to start // decoding if (s[i] == ']') { let temp = \"\"; while (st.length > 0 && st[st.length - 1] != '[') { // st.top() + temp makes sure that the // string won't be in reverse order eg, if // the stack contains 12[abc temp = c + \"\" => // temp = b + \"c\" => temp = a + \"bc\" temp = st[st.length - 1] + temp; st.pop(); } // remove the '[' from the stack st.pop(); let num = \"\"; // remove the digits from the stack while (st.length > 0 && st[st.length - 1].charCodeAt() >= 48 && st[st.length - 1].charCodeAt() <= 57) { num = st[st.length - 1] + num; st.pop(); } let number = parseInt(num); let repeat = \"\"; for (let j = 0; j < number; j++) repeat += temp; for (let c = 0; c < repeat.length; c++) st.push(repeat); } // if s[i] is not ']', simply push s[i] to the stack else st.push(s[i]); } let res = \"\"; while (st.length > 0) { res = st[st.length - 1] + res; st.pop(); } return res; } let str = \"3[b2[ca]]\"; document.write(decodeString(str)); // This code is contributed by divyesh072019.</script>", "e": 50159, "s": 48390, "text": null }, { "code": null, "e": 50175, "s": 50159, "text": "bcacabcacabcaca" }, { "code": null, "e": 50613, "s": 50175, "text": "This article is contributed by Anuj Chauhan and Gobinath A L. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 50625, "s": 50613, "text": "shrikanth13" }, { "code": null, "e": 50641, "s": 50625, "text": "PranchalKatiyar" }, { "code": null, "e": 50653, "s": 50641, "text": "Vipul Mehra" }, { "code": null, "e": 50671, "s": 50653, "text": "divyeshrabadiya07" }, { "code": null, "e": 50690, "s": 50671, "text": "surindertarika1234" }, { "code": null, "e": 50707, "s": 50690, "text": "surinderdawra388" }, { "code": null, "e": 50714, "s": 50707, "text": "gobial" }, { "code": null, "e": 50728, "s": 50714, "text": "divyesh072019" }, { "code": null, "e": 50737, "s": 50728, "text": "mukesh07" }, { "code": null, "e": 50748, "s": 50737, "text": "decode2207" }, { "code": null, "e": 50757, "s": 50748, "text": "suresh07" }, { "code": null, "e": 50766, "s": 50757, "text": "Facebook" }, { "code": null, "e": 50776, "s": 50766, "text": "Recursion" }, { "code": null, "e": 50782, "s": 50776, "text": "Stack" }, { "code": null, "e": 50790, "s": 50782, "text": "Strings" }, { "code": null, "e": 50799, "s": 50790, "text": "Facebook" }, { "code": null, "e": 50807, "s": 50799, "text": "Strings" }, { "code": null, "e": 50817, "s": 50807, "text": "Recursion" }, { "code": null, "e": 50823, "s": 50817, "text": "Stack" }, { "code": null, "e": 50921, "s": 50823, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 50949, "s": 50921, "text": "Backtracking | Introduction" }, { "code": null, "e": 51022, "s": 50949, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 51065, "s": 51022, "text": "Recursive Practice Problems with Solutions" }, { "code": null, "e": 51111, "s": 51065, "text": "Write a program to reverse digits of a number" }, { "code": null, "e": 51146, "s": 51111, "text": "Print all subsequences of a string" }, { "code": null, "e": 51194, "s": 51146, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 51214, "s": 51194, "text": "Stack Class in Java" }, { "code": null, "e": 51230, "s": 51214, "text": "Stack in Python" }, { "code": null, "e": 51305, "s": 51230, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" } ]
Merge two sorted arrays - GeeksforGeeks
11 Jan, 2022 Given two sorted arrays, the task is to merge them in a sorted manner.Examples: Input: arr1[] = { 1, 3, 4, 5}, arr2[] = {2, 4, 6, 8} Output: arr3[] = {1, 2, 3, 4, 4, 5, 6, 8}Input: arr1[] = { 5, 8, 9}, arr2[] = {4, 7, 8} Output: arr3[] = {4, 5, 7, 8, 8, 9} Method 1 (O(n1 * n2) Time and O(n1+n2) Extra Space) Create an array arr3[] of size n1 + n2.Copy all n1 elements of arr1[] to arr3[]Traverse arr2[] and one by one insert elements (like insertion sort) of arr3[] to arr1[]. This step take O(n1 * n2) time. Create an array arr3[] of size n1 + n2. Copy all n1 elements of arr1[] to arr3[] Traverse arr2[] and one by one insert elements (like insertion sort) of arr3[] to arr1[]. This step take O(n1 * n2) time. We have discussed implementation of above method in Merge two sorted arrays with O(1) extra spaceMethod 2 (O(n1 + n2) Time and O(n1 + n2) Extra Space) The idea is to use Merge function of Merge sort. Create an array arr3[] of size n1 + n2.Simultaneously traverse arr1[] and arr2[]. Pick smaller of current elements in arr1[] and arr2[], copy this smaller element to next position in arr3[] and move ahead in arr3[] and the array whose element is picked.If there are remaining elements in arr1[] or arr2[], copy them also in arr3[]. Create an array arr3[] of size n1 + n2. Simultaneously traverse arr1[] and arr2[]. Pick smaller of current elements in arr1[] and arr2[], copy this smaller element to next position in arr3[] and move ahead in arr3[] and the array whose element is picked. Pick smaller of current elements in arr1[] and arr2[], copy this smaller element to next position in arr3[] and move ahead in arr3[] and the array whose element is picked. If there are remaining elements in arr1[] or arr2[], copy them also in arr3[]. Below image is a dry run of the above approach: Below is the implementation of the above approach: C++ Java Python 3 C# PHP Javascript // C++ program to merge two sorted arrays/#include<iostream>using namespace std; // Merge arr1[0..n1-1] and arr2[0..n2-1] into// arr3[0..n1+n2-1]void mergeArrays(int arr1[], int arr2[], int n1, int n2, int arr3[]){ int i = 0, j = 0, k = 0; // Traverse both array while (i<n1 && j <n2) { // Check if current element of first // array is smaller than current element // of second array. If yes, store first // array element and increment first array // index. Otherwise do same with second array if (arr1[i] < arr2[j]) arr3[k++] = arr1[i++]; else arr3[k++] = arr2[j++]; } // Store remaining elements of first array while (i < n1) arr3[k++] = arr1[i++]; // Store remaining elements of second array while (j < n2) arr3[k++] = arr2[j++];} // Driver codeint main(){ int arr1[] = {1, 3, 5, 7}; int n1 = sizeof(arr1) / sizeof(arr1[0]); int arr2[] = {2, 4, 6, 8}; int n2 = sizeof(arr2) / sizeof(arr2[0]); int arr3[n1+n2]; mergeArrays(arr1, arr2, n1, n2, arr3); cout << "Array after merging" <<endl; for (int i=0; i < n1+n2; i++) cout << arr3[i] << " "; return 0;} // Java program to merge two sorted arraysimport java.util.*;import java.lang.*;import java.io.*; class MergeTwoSorted{ // Merge arr1[0..n1-1] and arr2[0..n2-1] // into arr3[0..n1+n2-1] public static void mergeArrays(int[] arr1, int[] arr2, int n1, int n2, int[] arr3) { int i = 0, j = 0, k = 0; // Traverse both array while (i<n1 && j <n2) { // Check if current element of first // array is smaller than current element // of second array. If yes, store first // array element and increment first array // index. Otherwise do same with second array if (arr1[i] < arr2[j]) arr3[k++] = arr1[i++]; else arr3[k++] = arr2[j++]; } // Store remaining elements of first array while (i < n1) arr3[k++] = arr1[i++]; // Store remaining elements of second array while (j < n2) arr3[k++] = arr2[j++]; } public static void main (String[] args) { int[] arr1 = {1, 3, 5, 7}; int n1 = arr1.length; int[] arr2 = {2, 4, 6, 8}; int n2 = arr2.length; int[] arr3 = new int[n1+n2]; mergeArrays(arr1, arr2, n1, n2, arr3); System.out.println("Array after merging"); for (int i=0; i < n1+n2; i++) System.out.print(arr3[i] + " "); }} /* This code is contributed by Mr. Somesh Awasthi */ # Python program to merge# two sorted arrays # Merge arr1[0..n1-1] and# arr2[0..n2-1] into# arr3[0..n1+n2-1]def mergeArrays(arr1, arr2, n1, n2): arr3 = [None] * (n1 + n2) i = 0 j = 0 k = 0 # Traverse both array while i < n1 and j < n2: # Check if current element # of first array is smaller # than current element of # second array. If yes, # store first array element # and increment first array # index. Otherwise do same # with second array if arr1[i] < arr2[j]: arr3[k] = arr1[i] k = k + 1 i = i + 1 else: arr3[k] = arr2[j] k = k + 1 j = j + 1 # Store remaining elements # of first array while i < n1: arr3[k] = arr1[i]; k = k + 1 i = i + 1 # Store remaining elements # of second array while j < n2: arr3[k] = arr2[j]; k = k + 1 j = j + 1 print("Array after merging") for i in range(n1 + n2): print(str(arr3[i]), end = " ") # Driver codearr1 = [1, 3, 5, 7]n1 = len(arr1) arr2 = [2, 4, 6, 8]n2 = len(arr2)mergeArrays(arr1, arr2, n1, n2); # This code is contributed# by ChitraNayal // C# program to merge// two sorted arraysusing System; class GFG{ // Merge arr1[0..n1-1] and // arr2[0..n2-1] into // arr3[0..n1+n2-1] public static void mergeArrays(int[] arr1, int[] arr2, int n1, int n2, int[] arr3) { int i = 0, j = 0, k = 0; // Traverse both array while (i < n1 && j < n2) { // Check if current element // of first array is smaller // than current element // of second array. If yes, // store first array element // and increment first array // index. Otherwise do same // with second array if (arr1[i] < arr2[j]) arr3[k++] = arr1[i++]; else arr3[k++] = arr2[j++]; } // Store remaining // elements of first array while (i < n1) arr3[k++] = arr1[i++]; // Store remaining elements // of second array while (j < n2) arr3[k++] = arr2[j++]; } // Driver code public static void Main() { int[] arr1 = {1, 3, 5, 7}; int n1 = arr1.Length; int[] arr2 = {2, 4, 6, 8}; int n2 = arr2.Length; int[] arr3 = new int[n1+n2]; mergeArrays(arr1, arr2, n1, n2, arr3); Console.Write("Array after merging\n"); for (int i = 0; i < n1 + n2; i++) Console.Write(arr3[i] + " "); }} // This code is contributed// by ChitraNayal <?php// PHP program to merge// two sorted arrays // Merge $arr1[0..$n1-1] and// $arr2[0..$n2-1] into// $arr3[0..$n1+$n2-1]function mergeArrays(&$arr1, &$arr2, $n1, $n2, &$arr3){ $i = 0; $j = 0; $k = 0; // Traverse both array while ($i < $n1 && $j < $n2) { // Check if current element // of first array is smaller // than current element of // second array. If yes, // store first array element // and increment first array // index. Otherwise do same // with second array if ($arr1[$i] < $arr2[$j]) $arr3[$k++] = $arr1[$i++]; else $arr3[$k++] = $arr2[$j++]; } // Store remaining elements // of first array while ($i < $n1) $arr3[$k++] = $arr1[$i++]; // Store remaining elements // of second array while ($j < $n2) $arr3[$k++] = $arr2[$j++];} // Driver code$arr1 = array(1, 3, 5, 7);$n1 = sizeof($arr1); $arr2 = array(2, 4, 6, 8);$n2 = sizeof($arr2); $arr3[$n1 + $n2] = array();mergeArrays($arr1, $arr2, $n1, $n2, $arr3); echo "Array after merging \n" ;for ($i = 0; $i < $n1 + $n2; $i++) echo $arr3[$i] . " "; // This code is contributed// by ChitraNayal?> <script>// javascript program to merge two sorted arrays // Merge arr1[0..n1-1] and arr2[0..n2-1] // into arr3[0..n1+n2-1] function mergeArrays(arr1, arr2 , n1 , n2, arr3) { var i = 0, j = 0, k = 0; // Traverse both array while (i < n1 && j < n2) { // Check if current element of first // array is smaller than current element // of second array. If yes, store first // array element and increment first array // index. Otherwise do same with second array if (arr1[i] < arr2[j]) arr3[k++] = arr1[i++]; else arr3[k++] = arr2[j++]; } // Store remaining elements of first array while (i < n1) arr3[k++] = arr1[i++]; // Store remaining elements of second array while (j < n2) arr3[k++] = arr2[j++]; } var arr1 = [ 1, 3, 5, 7 ]; var n1 = arr1.length; var arr2 = [ 2, 4, 6, 8 ]; var n2 = arr2.length; var arr3 = Array(n1 + n2).fill(0); mergeArrays(arr1, arr2, n1, n2, arr3); document.write("Array after merging<br/>"); for (i = 0; i < n1 + n2; i++) document.write(arr3[i] + " "); // This code contributed by Rajput-Ji</script> Output: Array after merging 1 2 3 4 5 6 7 8 Time Complexity : O(n1 + n2) Auxiliary Space : O(n1 + n2)Method 3: Using Maps (O(nlog(n) + mlog(m)) Time and O(N) Extra Space) Insert elements of both arrays in a map as keys.Print the keys of the map. Insert elements of both arrays in a map as keys. Print the keys of the map. Below is the implementation of above approach. CPP Java C# Javascript // C++ program to merge two sorted arrays//using maps#include<bits/stdc++.h>using namespace std; // Function to merge arraysvoid mergeArrays(int a[], int b[], int n, int m){ // Declaring a map. // using map as a inbuilt tool // to store elements in sorted order. map<int, bool> mp; // Inserting values to a map. for(int i = 0; i < n; i++) mp[a[i]] = true; for(int i = 0;i < m;i++) mp[b[i]] = true; // Printing keys of the map. for(auto i: mp) cout<< i.first <<" ";} // Driver Codeint main(){ int a[] = {1, 3, 5, 7}, b[] = {2, 4, 6, 8}; int size = sizeof(a)/sizeof(int); int size1 = sizeof(b)/sizeof(int); // Function call mergeArrays(a, b, size, size1); return 0;} //This code is contributed by yashbeersingh42 // Java program to merge two sorted arrays//using mapsimport java.io.*;import java.util.*; class GFG { // Function to merge arrays static void mergeArrays(int a[], int b[], int n, int m) { // Declaring a map. // using map as a inbuilt tool // to store elements in sorted order. Map<Integer,Boolean> mp = new TreeMap<Integer,Boolean>(); // Inserting values to a map. for(int i = 0; i < n; i++) { mp.put(a[i], true); } for(int i = 0;i < m;i++) { mp.put(b[i], true); } // Printing keys of the map. for (Map.Entry<Integer,Boolean> me : mp.entrySet()) { System.out.print(me.getKey() + " "); } } // Driver Code public static void main (String[] args) { int a[] = {1, 3, 5, 7}, b[] = {2, 4, 6, 8}; int size = a.length; int size1 = b.length; // Function call mergeArrays(a, b, size, size1); }} // This code is contributed by rag2127 // C# program to merge two sorted arrays//using mapsusing System;using System.Collections.Generic; public class GFG { // Function to merge arrays static void mergeArrays(int []a, int []b, int n, int m) { // Declaring a map. // using map as a inbuilt tool // to store elements in sorted order. SortedDictionary<int, Boolean> mp = new SortedDictionary<int, Boolean>(); // Inserting values to a map. for (int i = 0; i < n; i++) { mp.Add(a[i], true); } for (int i = 0; i < m; i++) { mp.Add(b[i], true); } // Printing keys of the map. foreach (KeyValuePair<int, Boolean> me in mp) { Console.Write(me.Key + " "); } } // Driver Code public static void Main(String[] args) { int []a = { 1, 3, 5, 7 }; int []b = { 2, 4, 6, 8 }; int size = a.Length; int size1 = b.Length; // Function call mergeArrays(a, b, size, size1); }} // This code is contributed by gauravrajput1 <script>// javascript program to merge two sorted arrays//using maps // Function to merge arrays function mergeArrays(a , b , n , m) { // Declaring a map. // using map as a inbuilt tool // to store elements in sorted order. var mp = new Map(); // Inserting values to a map. for (i = 0; i < n; i++) { mp.set(a[i], true); } for (i = 0; i < m; i++) { mp.set(b[i], true); } var a = []; // Printing keys of the map. for ( me of mp.keys()) { a.push(me); } a.sort(); for ( me of a) { document.write(me + " "); } } // Driver Code var a = [ 1, 3, 5, 7 ], b = [ 2, 4, 6, 8 ]; var size = a.length; var size1 = b.length; // Function call mergeArrays(a, b, size, size1); // This code is contributed by gauravrajput1</script> Output: 1 2 3 4 5 6 7 8 Time Complexity: O( nlog(n) + mlog(m) ) Auxiliary Space: O(N)Brocade,Goldman-Sachs,Juniper,Linkedin,Microsoft,Quikr,Snapdeal,Synopsys,ZohoRelated Articles : Merge two sorted arrays with O(1) extra space Merge k sorted arrays | Set 1This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. ukasp nkkanasagara Patabhu nidhi_biet yashbeersingh42 parth_gpta rag2127 local-dante drig rohitharjani0107 Rajput-Ji GauravRajput1 Amazon Amdocs Brocade Goldman Sachs Insertion Sort Juniper Networks Linkedin Merge Sort Microsoft Quikr Snapdeal Synopsys Visa Zoho Arrays Mathematical Sorting Zoho Amazon Microsoft Snapdeal Visa Goldman Sachs Linkedin Amdocs Brocade Juniper Networks Quikr Synopsys Arrays Mathematical Sorting Merge Sort Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Arrays Multidimensional Arrays in Java Linked List vs Array Python | Using 2D arrays/lists the right way Search an element in a sorted and rotated array Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 26145, "s": 26117, "text": "\n11 Jan, 2022" }, { "code": null, "e": 26226, "s": 26145, "text": "Given two sorted arrays, the task is to merge them in a sorted manner.Examples: " }, { "code": null, "e": 26404, "s": 26226, "text": "Input: arr1[] = { 1, 3, 4, 5}, arr2[] = {2, 4, 6, 8} Output: arr3[] = {1, 2, 3, 4, 4, 5, 6, 8}Input: arr1[] = { 5, 8, 9}, arr2[] = {4, 7, 8} Output: arr3[] = {4, 5, 7, 8, 8, 9} " }, { "code": null, "e": 26457, "s": 26404, "text": "Method 1 (O(n1 * n2) Time and O(n1+n2) Extra Space) " }, { "code": null, "e": 26658, "s": 26457, "text": "Create an array arr3[] of size n1 + n2.Copy all n1 elements of arr1[] to arr3[]Traverse arr2[] and one by one insert elements (like insertion sort) of arr3[] to arr1[]. This step take O(n1 * n2) time." }, { "code": null, "e": 26698, "s": 26658, "text": "Create an array arr3[] of size n1 + n2." }, { "code": null, "e": 26739, "s": 26698, "text": "Copy all n1 elements of arr1[] to arr3[]" }, { "code": null, "e": 26861, "s": 26739, "text": "Traverse arr2[] and one by one insert elements (like insertion sort) of arr3[] to arr1[]. This step take O(n1 * n2) time." }, { "code": null, "e": 27062, "s": 26861, "text": "We have discussed implementation of above method in Merge two sorted arrays with O(1) extra spaceMethod 2 (O(n1 + n2) Time and O(n1 + n2) Extra Space) The idea is to use Merge function of Merge sort. " }, { "code": null, "e": 27394, "s": 27062, "text": "Create an array arr3[] of size n1 + n2.Simultaneously traverse arr1[] and arr2[]. Pick smaller of current elements in arr1[] and arr2[], copy this smaller element to next position in arr3[] and move ahead in arr3[] and the array whose element is picked.If there are remaining elements in arr1[] or arr2[], copy them also in arr3[]." }, { "code": null, "e": 27434, "s": 27394, "text": "Create an array arr3[] of size n1 + n2." }, { "code": null, "e": 27649, "s": 27434, "text": "Simultaneously traverse arr1[] and arr2[]. Pick smaller of current elements in arr1[] and arr2[], copy this smaller element to next position in arr3[] and move ahead in arr3[] and the array whose element is picked." }, { "code": null, "e": 27821, "s": 27649, "text": "Pick smaller of current elements in arr1[] and arr2[], copy this smaller element to next position in arr3[] and move ahead in arr3[] and the array whose element is picked." }, { "code": null, "e": 27900, "s": 27821, "text": "If there are remaining elements in arr1[] or arr2[], copy them also in arr3[]." }, { "code": null, "e": 27949, "s": 27900, "text": "Below image is a dry run of the above approach: " }, { "code": null, "e": 28001, "s": 27949, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 28005, "s": 28001, "text": "C++" }, { "code": null, "e": 28010, "s": 28005, "text": "Java" }, { "code": null, "e": 28019, "s": 28010, "text": "Python 3" }, { "code": null, "e": 28022, "s": 28019, "text": "C#" }, { "code": null, "e": 28026, "s": 28022, "text": "PHP" }, { "code": null, "e": 28037, "s": 28026, "text": "Javascript" }, { "code": "// C++ program to merge two sorted arrays/#include<iostream>using namespace std; // Merge arr1[0..n1-1] and arr2[0..n2-1] into// arr3[0..n1+n2-1]void mergeArrays(int arr1[], int arr2[], int n1, int n2, int arr3[]){ int i = 0, j = 0, k = 0; // Traverse both array while (i<n1 && j <n2) { // Check if current element of first // array is smaller than current element // of second array. If yes, store first // array element and increment first array // index. Otherwise do same with second array if (arr1[i] < arr2[j]) arr3[k++] = arr1[i++]; else arr3[k++] = arr2[j++]; } // Store remaining elements of first array while (i < n1) arr3[k++] = arr1[i++]; // Store remaining elements of second array while (j < n2) arr3[k++] = arr2[j++];} // Driver codeint main(){ int arr1[] = {1, 3, 5, 7}; int n1 = sizeof(arr1) / sizeof(arr1[0]); int arr2[] = {2, 4, 6, 8}; int n2 = sizeof(arr2) / sizeof(arr2[0]); int arr3[n1+n2]; mergeArrays(arr1, arr2, n1, n2, arr3); cout << \"Array after merging\" <<endl; for (int i=0; i < n1+n2; i++) cout << arr3[i] << \" \"; return 0;}", "e": 29273, "s": 28037, "text": null }, { "code": "// Java program to merge two sorted arraysimport java.util.*;import java.lang.*;import java.io.*; class MergeTwoSorted{ // Merge arr1[0..n1-1] and arr2[0..n2-1] // into arr3[0..n1+n2-1] public static void mergeArrays(int[] arr1, int[] arr2, int n1, int n2, int[] arr3) { int i = 0, j = 0, k = 0; // Traverse both array while (i<n1 && j <n2) { // Check if current element of first // array is smaller than current element // of second array. If yes, store first // array element and increment first array // index. Otherwise do same with second array if (arr1[i] < arr2[j]) arr3[k++] = arr1[i++]; else arr3[k++] = arr2[j++]; } // Store remaining elements of first array while (i < n1) arr3[k++] = arr1[i++]; // Store remaining elements of second array while (j < n2) arr3[k++] = arr2[j++]; } public static void main (String[] args) { int[] arr1 = {1, 3, 5, 7}; int n1 = arr1.length; int[] arr2 = {2, 4, 6, 8}; int n2 = arr2.length; int[] arr3 = new int[n1+n2]; mergeArrays(arr1, arr2, n1, n2, arr3); System.out.println(\"Array after merging\"); for (int i=0; i < n1+n2; i++) System.out.print(arr3[i] + \" \"); }} /* This code is contributed by Mr. Somesh Awasthi */", "e": 30792, "s": 29273, "text": null }, { "code": "# Python program to merge# two sorted arrays # Merge arr1[0..n1-1] and# arr2[0..n2-1] into# arr3[0..n1+n2-1]def mergeArrays(arr1, arr2, n1, n2): arr3 = [None] * (n1 + n2) i = 0 j = 0 k = 0 # Traverse both array while i < n1 and j < n2: # Check if current element # of first array is smaller # than current element of # second array. If yes, # store first array element # and increment first array # index. Otherwise do same # with second array if arr1[i] < arr2[j]: arr3[k] = arr1[i] k = k + 1 i = i + 1 else: arr3[k] = arr2[j] k = k + 1 j = j + 1 # Store remaining elements # of first array while i < n1: arr3[k] = arr1[i]; k = k + 1 i = i + 1 # Store remaining elements # of second array while j < n2: arr3[k] = arr2[j]; k = k + 1 j = j + 1 print(\"Array after merging\") for i in range(n1 + n2): print(str(arr3[i]), end = \" \") # Driver codearr1 = [1, 3, 5, 7]n1 = len(arr1) arr2 = [2, 4, 6, 8]n2 = len(arr2)mergeArrays(arr1, arr2, n1, n2); # This code is contributed# by ChitraNayal", "e": 32016, "s": 30792, "text": null }, { "code": "// C# program to merge// two sorted arraysusing System; class GFG{ // Merge arr1[0..n1-1] and // arr2[0..n2-1] into // arr3[0..n1+n2-1] public static void mergeArrays(int[] arr1, int[] arr2, int n1, int n2, int[] arr3) { int i = 0, j = 0, k = 0; // Traverse both array while (i < n1 && j < n2) { // Check if current element // of first array is smaller // than current element // of second array. If yes, // store first array element // and increment first array // index. Otherwise do same // with second array if (arr1[i] < arr2[j]) arr3[k++] = arr1[i++]; else arr3[k++] = arr2[j++]; } // Store remaining // elements of first array while (i < n1) arr3[k++] = arr1[i++]; // Store remaining elements // of second array while (j < n2) arr3[k++] = arr2[j++]; } // Driver code public static void Main() { int[] arr1 = {1, 3, 5, 7}; int n1 = arr1.Length; int[] arr2 = {2, 4, 6, 8}; int n2 = arr2.Length; int[] arr3 = new int[n1+n2]; mergeArrays(arr1, arr2, n1, n2, arr3); Console.Write(\"Array after merging\\n\"); for (int i = 0; i < n1 + n2; i++) Console.Write(arr3[i] + \" \"); }} // This code is contributed// by ChitraNayal", "e": 33546, "s": 32016, "text": null }, { "code": "<?php// PHP program to merge// two sorted arrays // Merge $arr1[0..$n1-1] and// $arr2[0..$n2-1] into// $arr3[0..$n1+$n2-1]function mergeArrays(&$arr1, &$arr2, $n1, $n2, &$arr3){ $i = 0; $j = 0; $k = 0; // Traverse both array while ($i < $n1 && $j < $n2) { // Check if current element // of first array is smaller // than current element of // second array. If yes, // store first array element // and increment first array // index. Otherwise do same // with second array if ($arr1[$i] < $arr2[$j]) $arr3[$k++] = $arr1[$i++]; else $arr3[$k++] = $arr2[$j++]; } // Store remaining elements // of first array while ($i < $n1) $arr3[$k++] = $arr1[$i++]; // Store remaining elements // of second array while ($j < $n2) $arr3[$k++] = $arr2[$j++];} // Driver code$arr1 = array(1, 3, 5, 7);$n1 = sizeof($arr1); $arr2 = array(2, 4, 6, 8);$n2 = sizeof($arr2); $arr3[$n1 + $n2] = array();mergeArrays($arr1, $arr2, $n1, $n2, $arr3); echo \"Array after merging \\n\" ;for ($i = 0; $i < $n1 + $n2; $i++) echo $arr3[$i] . \" \"; // This code is contributed// by ChitraNayal?>", "e": 34804, "s": 33546, "text": null }, { "code": "<script>// javascript program to merge two sorted arrays // Merge arr1[0..n1-1] and arr2[0..n2-1] // into arr3[0..n1+n2-1] function mergeArrays(arr1, arr2 , n1 , n2, arr3) { var i = 0, j = 0, k = 0; // Traverse both array while (i < n1 && j < n2) { // Check if current element of first // array is smaller than current element // of second array. If yes, store first // array element and increment first array // index. Otherwise do same with second array if (arr1[i] < arr2[j]) arr3[k++] = arr1[i++]; else arr3[k++] = arr2[j++]; } // Store remaining elements of first array while (i < n1) arr3[k++] = arr1[i++]; // Store remaining elements of second array while (j < n2) arr3[k++] = arr2[j++]; } var arr1 = [ 1, 3, 5, 7 ]; var n1 = arr1.length; var arr2 = [ 2, 4, 6, 8 ]; var n2 = arr2.length; var arr3 = Array(n1 + n2).fill(0); mergeArrays(arr1, arr2, n1, n2, arr3); document.write(\"Array after merging<br/>\"); for (i = 0; i < n1 + n2; i++) document.write(arr3[i] + \" \"); // This code contributed by Rajput-Ji</script>", "e": 36105, "s": 34804, "text": null }, { "code": null, "e": 36114, "s": 36105, "text": "Output: " }, { "code": null, "e": 36150, "s": 36114, "text": "Array after merging\n1 2 3 4 5 6 7 8" }, { "code": null, "e": 36278, "s": 36150, "text": "Time Complexity : O(n1 + n2) Auxiliary Space : O(n1 + n2)Method 3: Using Maps (O(nlog(n) + mlog(m)) Time and O(N) Extra Space) " }, { "code": null, "e": 36353, "s": 36278, "text": "Insert elements of both arrays in a map as keys.Print the keys of the map." }, { "code": null, "e": 36402, "s": 36353, "text": "Insert elements of both arrays in a map as keys." }, { "code": null, "e": 36429, "s": 36402, "text": "Print the keys of the map." }, { "code": null, "e": 36477, "s": 36429, "text": "Below is the implementation of above approach. " }, { "code": null, "e": 36481, "s": 36477, "text": "CPP" }, { "code": null, "e": 36486, "s": 36481, "text": "Java" }, { "code": null, "e": 36489, "s": 36486, "text": "C#" }, { "code": null, "e": 36500, "s": 36489, "text": "Javascript" }, { "code": "// C++ program to merge two sorted arrays//using maps#include<bits/stdc++.h>using namespace std; // Function to merge arraysvoid mergeArrays(int a[], int b[], int n, int m){ // Declaring a map. // using map as a inbuilt tool // to store elements in sorted order. map<int, bool> mp; // Inserting values to a map. for(int i = 0; i < n; i++) mp[a[i]] = true; for(int i = 0;i < m;i++) mp[b[i]] = true; // Printing keys of the map. for(auto i: mp) cout<< i.first <<\" \";} // Driver Codeint main(){ int a[] = {1, 3, 5, 7}, b[] = {2, 4, 6, 8}; int size = sizeof(a)/sizeof(int); int size1 = sizeof(b)/sizeof(int); // Function call mergeArrays(a, b, size, size1); return 0;} //This code is contributed by yashbeersingh42", "e": 37295, "s": 36500, "text": null }, { "code": "// Java program to merge two sorted arrays//using mapsimport java.io.*;import java.util.*; class GFG { // Function to merge arrays static void mergeArrays(int a[], int b[], int n, int m) { // Declaring a map. // using map as a inbuilt tool // to store elements in sorted order. Map<Integer,Boolean> mp = new TreeMap<Integer,Boolean>(); // Inserting values to a map. for(int i = 0; i < n; i++) { mp.put(a[i], true); } for(int i = 0;i < m;i++) { mp.put(b[i], true); } // Printing keys of the map. for (Map.Entry<Integer,Boolean> me : mp.entrySet()) { System.out.print(me.getKey() + \" \"); } } // Driver Code public static void main (String[] args) { int a[] = {1, 3, 5, 7}, b[] = {2, 4, 6, 8}; int size = a.length; int size1 = b.length; // Function call mergeArrays(a, b, size, size1); }} // This code is contributed by rag2127", "e": 38357, "s": 37295, "text": null }, { "code": "// C# program to merge two sorted arrays//using mapsusing System;using System.Collections.Generic; public class GFG { // Function to merge arrays static void mergeArrays(int []a, int []b, int n, int m) { // Declaring a map. // using map as a inbuilt tool // to store elements in sorted order. SortedDictionary<int, Boolean> mp = new SortedDictionary<int, Boolean>(); // Inserting values to a map. for (int i = 0; i < n; i++) { mp.Add(a[i], true); } for (int i = 0; i < m; i++) { mp.Add(b[i], true); } // Printing keys of the map. foreach (KeyValuePair<int, Boolean> me in mp) { Console.Write(me.Key + \" \"); } } // Driver Code public static void Main(String[] args) { int []a = { 1, 3, 5, 7 }; int []b = { 2, 4, 6, 8 }; int size = a.Length; int size1 = b.Length; // Function call mergeArrays(a, b, size, size1); }} // This code is contributed by gauravrajput1", "e": 39298, "s": 38357, "text": null }, { "code": "<script>// javascript program to merge two sorted arrays//using maps // Function to merge arrays function mergeArrays(a , b , n , m) { // Declaring a map. // using map as a inbuilt tool // to store elements in sorted order. var mp = new Map(); // Inserting values to a map. for (i = 0; i < n; i++) { mp.set(a[i], true); } for (i = 0; i < m; i++) { mp.set(b[i], true); } var a = []; // Printing keys of the map. for ( me of mp.keys()) { a.push(me); } a.sort(); for ( me of a) { document.write(me + \" \"); } } // Driver Code var a = [ 1, 3, 5, 7 ], b = [ 2, 4, 6, 8 ]; var size = a.length; var size1 = b.length; // Function call mergeArrays(a, b, size, size1); // This code is contributed by gauravrajput1</script>", "e": 40234, "s": 39298, "text": null }, { "code": null, "e": 40242, "s": 40234, "text": "Output:" }, { "code": null, "e": 40258, "s": 40242, "text": "1 2 3 4 5 6 7 8" }, { "code": null, "e": 40911, "s": 40258, "text": "Time Complexity: O( nlog(n) + mlog(m) ) Auxiliary Space: O(N)Brocade,Goldman-Sachs,Juniper,Linkedin,Microsoft,Quikr,Snapdeal,Synopsys,ZohoRelated Articles : Merge two sorted arrays with O(1) extra space Merge k sorted arrays | Set 1This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 40917, "s": 40911, "text": "ukasp" }, { "code": null, "e": 40930, "s": 40917, "text": "nkkanasagara" }, { "code": null, "e": 40938, "s": 40930, "text": "Patabhu" }, { "code": null, "e": 40949, "s": 40938, "text": "nidhi_biet" }, { "code": null, "e": 40965, "s": 40949, "text": "yashbeersingh42" }, { "code": null, "e": 40976, "s": 40965, "text": "parth_gpta" }, { "code": null, "e": 40984, "s": 40976, "text": "rag2127" }, { "code": null, "e": 40996, "s": 40984, "text": "local-dante" }, { "code": null, "e": 41001, "s": 40996, "text": "drig" }, { "code": null, "e": 41018, "s": 41001, "text": "rohitharjani0107" }, { "code": null, "e": 41028, "s": 41018, "text": "Rajput-Ji" }, { "code": null, "e": 41042, "s": 41028, "text": "GauravRajput1" }, { "code": null, "e": 41049, "s": 41042, "text": "Amazon" }, { "code": null, "e": 41056, "s": 41049, "text": "Amdocs" }, { "code": null, "e": 41064, "s": 41056, "text": "Brocade" }, { "code": null, "e": 41078, "s": 41064, "text": "Goldman Sachs" }, { "code": null, "e": 41093, "s": 41078, "text": "Insertion Sort" }, { "code": null, "e": 41110, "s": 41093, "text": "Juniper Networks" }, { "code": null, "e": 41119, "s": 41110, "text": "Linkedin" }, { "code": null, "e": 41130, "s": 41119, "text": "Merge Sort" }, { "code": null, "e": 41140, "s": 41130, "text": "Microsoft" }, { "code": null, "e": 41146, "s": 41140, "text": "Quikr" }, { "code": null, "e": 41155, "s": 41146, "text": "Snapdeal" }, { "code": null, "e": 41164, "s": 41155, "text": "Synopsys" }, { "code": null, "e": 41169, "s": 41164, "text": "Visa" }, { "code": null, "e": 41174, "s": 41169, "text": "Zoho" }, { "code": null, "e": 41181, "s": 41174, "text": "Arrays" }, { "code": null, "e": 41194, "s": 41181, "text": "Mathematical" }, { "code": null, "e": 41202, "s": 41194, "text": "Sorting" }, { "code": null, "e": 41207, "s": 41202, "text": "Zoho" }, { "code": null, "e": 41214, "s": 41207, "text": "Amazon" }, { "code": null, "e": 41224, "s": 41214, "text": "Microsoft" }, { "code": null, "e": 41233, "s": 41224, "text": "Snapdeal" }, { "code": null, "e": 41238, "s": 41233, "text": "Visa" }, { "code": null, "e": 41252, "s": 41238, "text": "Goldman Sachs" }, { "code": null, "e": 41261, "s": 41252, "text": "Linkedin" }, { "code": null, "e": 41268, "s": 41261, "text": "Amdocs" }, { "code": null, "e": 41276, "s": 41268, "text": "Brocade" }, { "code": null, "e": 41293, "s": 41276, "text": "Juniper Networks" }, { "code": null, "e": 41299, "s": 41293, "text": "Quikr" }, { "code": null, "e": 41308, "s": 41299, "text": "Synopsys" }, { "code": null, "e": 41315, "s": 41308, "text": "Arrays" }, { "code": null, "e": 41328, "s": 41315, "text": "Mathematical" }, { "code": null, "e": 41336, "s": 41328, "text": "Sorting" }, { "code": null, "e": 41347, "s": 41336, "text": "Merge Sort" }, { "code": null, "e": 41445, "s": 41347, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41468, "s": 41445, "text": "Introduction to Arrays" }, { "code": null, "e": 41500, "s": 41468, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 41521, "s": 41500, "text": "Linked List vs Array" }, { "code": null, "e": 41566, "s": 41521, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 41614, "s": 41566, "text": "Search an element in a sorted and rotated array" }, { "code": null, "e": 41644, "s": 41614, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 41704, "s": 41644, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 41719, "s": 41704, "text": "C++ Data Types" }, { "code": null, "e": 41762, "s": 41719, "text": "Set in C++ Standard Template Library (STL)" } ]
LEX program to count the number of vowels and consonants in a given string - GeeksforGeeks
27 Feb, 2020 Prerequisite: Flex (Fast lexical Analyzer Generator) Given a string containing both vowels and consonants, write a LEX program to count the number of vowels and consonants in given string. Examples: Input: Hello everyone Output: Number of vowels are: 6 Number of consonants are: 7 Input: This is GeeksforGeeks Output: Number of vowels are: 7 Number of consonants are: 12 Approach-Approach is very simple. If any vowel is found increase vowel counter, if consonant is found increase consonant counter otherwise do nothing. Below is the implementation: %{ int vow_count=0; int const_count =0;%} %%[aeiouAEIOU] {vow_count++;}[a-zA-Z] {const_count++;}%%int yywrap(){}int main(){ printf("Enter the string of vowels and consonents:"); yylex(); printf("Number of vowels are: %d\n", vow_count); printf("Number of consonants are: %d\n", const_count); return 0;} Output: ankita_chandra Lex program Compiler Design Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Symbol Table in Compiler Code Optimization in Compiler Design Intermediate Code Generation in Compiler Design Directed Acyclic graph in Compiler Design (with examples) Introduction of Compiler Design Types of Parsers in Compiler Design Ambiguous Grammar Difference between Compiler and Interpreter Peephole Optimization in Compiler Design S - attributed and L - attributed SDTs in Syntax directed translation
[ { "code": null, "e": 25955, "s": 25927, "text": "\n27 Feb, 2020" }, { "code": null, "e": 26008, "s": 25955, "text": "Prerequisite: Flex (Fast lexical Analyzer Generator)" }, { "code": null, "e": 26144, "s": 26008, "text": "Given a string containing both vowels and consonants, write a LEX program to count the number of vowels and consonants in given string." }, { "code": null, "e": 26154, "s": 26144, "text": "Examples:" }, { "code": null, "e": 26345, "s": 26154, "text": "Input: Hello everyone\nOutput: Number of vowels are: 6\n Number of consonants are: 7\n\n\nInput: This is GeeksforGeeks\nOutput: Number of vowels are: 7\n Number of consonants are: 12\n" }, { "code": null, "e": 26496, "s": 26345, "text": "Approach-Approach is very simple. If any vowel is found increase vowel counter, if consonant is found increase consonant counter otherwise do nothing." }, { "code": null, "e": 26525, "s": 26496, "text": "Below is the implementation:" }, { "code": "%{ int vow_count=0; int const_count =0;%} %%[aeiouAEIOU] {vow_count++;}[a-zA-Z] {const_count++;}%%int yywrap(){}int main(){ printf(\"Enter the string of vowels and consonents:\"); yylex(); printf(\"Number of vowels are: %d\\n\", vow_count); printf(\"Number of consonants are: %d\\n\", const_count); return 0;} ", "e": 26852, "s": 26525, "text": null }, { "code": null, "e": 26860, "s": 26852, "text": "Output:" }, { "code": null, "e": 26875, "s": 26860, "text": "ankita_chandra" }, { "code": null, "e": 26887, "s": 26875, "text": "Lex program" }, { "code": null, "e": 26903, "s": 26887, "text": "Compiler Design" }, { "code": null, "e": 27001, "s": 26903, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27026, "s": 27001, "text": "Symbol Table in Compiler" }, { "code": null, "e": 27063, "s": 27026, "text": "Code Optimization in Compiler Design" }, { "code": null, "e": 27111, "s": 27063, "text": "Intermediate Code Generation in Compiler Design" }, { "code": null, "e": 27169, "s": 27111, "text": "Directed Acyclic graph in Compiler Design (with examples)" }, { "code": null, "e": 27201, "s": 27169, "text": "Introduction of Compiler Design" }, { "code": null, "e": 27237, "s": 27201, "text": "Types of Parsers in Compiler Design" }, { "code": null, "e": 27255, "s": 27237, "text": "Ambiguous Grammar" }, { "code": null, "e": 27299, "s": 27255, "text": "Difference between Compiler and Interpreter" }, { "code": null, "e": 27340, "s": 27299, "text": "Peephole Optimization in Compiler Design" } ]
Program to find gravitational force between two objects - GeeksforGeeks
04 May, 2022 Introduction to Gravitational Force We know that gravity is universal. According to Newton’s Law of Universal Gravitation, all objects attract each other with a force of gravitational attraction. According to this law, the force of gravitational attraction is directly dependent upon the masses of both objects and inversely proportional to the square of the distance that separates their centres. On removing the proportionality sign, we add G, the Universal Gravitational Constant. This can be reduced to the following equation: F= Gravitation force of attraction between two objects in newton(N)G=Universal Gravitational Constant()m1 and m2 = Mass of two objects(Kg)r= separation in meters(m) between the objects, as measured from their centres of mass. Examples: Input: m1 = 20000000 kg m2 = 4000000 kg r = 15 m Output : The Gravitational Force is: 23.73 N Input: m1 = 5000000 kg m2 = 900000 kg r = 30 m Output : The Gravitational Force is: 0.33 N The approach is simple. We will just use the formula mentioned in the Introduction. C++ Python3 Javascript // C++ code to find Gravitational Force#include <iostream>using namespace std; float round(float F){ float value = (int)(F * 100 + .5); return (float)value / 100;} float force(double m1, double m2, double r){ float G; G = 6.67 / 1e11; float F; F = (G * m1 * m2) / (r * r); // Rounding to two digits after decimal return round(F);} // Driver codeint main(){ float m1, m2, r; m1 = 5000000; m2 = 900000; r = 30; cout << "The Gravitational Force is: " << force(m1, m2, r) << "N"; return 0;} // This code is contributed by parthagarwal1962000 # Python3 code to find Gravitational Forcedef force(m1, m2, r): G = 6.673*(10**-11) F = (G*m1*m2)/(r**2) # Rounding to two digits after decimal return round(F, 2) # Driver Codem1 = 5000000m2 = 900000r = 30print("The Gravitational Force is: ", force(m1, m2, r), "N") <script>// JavaScript code to find Gravitational Forcefunction round (F){ var value = (F * 100 + .5); return value / 100; } function force(m1, m2, r){ var G; G = 6.67 / 1e11; var F; F = (G * m1 * m2) / (r * r); // Rounding to two digits after decimal return round(F); } // Driver code var m1, m2, r; m1 = 5000000; m2 = 900000; r = 30; document.write("The Gravitational Force is: " + force(m1, m2, r) +"N"); // This code is contributed by shivanisinghss2110</script> Output: The Gravitational Force is: 0.33 N ysachin2314 parthagarwal1962000 shivanisinghss2110 surinderdawra388 School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Constructors in Java Exceptions in Java Data Types Inline Functions in C++ Pure Virtual Functions and Abstract Classes in C++ Difference between Abstract Class and Interface in Java Destructors in C++ Python Exception Handling Exception Handling in C++ Input and Output
[ { "code": null, "e": 25439, "s": 25411, "text": "\n04 May, 2022" }, { "code": null, "e": 25475, "s": 25439, "text": "Introduction to Gravitational Force" }, { "code": null, "e": 26196, "s": 25475, "text": "We know that gravity is universal. According to Newton’s Law of Universal Gravitation, all objects attract each other with a force of gravitational attraction. According to this law, the force of gravitational attraction is directly dependent upon the masses of both objects and inversely proportional to the square of the distance that separates their centres. On removing the proportionality sign, we add G, the Universal Gravitational Constant. This can be reduced to the following equation: F= Gravitation force of attraction between two objects in newton(N)G=Universal Gravitational Constant()m1 and m2 = Mass of two objects(Kg)r= separation in meters(m) between the objects, as measured from their centres of mass." }, { "code": null, "e": 26207, "s": 26196, "text": "Examples: " }, { "code": null, "e": 26423, "s": 26207, "text": "Input: m1 = 20000000 kg\n m2 = 4000000 kg\n r = 15 m\nOutput : The Gravitational Force is: 23.73 N\n\nInput: m1 = 5000000 kg\n m2 = 900000 kg\n r = 30 m\nOutput : The Gravitational Force is: 0.33 N" }, { "code": null, "e": 26508, "s": 26423, "text": "The approach is simple. We will just use the formula mentioned in the Introduction. " }, { "code": null, "e": 26512, "s": 26508, "text": "C++" }, { "code": null, "e": 26520, "s": 26512, "text": "Python3" }, { "code": null, "e": 26531, "s": 26520, "text": "Javascript" }, { "code": "// C++ code to find Gravitational Force#include <iostream>using namespace std; float round(float F){ float value = (int)(F * 100 + .5); return (float)value / 100;} float force(double m1, double m2, double r){ float G; G = 6.67 / 1e11; float F; F = (G * m1 * m2) / (r * r); // Rounding to two digits after decimal return round(F);} // Driver codeint main(){ float m1, m2, r; m1 = 5000000; m2 = 900000; r = 30; cout << \"The Gravitational Force is: \" << force(m1, m2, r) << \"N\"; return 0;} // This code is contributed by parthagarwal1962000", "e": 27134, "s": 26531, "text": null }, { "code": "# Python3 code to find Gravitational Forcedef force(m1, m2, r): G = 6.673*(10**-11) F = (G*m1*m2)/(r**2) # Rounding to two digits after decimal return round(F, 2) # Driver Codem1 = 5000000m2 = 900000r = 30print(\"The Gravitational Force is: \", force(m1, m2, r), \"N\")", "e": 27413, "s": 27134, "text": null }, { "code": "<script>// JavaScript code to find Gravitational Forcefunction round (F){ var value = (F * 100 + .5); return value / 100; } function force(m1, m2, r){ var G; G = 6.67 / 1e11; var F; F = (G * m1 * m2) / (r * r); // Rounding to two digits after decimal return round(F); } // Driver code var m1, m2, r; m1 = 5000000; m2 = 900000; r = 30; document.write(\"The Gravitational Force is: \" + force(m1, m2, r) +\"N\"); // This code is contributed by shivanisinghss2110</script>", "e": 27954, "s": 27413, "text": null }, { "code": null, "e": 27963, "s": 27954, "text": "Output: " }, { "code": null, "e": 27999, "s": 27963, "text": "The Gravitational Force is: 0.33 N" }, { "code": null, "e": 28013, "s": 28001, "text": "ysachin2314" }, { "code": null, "e": 28033, "s": 28013, "text": "parthagarwal1962000" }, { "code": null, "e": 28052, "s": 28033, "text": "shivanisinghss2110" }, { "code": null, "e": 28069, "s": 28052, "text": "surinderdawra388" }, { "code": null, "e": 28088, "s": 28069, "text": "School Programming" }, { "code": null, "e": 28186, "s": 28088, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28207, "s": 28186, "text": "Constructors in Java" }, { "code": null, "e": 28226, "s": 28207, "text": "Exceptions in Java" }, { "code": null, "e": 28237, "s": 28226, "text": "Data Types" }, { "code": null, "e": 28261, "s": 28237, "text": "Inline Functions in C++" }, { "code": null, "e": 28312, "s": 28261, "text": "Pure Virtual Functions and Abstract Classes in C++" }, { "code": null, "e": 28368, "s": 28312, "text": "Difference between Abstract Class and Interface in Java" }, { "code": null, "e": 28387, "s": 28368, "text": "Destructors in C++" }, { "code": null, "e": 28413, "s": 28387, "text": "Python Exception Handling" }, { "code": null, "e": 28439, "s": 28413, "text": "Exception Handling in C++" } ]
Choose atleast two elements from array such that their GCD is 1 and cost is minimum - GeeksforGeeks
02 Jun, 2021 Given two integer arrays arr[] and cost[] where cost[i] is the cost of choosing arr[i]. The task is to choose a subset with at least two elements such that the GCD of all the elements from the subset is 1 and the cost of choosing those elements is as minimum as possible then print the minimum cost.Examples: Input: arr[] = {5, 10, 12, 1}, cost[] = {2, 1, 2, 6} Output: 4 {5, 12} is the required subset with cost = 2 + 2 = 4Input: arr[] = {50, 100, 150, 200, 300}, cost[] = {2, 3, 4, 5, 6} Output: -1 No subset possible with gcd = 1 Approach: Add GCD of any two elements to a map, now for every element arr[i] calculate its gcd with all the gcd values found so far (saved in the map) and update map[gcd] = min(map[gcd], map[gcd] + cost[i]). If in the end, map doesn’t contain any entry for gcd = 1 then print -1 else print the stored minimum cost.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the minimum cost requiredint getMinCost(int arr[], int n, int cost[]){ // Map to store <gcd, cost> pair where // cost is the cost to get the current gcd map<int, int> mp; mp.clear(); mp[0] = 0; for (int i = 0; i < n; i++) { for (auto it : mp) { int gcd = __gcd(arr[i], it.first); // If current gcd value already exists in map if (mp.count(gcd) == 1) // Update the minimum cost // to get the current gcd mp[gcd] = min(mp[gcd], it.second + cost[i]); else mp[gcd] = it.second + cost[i]; } } // If there can be no sub-set such that // the gcd of all the elements is 1 if (mp[1] == 0) return -1; else return mp[1];} // Driver codeint main(){ int arr[] = { 5, 10, 12, 1 }; int cost[] = { 2, 1, 2, 6 }; int n = sizeof(arr) / sizeof(arr[0]); cout << getMinCost(arr, n, cost); return 0;} // Java implementation of the approach import java.util.*;import java.util.concurrent.ConcurrentHashMap; class GFG{ // Function to return the minimum cost requiredstatic int getMinCost(int arr[], int n, int cost[]){ // Map to store <gcd, cost> pair where // cost is the cost to get the current gcd Map<Integer,Integer> mp = new ConcurrentHashMap<Integer,Integer>(); mp.clear(); mp.put(0, 0); for (int i = 0; i < n; i++) { for (Map.Entry<Integer,Integer> it : mp.entrySet()){ int gcd = __gcd(arr[i], it.getKey()); // If current gcd value already exists in map if (mp.containsKey(gcd)) // Update the minimum cost // to get the current gcd mp.put(gcd, Math.min(mp.get(gcd), it.getValue() + cost[i])); else mp.put(gcd,it.getValue() + cost[i]); } } // If there can be no sub-set such that // the gcd of all the elements is 1 if (!mp.containsKey(1)) return -1; else return mp.get(1);}static int __gcd(int a, int b) { return b == 0? a:__gcd(b, a % b); }// Driver codepublic static void main(String[] args){ int arr[] = { 5, 10, 12, 1 }; int cost[] = { 2, 1, 2, 6 }; int n = arr.length; System.out.print(getMinCost(arr, n, cost));}} // This code is contributed by PrinciRaj1992 # Python3 implementation of the approachfrom math import gcd as __gcd # Function to return the minimum cost requireddef getMinCost(arr, n, cost): # Map to store <gcd, cost> pair where # cost is the cost to get the current gcd mp = dict() mp[0] = 0 for i in range(n): for it in list(mp): gcd = __gcd(arr[i], it) # If current gcd value # already exists in map if (gcd in mp): # Update the minimum cost # to get the current gcd mp[gcd] = min(mp[gcd], mp[it] + cost[i]) else: mp[gcd] = mp[it] + cost[i] # If there can be no sub-set such that # the gcd of all the elements is 1 if (mp[1] == 0): return -1 else: return mp[1] # Driver codearr = [ 5, 10, 12, 1]cost = [ 2, 1, 2, 6]n = len(arr) print(getMinCost(arr, n, cost)) # This code is contributed by Mohit Kumar // C# implementation of the approachusing System;using System.Collections.Generic;using System.Linq;class GFG{ static int __gcd(int a, int b) { return b == 0? a:__gcd(b, a % b); } // Function to return the minimum cost required static int getMinCost(int[] arr, int n, int[] cost) { // Map to store <gcd, cost> pair where // cost is the cost to get the current gcd Dictionary<int, int> mp = new Dictionary<int, int>(); mp.Add(0, 0); for (int i = 0; i < n; i++) { foreach (int it in mp.Keys.ToList()) { int gcd = __gcd(arr[i], it); // If current gcd value already exists in map if(mp.ContainsKey(gcd)) { // Update the minimum cost // to get the current gcd mp[gcd] = Math.Min(mp[gcd], mp[it] + cost[i]); } else { mp.Add(gcd, mp[it] + cost[i]); } } } // If there can be no sub-set such that // the gcd of all the elements is 1 if (mp[1] == 0) { return -1; } else { return mp[1]; } } // Driver code static public void Main () { int[] arr = { 5, 10, 12, 1 }; int[] cost = { 2, 1, 2, 6 }; int n = arr.Length; Console.WriteLine(getMinCost(arr, n, cost)); }} // This code is contributed by avanitrachhadiya2155 <script> // JavaScript implementation of the approach // Function to return the minimum cost requiredfunction getMinCost(arr,n,cost){ // Map to store <gcd, cost> pair where // cost is the cost to get the current gcd let mp = new Map(); mp.set(0, 0); for (let i = 0; i < n; i++) { for (let [key, value] of mp.entries()){ let gcd = __gcd(arr[i], key); // If current gcd value already exists in map if (mp.has(gcd)) // Update the minimum cost // to get the current gcd mp.set(gcd, Math.min(mp.get(gcd), value + cost[i])); else mp.set(gcd,value + cost[i]); } } // If there can be no sub-set such that // the gcd of all the elements is 1 if (!mp.has(1)) return -1; else return mp.get(1);} function __gcd(a,b){ return b == 0? a:__gcd(b, a % b);} // Driver codelet arr=[5, 10, 12, 1 ];let cost=[2, 1, 2, 6 ];let n = arr.length;document.write(getMinCost(arr, n, cost)); // This code is contributed by unknown2108 </script> 4 mohit kumar 29 princiraj1992 avanitrachhadiya2155 unknown2108 Constructive Algorithms cpp-map Google Algorithms Hash Google Hash Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar How to write a Pseudo Code? Understanding Time Complexity with Simple Examples Introduction to Algorithms Internal Working of HashMap in Java Hashing | Set 1 (Introduction) Hashing | Set 3 (Open Addressing) Hashing | Set 2 (Separate Chaining) Sort string of characters
[ { "code": null, "e": 26483, "s": 26455, "text": "\n02 Jun, 2021" }, { "code": null, "e": 26794, "s": 26483, "text": "Given two integer arrays arr[] and cost[] where cost[i] is the cost of choosing arr[i]. The task is to choose a subset with at least two elements such that the GCD of all the elements from the subset is 1 and the cost of choosing those elements is as minimum as possible then print the minimum cost.Examples: " }, { "code": null, "e": 27020, "s": 26794, "text": "Input: arr[] = {5, 10, 12, 1}, cost[] = {2, 1, 2, 6} Output: 4 {5, 12} is the required subset with cost = 2 + 2 = 4Input: arr[] = {50, 100, 150, 200, 300}, cost[] = {2, 3, 4, 5, 6} Output: -1 No subset possible with gcd = 1 " }, { "code": null, "e": 27389, "s": 27022, "text": "Approach: Add GCD of any two elements to a map, now for every element arr[i] calculate its gcd with all the gcd values found so far (saved in the map) and update map[gcd] = min(map[gcd], map[gcd] + cost[i]). If in the end, map doesn’t contain any entry for gcd = 1 then print -1 else print the stored minimum cost.Below is the implementation of the above approach: " }, { "code": null, "e": 27393, "s": 27389, "text": "C++" }, { "code": null, "e": 27398, "s": 27393, "text": "Java" }, { "code": null, "e": 27406, "s": 27398, "text": "Python3" }, { "code": null, "e": 27409, "s": 27406, "text": "C#" }, { "code": null, "e": 27420, "s": 27409, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the minimum cost requiredint getMinCost(int arr[], int n, int cost[]){ // Map to store <gcd, cost> pair where // cost is the cost to get the current gcd map<int, int> mp; mp.clear(); mp[0] = 0; for (int i = 0; i < n; i++) { for (auto it : mp) { int gcd = __gcd(arr[i], it.first); // If current gcd value already exists in map if (mp.count(gcd) == 1) // Update the minimum cost // to get the current gcd mp[gcd] = min(mp[gcd], it.second + cost[i]); else mp[gcd] = it.second + cost[i]; } } // If there can be no sub-set such that // the gcd of all the elements is 1 if (mp[1] == 0) return -1; else return mp[1];} // Driver codeint main(){ int arr[] = { 5, 10, 12, 1 }; int cost[] = { 2, 1, 2, 6 }; int n = sizeof(arr) / sizeof(arr[0]); cout << getMinCost(arr, n, cost); return 0;}", "e": 28490, "s": 27420, "text": null }, { "code": "// Java implementation of the approach import java.util.*;import java.util.concurrent.ConcurrentHashMap; class GFG{ // Function to return the minimum cost requiredstatic int getMinCost(int arr[], int n, int cost[]){ // Map to store <gcd, cost> pair where // cost is the cost to get the current gcd Map<Integer,Integer> mp = new ConcurrentHashMap<Integer,Integer>(); mp.clear(); mp.put(0, 0); for (int i = 0; i < n; i++) { for (Map.Entry<Integer,Integer> it : mp.entrySet()){ int gcd = __gcd(arr[i], it.getKey()); // If current gcd value already exists in map if (mp.containsKey(gcd)) // Update the minimum cost // to get the current gcd mp.put(gcd, Math.min(mp.get(gcd), it.getValue() + cost[i])); else mp.put(gcd,it.getValue() + cost[i]); } } // If there can be no sub-set such that // the gcd of all the elements is 1 if (!mp.containsKey(1)) return -1; else return mp.get(1);}static int __gcd(int a, int b) { return b == 0? a:__gcd(b, a % b); }// Driver codepublic static void main(String[] args){ int arr[] = { 5, 10, 12, 1 }; int cost[] = { 2, 1, 2, 6 }; int n = arr.length; System.out.print(getMinCost(arr, n, cost));}} // This code is contributed by PrinciRaj1992", "e": 29859, "s": 28490, "text": null }, { "code": "# Python3 implementation of the approachfrom math import gcd as __gcd # Function to return the minimum cost requireddef getMinCost(arr, n, cost): # Map to store <gcd, cost> pair where # cost is the cost to get the current gcd mp = dict() mp[0] = 0 for i in range(n): for it in list(mp): gcd = __gcd(arr[i], it) # If current gcd value # already exists in map if (gcd in mp): # Update the minimum cost # to get the current gcd mp[gcd] = min(mp[gcd], mp[it] + cost[i]) else: mp[gcd] = mp[it] + cost[i] # If there can be no sub-set such that # the gcd of all the elements is 1 if (mp[1] == 0): return -1 else: return mp[1] # Driver codearr = [ 5, 10, 12, 1]cost = [ 2, 1, 2, 6]n = len(arr) print(getMinCost(arr, n, cost)) # This code is contributed by Mohit Kumar", "e": 30817, "s": 29859, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections.Generic;using System.Linq;class GFG{ static int __gcd(int a, int b) { return b == 0? a:__gcd(b, a % b); } // Function to return the minimum cost required static int getMinCost(int[] arr, int n, int[] cost) { // Map to store <gcd, cost> pair where // cost is the cost to get the current gcd Dictionary<int, int> mp = new Dictionary<int, int>(); mp.Add(0, 0); for (int i = 0; i < n; i++) { foreach (int it in mp.Keys.ToList()) { int gcd = __gcd(arr[i], it); // If current gcd value already exists in map if(mp.ContainsKey(gcd)) { // Update the minimum cost // to get the current gcd mp[gcd] = Math.Min(mp[gcd], mp[it] + cost[i]); } else { mp.Add(gcd, mp[it] + cost[i]); } } } // If there can be no sub-set such that // the gcd of all the elements is 1 if (mp[1] == 0) { return -1; } else { return mp[1]; } } // Driver code static public void Main () { int[] arr = { 5, 10, 12, 1 }; int[] cost = { 2, 1, 2, 6 }; int n = arr.Length; Console.WriteLine(getMinCost(arr, n, cost)); }} // This code is contributed by avanitrachhadiya2155", "e": 32132, "s": 30817, "text": null }, { "code": "<script> // JavaScript implementation of the approach // Function to return the minimum cost requiredfunction getMinCost(arr,n,cost){ // Map to store <gcd, cost> pair where // cost is the cost to get the current gcd let mp = new Map(); mp.set(0, 0); for (let i = 0; i < n; i++) { for (let [key, value] of mp.entries()){ let gcd = __gcd(arr[i], key); // If current gcd value already exists in map if (mp.has(gcd)) // Update the minimum cost // to get the current gcd mp.set(gcd, Math.min(mp.get(gcd), value + cost[i])); else mp.set(gcd,value + cost[i]); } } // If there can be no sub-set such that // the gcd of all the elements is 1 if (!mp.has(1)) return -1; else return mp.get(1);} function __gcd(a,b){ return b == 0? a:__gcd(b, a % b);} // Driver codelet arr=[5, 10, 12, 1 ];let cost=[2, 1, 2, 6 ];let n = arr.length;document.write(getMinCost(arr, n, cost)); // This code is contributed by unknown2108 </script>", "e": 33233, "s": 32132, "text": null }, { "code": null, "e": 33235, "s": 33233, "text": "4" }, { "code": null, "e": 33252, "s": 33237, "text": "mohit kumar 29" }, { "code": null, "e": 33266, "s": 33252, "text": "princiraj1992" }, { "code": null, "e": 33287, "s": 33266, "text": "avanitrachhadiya2155" }, { "code": null, "e": 33299, "s": 33287, "text": "unknown2108" }, { "code": null, "e": 33323, "s": 33299, "text": "Constructive Algorithms" }, { "code": null, "e": 33331, "s": 33323, "text": "cpp-map" }, { "code": null, "e": 33338, "s": 33331, "text": "Google" }, { "code": null, "e": 33349, "s": 33338, "text": "Algorithms" }, { "code": null, "e": 33354, "s": 33349, "text": "Hash" }, { "code": null, "e": 33361, "s": 33354, "text": "Google" }, { "code": null, "e": 33366, "s": 33361, "text": "Hash" }, { "code": null, "e": 33377, "s": 33366, "text": "Algorithms" }, { "code": null, "e": 33475, "s": 33377, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33524, "s": 33475, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 33549, "s": 33524, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 33577, "s": 33549, "text": "How to write a Pseudo Code?" }, { "code": null, "e": 33628, "s": 33577, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 33655, "s": 33628, "text": "Introduction to Algorithms" }, { "code": null, "e": 33691, "s": 33655, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 33722, "s": 33691, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 33756, "s": 33722, "text": "Hashing | Set 3 (Open Addressing)" }, { "code": null, "e": 33792, "s": 33756, "text": "Hashing | Set 2 (Separate Chaining)" } ]
Schedule Python Script using Windows Scheduler
24 Feb, 2021 In this article, we are going to schedule a python script using a windows task scheduler, i.e. make it launch automatically at a certain time or after a certain time period. Before starting we need to know the following point: Python Script: It is a bunch of python code meant to be directly executed by the user from the command line. Most of these are automation scripts, meant to automate certain tasks. These usually contain a few lines of code. Windows Scheduler: Windows Task Scheduler is a Microsoft Windows component or program which gives the user ability to schedule certain scripts or programs and automatically launch them at a certain time. It is used majorly to automate certain tasks like daily planners, monthly data scraping, etc. Step 1: Make a python script First, we’ll make the python script that we want to schedule. If you have already made the script, skip this section. If not, you can make your own python script or follow mine. Here we made a python script that fetches a random inspirational quote image from a folder where I’ve saved a couple of them and displays it. You’ll need the following python packages/modules: tkinter, PIL, os, random. Python3 # Python3 script to display# random image quotes from a folder # Importing modulesfrom tkinter import *from PIL import ImageTk, Imageimport osimport random # Getting the file name of# random selected imagename = random.choice(os.listdir( "C:\\Users\\NEERAJ RANA\\Desktop\\quotes_folder\\")) # Appending the rest of the path# to the filenamefile = "C:\\Users\\NEERAJ RANA\\Desktop\\quotes_folder\\" + name # Displaying the imageroot = Tk()canvas = Canvas(root, width=1300, height=750)canvas.pack()img = ImageTk.PhotoImage(Image.open(file))canvas.create_image(20, 20, anchor=NW, image=img)root.mainloop() Remember to change the folder path according to the folder location on your system. Now, there are two ways to schedule the script. The first method involves making a batch file, the other does not. If you don’t want to make a batch file, you can skip stepping 3. Step 2(Optional): Make a batch file A batch file is used to execute commands with the command prompt. It contains a series of commands in plain text you would normally use in the command prompt and is generally used to execute programs. We are going to make a batch file to run our python script. First, open up any text editor.Next, enter the following lines in an empty file: First, open up any text editor. Next, enter the following lines in an empty file: "C:\Python38\python.exe" "C:\Users\NEERAJ RANA\Desktop\GFG_Articles\scheduler\quote.py" pause The first string is the path to the python executable on your machine and the second one is the path to your saved python script. If you don’t know the path to your python executable, open up a command prompt and enter the following command: where python. where command If you see multiple paths, use any one of them. Also, change the path to your saved python script according to your system. The pause command is used to suspend the processing of the batch program and wait for the user’s input. And lastly, save this file with a .bat extension. Step 3: Scheduling the script Open up the Task Scheduler application. It should look something like this: Click “Create Basic Task...” in the Actions tab on the right. Enter a suitable name and description to the task in the given fields and click next. Choose the frequency with which you want to want your task to be executed. You can choose between daily, weekly, monthly, etc and then click next. Choose the start date and time when you want the task to be triggered. Also, choose after how many days you want the task to repeat/recur and click next. Choose “Start a program” in “What task do you want to perform?” and click next. If you made a batch file in step 2, just enter the path to the batch file in the program/script section. If you skipped step 2, enter the path to the python executable in the program/script section and enter the path to your python script file in the “Add arguments (optional)” section. If your script has some dependencies installed in some folder, like browser executable, you can include the folder path in the “Start in (optional)” section and click next. If you made a batch file If you didn’t make a batch file 8: Lastly, check all the entered values and click finish. Now, at your chosen time, your script will execute. Picked python-utility 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 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": "\n24 Feb, 2021" }, { "code": null, "e": 228, "s": 54, "text": "In this article, we are going to schedule a python script using a windows task scheduler, i.e. make it launch automatically at a certain time or after a certain time period." }, { "code": null, "e": 281, "s": 228, "text": "Before starting we need to know the following point:" }, { "code": null, "e": 504, "s": 281, "text": "Python Script: It is a bunch of python code meant to be directly executed by the user from the command line. Most of these are automation scripts, meant to automate certain tasks. These usually contain a few lines of code." }, { "code": null, "e": 802, "s": 504, "text": "Windows Scheduler: Windows Task Scheduler is a Microsoft Windows component or program which gives the user ability to schedule certain scripts or programs and automatically launch them at a certain time. It is used majorly to automate certain tasks like daily planners, monthly data scraping, etc." }, { "code": null, "e": 831, "s": 802, "text": "Step 1: Make a python script" }, { "code": null, "e": 1009, "s": 831, "text": "First, we’ll make the python script that we want to schedule. If you have already made the script, skip this section. If not, you can make your own python script or follow mine." }, { "code": null, "e": 1228, "s": 1009, "text": "Here we made a python script that fetches a random inspirational quote image from a folder where I’ve saved a couple of them and displays it. You’ll need the following python packages/modules: tkinter, PIL, os, random." }, { "code": null, "e": 1236, "s": 1228, "text": "Python3" }, { "code": "# Python3 script to display# random image quotes from a folder # Importing modulesfrom tkinter import *from PIL import ImageTk, Imageimport osimport random # Getting the file name of# random selected imagename = random.choice(os.listdir( \"C:\\\\Users\\\\NEERAJ RANA\\\\Desktop\\\\quotes_folder\\\\\")) # Appending the rest of the path# to the filenamefile = \"C:\\\\Users\\\\NEERAJ RANA\\\\Desktop\\\\quotes_folder\\\\\" + name # Displaying the imageroot = Tk()canvas = Canvas(root, width=1300, height=750)canvas.pack()img = ImageTk.PhotoImage(Image.open(file))canvas.create_image(20, 20, anchor=NW, image=img)root.mainloop()", "e": 1846, "s": 1236, "text": null }, { "code": null, "e": 1930, "s": 1846, "text": "Remember to change the folder path according to the folder location on your system." }, { "code": null, "e": 2110, "s": 1930, "text": "Now, there are two ways to schedule the script. The first method involves making a batch file, the other does not. If you don’t want to make a batch file, you can skip stepping 3." }, { "code": null, "e": 2146, "s": 2110, "text": "Step 2(Optional): Make a batch file" }, { "code": null, "e": 2347, "s": 2146, "text": "A batch file is used to execute commands with the command prompt. It contains a series of commands in plain text you would normally use in the command prompt and is generally used to execute programs." }, { "code": null, "e": 2407, "s": 2347, "text": "We are going to make a batch file to run our python script." }, { "code": null, "e": 2488, "s": 2407, "text": "First, open up any text editor.Next, enter the following lines in an empty file:" }, { "code": null, "e": 2520, "s": 2488, "text": "First, open up any text editor." }, { "code": null, "e": 2570, "s": 2520, "text": "Next, enter the following lines in an empty file:" }, { "code": null, "e": 2664, "s": 2570, "text": "\"C:\\Python38\\python.exe\" \"C:\\Users\\NEERAJ RANA\\Desktop\\GFG_Articles\\scheduler\\quote.py\"\npause" }, { "code": null, "e": 2920, "s": 2664, "text": "The first string is the path to the python executable on your machine and the second one is the path to your saved python script. If you don’t know the path to your python executable, open up a command prompt and enter the following command: where python." }, { "code": null, "e": 2934, "s": 2920, "text": "where command" }, { "code": null, "e": 3212, "s": 2934, "text": "If you see multiple paths, use any one of them. Also, change the path to your saved python script according to your system. The pause command is used to suspend the processing of the batch program and wait for the user’s input. And lastly, save this file with a .bat extension." }, { "code": null, "e": 3242, "s": 3212, "text": "Step 3: Scheduling the script" }, { "code": null, "e": 3318, "s": 3242, "text": "Open up the Task Scheduler application. It should look something like this:" }, { "code": null, "e": 3380, "s": 3318, "text": "Click “Create Basic Task...” in the Actions tab on the right." }, { "code": null, "e": 3466, "s": 3380, "text": "Enter a suitable name and description to the task in the given fields and click next." }, { "code": null, "e": 3613, "s": 3466, "text": "Choose the frequency with which you want to want your task to be executed. You can choose between daily, weekly, monthly, etc and then click next." }, { "code": null, "e": 3767, "s": 3613, "text": "Choose the start date and time when you want the task to be triggered. Also, choose after how many days you want the task to repeat/recur and click next." }, { "code": null, "e": 3847, "s": 3767, "text": "Choose “Start a program” in “What task do you want to perform?” and click next." }, { "code": null, "e": 4134, "s": 3847, "text": "If you made a batch file in step 2, just enter the path to the batch file in the program/script section. If you skipped step 2, enter the path to the python executable in the program/script section and enter the path to your python script file in the “Add arguments (optional)” section." }, { "code": null, "e": 4307, "s": 4134, "text": "If your script has some dependencies installed in some folder, like browser executable, you can include the folder path in the “Start in (optional)” section and click next." }, { "code": null, "e": 4332, "s": 4307, "text": "If you made a batch file" }, { "code": null, "e": 4364, "s": 4332, "text": "If you didn’t make a batch file" }, { "code": null, "e": 4422, "s": 4364, "text": "8: Lastly, check all the entered values and click finish." }, { "code": null, "e": 4474, "s": 4422, "text": "Now, at your chosen time, your script will execute." }, { "code": null, "e": 4481, "s": 4474, "text": "Picked" }, { "code": null, "e": 4496, "s": 4481, "text": "python-utility" }, { "code": null, "e": 4503, "s": 4496, "text": "Python" }, { "code": null, "e": 4601, "s": 4503, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4633, "s": 4601, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4660, "s": 4633, "text": "Python Classes and Objects" }, { "code": null, "e": 4681, "s": 4660, "text": "Python OOPs Concepts" }, { "code": null, "e": 4704, "s": 4681, "text": "Introduction To PYTHON" }, { "code": null, "e": 4760, "s": 4704, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 4791, "s": 4760, "text": "Python | os.path.join() method" }, { "code": null, "e": 4833, "s": 4791, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 4875, "s": 4833, "text": "Check if element exists in list in Python" }, { "code": null, "e": 4914, "s": 4875, "text": "Python | datetime.timedelta() function" } ]
Number of matches required to find the winner
13 Apr, 2021 Given a number N which represent the number of players participating in Badminton match. The task is to determine the Number of matches required to determine the Winner. In each Match 1 player is knocked out. Examples: Input: N = 4 Output: Matches played = 3 (As after each match only N - 1 players left) Input: N = 9 Output: Matches played = 8 Approach: Since, after each match one player is knocked out. So to get the winner, n-1 players should be knocked out and for which n-1 matches to be played. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function that will tell// no. of matches requiredint noOfMatches(int N){ return N - 1;} // Driver codeint main(){ int N = 8; cout << "Matches played = " << noOfMatches(N); return 0;} // Java implementation of above approachimport java.io.*; class GFG{ // Function that will tell// no. of matches requiredstatic int noOfMatches(int N){ return N - 1;} // Driver codepublic static void main (String[] args){ int N = 8; System.out.println ("Matches played = " + noOfMatches(N));}} // This code is contributed by jit_t # Python 3 implementation of# above approach # Function that will tell# no. of matches requireddef noOfMatches(N) : return N - 1 # Driver codeif __name__ == "__main__" : N = 8 print("Matches played =", noOfMatches(N)) # This code is contributed# by ANKITRAI1 //C# implementation of above approachusing System; public class GFG{ // Function that will tell// no. of matches requiredstatic int noOfMatches(int N){ return N - 1;} // Driver code static public void Main (){ int N = 8; Console.WriteLine("Matches played = " + noOfMatches(N));}} // This code is contributed by ajit <?php// PHP implementation of above approach // Function that will tell// no. of matches requiredfunction noOfMatches($N){ return ($N - 1);} // Driver code$N = 8;echo "Matches played = ", noOfMatches($N); // This code is contributed by akt_mit?> <script> // Javascript implementation of above approach // Function that will tell// no. of matches requiredfunction noOfMatches(N){ return N - 1;} // Driver codevar N = 8; document.write("Matches played = " + noOfMatches(N)); // This code is contributed by rutvik_56 </script> Matches played = 7 jit_t ankthon rutvik_56 School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction To PYTHON Interfaces in Java Operator Overloading in C++ Polymorphism in C++ Types of Operating Systems Constructors in C++ Constructors in Java Exceptions in Java Different Methods to Reverse a String in C++ Python program to check if a string is palindrome or not
[ { "code": null, "e": 53, "s": 25, "text": "\n13 Apr, 2021" }, { "code": null, "e": 262, "s": 53, "text": "Given a number N which represent the number of players participating in Badminton match. The task is to determine the Number of matches required to determine the Winner. In each Match 1 player is knocked out." }, { "code": null, "e": 273, "s": 262, "text": "Examples: " }, { "code": null, "e": 401, "s": 273, "text": "Input: N = 4\nOutput: Matches played = 3\n(As after each match only N - 1 players left)\n\nInput: N = 9\nOutput: Matches played = 8" }, { "code": null, "e": 558, "s": 401, "text": "Approach: Since, after each match one player is knocked out. So to get the winner, n-1 players should be knocked out and for which n-1 matches to be played." }, { "code": null, "e": 609, "s": 558, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 613, "s": 609, "text": "C++" }, { "code": null, "e": 618, "s": 613, "text": "Java" }, { "code": null, "e": 626, "s": 618, "text": "Python3" }, { "code": null, "e": 629, "s": 626, "text": "C#" }, { "code": null, "e": 633, "s": 629, "text": "PHP" }, { "code": null, "e": 644, "s": 633, "text": "Javascript" }, { "code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function that will tell// no. of matches requiredint noOfMatches(int N){ return N - 1;} // Driver codeint main(){ int N = 8; cout << \"Matches played = \" << noOfMatches(N); return 0;}", "e": 928, "s": 644, "text": null }, { "code": "// Java implementation of above approachimport java.io.*; class GFG{ // Function that will tell// no. of matches requiredstatic int noOfMatches(int N){ return N - 1;} // Driver codepublic static void main (String[] args){ int N = 8; System.out.println (\"Matches played = \" + noOfMatches(N));}} // This code is contributed by jit_t", "e": 1297, "s": 928, "text": null }, { "code": "# Python 3 implementation of# above approach # Function that will tell# no. of matches requireddef noOfMatches(N) : return N - 1 # Driver codeif __name__ == \"__main__\" : N = 8 print(\"Matches played =\", noOfMatches(N)) # This code is contributed# by ANKITRAI1", "e": 1581, "s": 1297, "text": null }, { "code": "//C# implementation of above approachusing System; public class GFG{ // Function that will tell// no. of matches requiredstatic int noOfMatches(int N){ return N - 1;} // Driver code static public void Main (){ int N = 8; Console.WriteLine(\"Matches played = \" + noOfMatches(N));}} // This code is contributed by ajit", "e": 1950, "s": 1581, "text": null }, { "code": "<?php// PHP implementation of above approach // Function that will tell// no. of matches requiredfunction noOfMatches($N){ return ($N - 1);} // Driver code$N = 8;echo \"Matches played = \", noOfMatches($N); // This code is contributed by akt_mit?>", "e": 2207, "s": 1950, "text": null }, { "code": "<script> // Javascript implementation of above approach // Function that will tell// no. of matches requiredfunction noOfMatches(N){ return N - 1;} // Driver codevar N = 8; document.write(\"Matches played = \" + noOfMatches(N)); // This code is contributed by rutvik_56 </script>", "e": 2517, "s": 2207, "text": null }, { "code": null, "e": 2536, "s": 2517, "text": "Matches played = 7" }, { "code": null, "e": 2544, "s": 2538, "text": "jit_t" }, { "code": null, "e": 2552, "s": 2544, "text": "ankthon" }, { "code": null, "e": 2562, "s": 2552, "text": "rutvik_56" }, { "code": null, "e": 2581, "s": 2562, "text": "School Programming" }, { "code": null, "e": 2679, "s": 2581, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2702, "s": 2679, "text": "Introduction To PYTHON" }, { "code": null, "e": 2721, "s": 2702, "text": "Interfaces in Java" }, { "code": null, "e": 2749, "s": 2721, "text": "Operator Overloading in C++" }, { "code": null, "e": 2769, "s": 2749, "text": "Polymorphism in C++" }, { "code": null, "e": 2796, "s": 2769, "text": "Types of Operating Systems" }, { "code": null, "e": 2816, "s": 2796, "text": "Constructors in C++" }, { "code": null, "e": 2837, "s": 2816, "text": "Constructors in Java" }, { "code": null, "e": 2856, "s": 2837, "text": "Exceptions in Java" }, { "code": null, "e": 2901, "s": 2856, "text": "Different Methods to Reverse a String in C++" } ]
Clockwise/Spiral Rule in C/C++ with Examples
22 Sep, 2021 The Spiral/Clockwise Method is a magic tool for C/C++ programmers to define the meaning of syntax declaration in the head within seconds. This method was created by David Anderson and here is a short brief about how to apply this method. While coding, when someone comes across a new unwanted syntax declaration: string(const** f(int, void (*const p)(int)))(char[]); The question here arises is what is the meaning of the function name “f”? There is an infamous way that will help one to deduce the meaning of this function “f” in seconds. Approach: Step 1: Consider this Clockwise-spiral. Step 2: Replace O with a. Step3: Now, along the clockwise path, replace “|” with some words and try to get the meaning of syntax, and replace “|” with “(“. The round brackets explain its function and say “‘a’ is a function”. Step 4: Consider seeing what is inside of the round brackets/function, so the open brackets (remember like from precedence of operators, brackets are always opened first) and go from left to right until the end of round brackets “)” are encountered. It can be said that “‘a’ is a function with the integer ‘x’ as an argument”. Step 5: Now come back to the first round bracket and continue the spiral path from “(“. Replace “|” with “*”. This means a return value and pointer. Here “‘a’ is a function with the integer ‘x’ as an argument which returns a pointer to “. Step 6: Continue the spiral clockwise. One will encounter “int” which was already dealt with, so continue the spiral path. Step 7: Replace “|” with “int”. It can be said that “‘a’ is a function with the integer ‘x’ as an argument which returns a pointer to an integer”. Step 8: Again, continue this path and one will get “;” which means this is the end of the statement, and see that’s how the meaning of syntax can be defined easily. Finally, it can be said that “‘a’ is a function with an integer ‘x’ as an argument which returns a pointer to the integer”. Answer: f is a function with arguments as int and p a function with the argument as int, returning a constant pointer to nothing (void) returning a pointer to a pointer to a constant function with the character array as an argument returning a string. Important Points: Syntax Explanations:A[ ]: array A is of undefined size and A[ 5 ] means the size of array is 5.(type 1,type 2): function passing type1 and type2.*: pointer to.Start with the variable name.Keep this reading until all modifiers in the variable declaration are overwritten.Always complete any content in parentheses first.Keep doing this in a spiral/clockwise direction until all tokens have been covered. Syntax Explanations:A[ ]: array A is of undefined size and A[ 5 ] means the size of array is 5.(type 1,type 2): function passing type1 and type2.*: pointer to. A[ ]: array A is of undefined size and A[ 5 ] means the size of array is 5. (type 1,type 2): function passing type1 and type2. *: pointer to. Start with the variable name. Keep this reading until all modifiers in the variable declaration are overwritten. Always complete any content in parentheses first. Keep doing this in a spiral/clockwise direction until all tokens have been covered. Example:Consider an example by visualizing a spiral in the brain: (char const *p) ( int , const (int *)*); Remember the thumb rule. Always start with the name of a variable. Starting from a variable p clockwise spiral. Step 1: ‘p’ is the variable. p Step 2: ‘p’ is a variable that is a pointer to. p -> * Step 3: ‘p’ is a variable that is a pointer to a function. p -> * -> ( Step 4: ‘p’ is a variable that is a pointer to a function with int as an argument. p -> * -> ( -> int Step 5: For the next step, there is no variable name, so give one. Let it be ‘a’. So the expression can be written as: (char const *p) ( int , const (int *)* a ); Step 6: Here ‘a’ is a variable. a Step 7: Closed round bracket doesn’t tell anything, so continue. a-> ) Step 8: In the next step, a is a variable pointer to. a -> ) -> * Step 9: Ignore the semicolon because the syntax definition is not complete, so continue. a -> ) -> * -> ; Step 10: The closed round bracket doesn’t tell anything, so continue. a -> ) -> * -> ; -> ) Step 11: Now ‘a’ is a variable pointer to pointer. a -> ) -> * -> ; -> ) -> * Step 12: ‘a’ is a variable pointer to pointer int. a -> ) -> * -> ; -> ) -> * -> int Step 13: ‘a’ is a variable pointer to pointer int constant. a -> ) -> * -> ; -> ) -> * -> int -> const Let’s get back to where defining ‘p’ was left. Step 14: ‘p’ is a variable that is a pointer to a function with int as an argument and a variable pointer to the pointer int constant which returns a constant. p -> * -> ( -> int , const... -> const Note: The reused terms already used for defining syntax are being ignored here. Step 15: p is a variable that is a pointer to a function with int as argument and a variable pointer to pointer int constant which returns a constant character. p -> * -> ( -> int , const... -> const->char This finishes the complete meaning of the syntax. Note:There is an exception to this rule when syntax has arrays (especially multidimensional arrays), so there is an update to this rule. When an array is encountered, move to the most-right closing square bracket and treat the array as one ‘sweep’ “ Example: int *a[10][]: ‘a’ is a multidimensional array of size 10 and an undefined size of pointers to int. int *a[10][]: ‘a’ is a multidimensional array of size 10 and an undefined size of pointers to int. simplekind C-Pointers cpp-pointer C Language C++ How To CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Unordered Sets in C++ Standard Template Library Operators in C / C++ Exception Handling in C++ What is the purpose of a function prototype? TCP Server-Client implementation in C Vector in C++ STL Map in C++ Standard Template Library (STL) Initialize a vector in C++ (7 different ways) Set in C++ Standard Template Library (STL) Priority Queue in C++ Standard Template Library (STL)
[ { "code": null, "e": 54, "s": 26, "text": "\n22 Sep, 2021" }, { "code": null, "e": 292, "s": 54, "text": "The Spiral/Clockwise Method is a magic tool for C/C++ programmers to define the meaning of syntax declaration in the head within seconds. This method was created by David Anderson and here is a short brief about how to apply this method." }, { "code": null, "e": 367, "s": 292, "text": "While coding, when someone comes across a new unwanted syntax declaration:" }, { "code": null, "e": 421, "s": 367, "text": "string(const** f(int, void (*const p)(int)))(char[]);" }, { "code": null, "e": 594, "s": 421, "text": "The question here arises is what is the meaning of the function name “f”? There is an infamous way that will help one to deduce the meaning of this function “f” in seconds." }, { "code": null, "e": 604, "s": 594, "text": "Approach:" }, { "code": null, "e": 644, "s": 604, "text": "Step 1: Consider this Clockwise-spiral." }, { "code": null, "e": 670, "s": 644, "text": "Step 2: Replace O with a." }, { "code": null, "e": 870, "s": 670, "text": "Step3: Now, along the clockwise path, replace “|” with some words and try to get the meaning of syntax, and replace “|” with “(“. The round brackets explain its function and say “‘a’ is a function”. " }, { "code": null, "e": 1198, "s": 870, "text": "Step 4: Consider seeing what is inside of the round brackets/function, so the open brackets (remember like from precedence of operators, brackets are always opened first) and go from left to right until the end of round brackets “)” are encountered. It can be said that “‘a’ is a function with the integer ‘x’ as an argument”." }, { "code": null, "e": 1437, "s": 1198, "text": "Step 5: Now come back to the first round bracket and continue the spiral path from “(“. Replace “|” with “*”. This means a return value and pointer. Here “‘a’ is a function with the integer ‘x’ as an argument which returns a pointer to “." }, { "code": null, "e": 1560, "s": 1437, "text": "Step 6: Continue the spiral clockwise. One will encounter “int” which was already dealt with, so continue the spiral path." }, { "code": null, "e": 1707, "s": 1560, "text": "Step 7: Replace “|” with “int”. It can be said that “‘a’ is a function with the integer ‘x’ as an argument which returns a pointer to an integer”." }, { "code": null, "e": 1872, "s": 1707, "text": "Step 8: Again, continue this path and one will get “;” which means this is the end of the statement, and see that’s how the meaning of syntax can be defined easily." }, { "code": null, "e": 1996, "s": 1872, "text": "Finally, it can be said that “‘a’ is a function with an integer ‘x’ as an argument which returns a pointer to the integer”." }, { "code": null, "e": 2248, "s": 1996, "text": "Answer: f is a function with arguments as int and p a function with the argument as int, returning a constant pointer to nothing (void) returning a pointer to a pointer to a constant function with the character array as an argument returning a string." }, { "code": null, "e": 2266, "s": 2248, "text": "Important Points:" }, { "code": null, "e": 2669, "s": 2266, "text": "Syntax Explanations:A[ ]: array A is of undefined size and A[ 5 ] means the size of array is 5.(type 1,type 2): function passing type1 and type2.*: pointer to.Start with the variable name.Keep this reading until all modifiers in the variable declaration are overwritten.Always complete any content in parentheses first.Keep doing this in a spiral/clockwise direction until all tokens have been covered." }, { "code": null, "e": 2829, "s": 2669, "text": "Syntax Explanations:A[ ]: array A is of undefined size and A[ 5 ] means the size of array is 5.(type 1,type 2): function passing type1 and type2.*: pointer to." }, { "code": null, "e": 2905, "s": 2829, "text": "A[ ]: array A is of undefined size and A[ 5 ] means the size of array is 5." }, { "code": null, "e": 2956, "s": 2905, "text": "(type 1,type 2): function passing type1 and type2." }, { "code": null, "e": 2971, "s": 2956, "text": "*: pointer to." }, { "code": null, "e": 3001, "s": 2971, "text": "Start with the variable name." }, { "code": null, "e": 3084, "s": 3001, "text": "Keep this reading until all modifiers in the variable declaration are overwritten." }, { "code": null, "e": 3134, "s": 3084, "text": "Always complete any content in parentheses first." }, { "code": null, "e": 3218, "s": 3134, "text": "Keep doing this in a spiral/clockwise direction until all tokens have been covered." }, { "code": null, "e": 3284, "s": 3218, "text": "Example:Consider an example by visualizing a spiral in the brain:" }, { "code": null, "e": 3326, "s": 3284, "text": "(char const *p) ( int , const (int *)*);" }, { "code": null, "e": 3438, "s": 3326, "text": "Remember the thumb rule. Always start with the name of a variable. Starting from a variable p clockwise spiral." }, { "code": null, "e": 3467, "s": 3438, "text": "Step 1: ‘p’ is the variable." }, { "code": null, "e": 3515, "s": 3467, "text": "p " }, { "code": null, "e": 3563, "s": 3515, "text": "Step 2: ‘p’ is a variable that is a pointer to." }, { "code": null, "e": 3607, "s": 3563, "text": "p -> * " }, { "code": null, "e": 3666, "s": 3607, "text": "Step 3: ‘p’ is a variable that is a pointer to a function." }, { "code": null, "e": 3708, "s": 3666, "text": "p -> * -> ( " }, { "code": null, "e": 3791, "s": 3708, "text": "Step 4: ‘p’ is a variable that is a pointer to a function with int as an argument." }, { "code": null, "e": 3827, "s": 3791, "text": "p -> * -> ( -> int " }, { "code": null, "e": 3946, "s": 3827, "text": "Step 5: For the next step, there is no variable name, so give one. Let it be ‘a’. So the expression can be written as:" }, { "code": null, "e": 3991, "s": 3946, "text": "(char const *p) ( int , const (int *)* a );" }, { "code": null, "e": 4024, "s": 3991, "text": "Step 6: Here ‘a’ is a variable. " }, { "code": null, "e": 4031, "s": 4024, "text": "a " }, { "code": null, "e": 4096, "s": 4031, "text": "Step 7: Closed round bracket doesn’t tell anything, so continue." }, { "code": null, "e": 4128, "s": 4096, "text": "a-> ) " }, { "code": null, "e": 4182, "s": 4128, "text": "Step 8: In the next step, a is a variable pointer to." }, { "code": null, "e": 4200, "s": 4182, "text": "a -> ) -> * " }, { "code": null, "e": 4289, "s": 4200, "text": "Step 9: Ignore the semicolon because the syntax definition is not complete, so continue." }, { "code": null, "e": 4309, "s": 4289, "text": "a -> ) -> * -> ; " }, { "code": null, "e": 4379, "s": 4309, "text": "Step 10: The closed round bracket doesn’t tell anything, so continue." }, { "code": null, "e": 4402, "s": 4379, "text": "a -> ) -> * -> ; -> )" }, { "code": null, "e": 4453, "s": 4402, "text": "Step 11: Now ‘a’ is a variable pointer to pointer." }, { "code": null, "e": 4551, "s": 4453, "text": "a -> ) -> * -> ; -> ) -> * " }, { "code": null, "e": 4602, "s": 4551, "text": "Step 12: ‘a’ is a variable pointer to pointer int." }, { "code": null, "e": 4658, "s": 4602, "text": "a -> ) -> * -> ; -> ) -> * -> int " }, { "code": null, "e": 4718, "s": 4658, "text": "Step 13: ‘a’ is a variable pointer to pointer int constant." }, { "code": null, "e": 4767, "s": 4718, "text": "a -> ) -> * -> ; -> ) -> * -> int -> const " }, { "code": null, "e": 4814, "s": 4767, "text": "Let’s get back to where defining ‘p’ was left." }, { "code": null, "e": 4974, "s": 4814, "text": "Step 14: ‘p’ is a variable that is a pointer to a function with int as an argument and a variable pointer to the pointer int constant which returns a constant." }, { "code": null, "e": 5015, "s": 4974, "text": "p -> * -> ( -> int , const... -> const" }, { "code": null, "e": 5095, "s": 5015, "text": "Note: The reused terms already used for defining syntax are being ignored here." }, { "code": null, "e": 5256, "s": 5095, "text": "Step 15: p is a variable that is a pointer to a function with int as argument and a variable pointer to pointer int constant which returns a constant character." }, { "code": null, "e": 5303, "s": 5256, "text": "p -> * -> ( -> int , const... -> const->char" }, { "code": null, "e": 5353, "s": 5303, "text": "This finishes the complete meaning of the syntax." }, { "code": null, "e": 5490, "s": 5353, "text": "Note:There is an exception to this rule when syntax has arrays (especially multidimensional arrays), so there is an update to this rule." }, { "code": null, "e": 5603, "s": 5490, "text": "When an array is encountered, move to the most-right closing square bracket and treat the array as one ‘sweep’ “" }, { "code": null, "e": 5711, "s": 5603, "text": "Example: int *a[10][]: ‘a’ is a multidimensional array of size 10 and an undefined size of pointers to int." }, { "code": null, "e": 5810, "s": 5711, "text": "int *a[10][]: ‘a’ is a multidimensional array of size 10 and an undefined size of pointers to int." }, { "code": null, "e": 5821, "s": 5810, "text": "simplekind" }, { "code": null, "e": 5832, "s": 5821, "text": "C-Pointers" }, { "code": null, "e": 5844, "s": 5832, "text": "cpp-pointer" }, { "code": null, "e": 5855, "s": 5844, "text": "C Language" }, { "code": null, "e": 5859, "s": 5855, "text": "C++" }, { "code": null, "e": 5866, "s": 5859, "text": "How To" }, { "code": null, "e": 5870, "s": 5866, "text": "CPP" }, { "code": null, "e": 5968, "s": 5870, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6016, "s": 5968, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 6037, "s": 6016, "text": "Operators in C / C++" }, { "code": null, "e": 6063, "s": 6037, "text": "Exception Handling in C++" }, { "code": null, "e": 6108, "s": 6063, "text": "What is the purpose of a function prototype?" }, { "code": null, "e": 6146, "s": 6108, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 6164, "s": 6146, "text": "Vector in C++ STL" }, { "code": null, "e": 6207, "s": 6164, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 6253, "s": 6207, "text": "Initialize a vector in C++ (7 different ways)" }, { "code": null, "e": 6296, "s": 6253, "text": "Set in C++ Standard Template Library (STL)" } ]
Classification Algorithms - Decision Tree
In general, Decision tree analysis is a predictive modelling tool that can be applied across many areas. Decision trees can be constructed by an algorithmic approach that can split the dataset in different ways based on different conditions. Decisions tress are the most powerful algorithms that falls under the category of supervised algorithms. They can be used for both classification and regression tasks. The two main entities of a tree are decision nodes, where the data is split and leaves, where we got outcome. The example of a binary tree for predicting whether a person is fit or unfit providing various information like age, eating habits and exercise habits, is given below − In the above decision tree, the question are decision nodes and final outcomes are leaves. We have the following two types of decision trees − Classification decision trees − In this kind of decision trees, the decision variable is categorical. The above decision tree is an example of classification decision tree. Classification decision trees − In this kind of decision trees, the decision variable is categorical. The above decision tree is an example of classification decision tree. Regression decision trees − In this kind of decision trees, the decision variable is continuous. Regression decision trees − In this kind of decision trees, the decision variable is continuous. It is the name of the cost function that is used to evaluate the binary splits in the dataset and works with the categorial target variable “Success” or “Failure”. Higher the value of Gini index, higher the homogeneity. A perfect Gini index value is 0 and worst is 0.5 (for 2 class problem). Gini index for a split can be calculated with the help of following steps − First, calculate Gini index for sub-nodes by using the formula p^2+q^2 , which is the sum of the square of probability for success and failure. First, calculate Gini index for sub-nodes by using the formula p^2+q^2 , which is the sum of the square of probability for success and failure. Next, calculate Gini index for split using weighted Gini score of each node of that split. Next, calculate Gini index for split using weighted Gini score of each node of that split. Classification and Regression Tree (CART) algorithm uses Gini method to generate binary splits. A split is basically including an attribute in the dataset and a value. We can create a split in dataset with the help of following three parts − Part1: Calculating Gini Score − We have just discussed this part in the previous section. Part1: Calculating Gini Score − We have just discussed this part in the previous section. Part2: Splitting a dataset − It may be defined as separating a dataset into two lists of rows having index of an attribute and a split value of that attribute. After getting the two groups - right and left, from the dataset, we can calculate the value of split by using Gini score calculated in first part. Split value will decide in which group the attribute will reside. Part2: Splitting a dataset − It may be defined as separating a dataset into two lists of rows having index of an attribute and a split value of that attribute. After getting the two groups - right and left, from the dataset, we can calculate the value of split by using Gini score calculated in first part. Split value will decide in which group the attribute will reside. Part3: Evaluating all splits − Next part after finding Gini score and splitting dataset is the evaluation of all splits. For this purpose, first, we must check every value associated with each attribute as a candidate split. Then we need to find the best possible split by evaluating the cost of the split. The best split will be used as a node in the decision tree. Part3: Evaluating all splits − Next part after finding Gini score and splitting dataset is the evaluation of all splits. For this purpose, first, we must check every value associated with each attribute as a candidate split. Then we need to find the best possible split by evaluating the cost of the split. The best split will be used as a node in the decision tree. As we know that a tree has root node and terminal nodes. After creating the root node, we can build the tree by following two parts − While creating terminal nodes of decision tree, one important point is to decide when to stop growing tree or creating further terminal nodes. It can be done by using two criteria namely maximum tree depth and minimum node records as follows − Maximum Tree Depth − As name suggests, this is the maximum number of the nodes in a tree after root node. We must stop adding terminal nodes once a tree reached at maximum depth i.e. once a tree got maximum number of terminal nodes. Maximum Tree Depth − As name suggests, this is the maximum number of the nodes in a tree after root node. We must stop adding terminal nodes once a tree reached at maximum depth i.e. once a tree got maximum number of terminal nodes. Minimum Node Records − It may be defined as the minimum number of training patterns that a given node is responsible for. We must stop adding terminal nodes once tree reached at these minimum node records or below this minimum. Minimum Node Records − It may be defined as the minimum number of training patterns that a given node is responsible for. We must stop adding terminal nodes once tree reached at these minimum node records or below this minimum. Terminal node is used to make a final prediction. As we understood about when to create terminal nodes, now we can start building our tree. Recursive splitting is a method to build the tree. In this method, once a node is created, we can create the child nodes (nodes added to an existing node) recursively on each group of data, generated by splitting the dataset, by calling the same function again and again. After building a decision tree, we need to make a prediction about it. Basically, prediction involves navigating the decision tree with the specifically provided row of data. We can make a prediction with the help of recursive function, as did above. The same prediction routine is called again with the left or the child right nodes. The following are some of the assumptions we make while creating decision tree − While preparing decision trees, the training set is as root node. While preparing decision trees, the training set is as root node. Decision tree classifier prefers the features values to be categorical. In case if you want to use continuous values then they must be done discretized prior to model building. Decision tree classifier prefers the features values to be categorical. In case if you want to use continuous values then they must be done discretized prior to model building. Based on the attribute’s values, the records are recursively distributed. Based on the attribute’s values, the records are recursively distributed. Statistical approach will be used to place attributes at any node position i.e.as root node or internal node. Statistical approach will be used to place attributes at any node position i.e.as root node or internal node. In the following example, we are going to implement Decision Tree classifier on Pima Indian Diabetes − First, start with importing necessary python packages − import pandas as pd from sklearn.tree import DecisionTreeClassifier from sklearn.model_selection import train_test_split Next, download the iris dataset from its weblink as follows − col_names = ['pregnant', 'glucose', 'bp', 'skin', 'insulin', 'bmi', 'pedigree', 'age', 'label'] pima = pd.read_csv(r"C:\pima-indians-diabetes.csv", header=None, names=col_names) pima.head() pregnant glucose bp skin insulin bmi pedigree age label 0 6 148 72 35 0 33.6 0.627 50 1 1 1 85 66 29 0 26.6 0.351 31 0 2 8 183 64 0 0 23.3 0.672 32 1 3 1 89 66 23 94 28.1 0.167 21 0 4 0 137 40 35 168 43.1 2.288 33 1 Now, split the dataset into features and target variable as follows − feature_cols = ['pregnant', 'insulin', 'bmi', 'age','glucose','bp','pedigree'] X = pima[feature_cols] # Features y = pima.label # Target variable Next, we will divide the data into train and test split. The following code will split the dataset into 70% training data and 30% of testing data − X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1) Next, train the model with the help of DecisionTreeClassifier class of sklearn as follows − clf = DecisionTreeClassifier() clf = clf.fit(X_train,y_train) At last we need to make prediction. It can be done with the help of following script − y_pred = clf.predict(X_test) Next, we can get the accuracy score, confusion matrix and classification report as follows − from sklearn.metrics import classification_report, confusion_matrix, accuracy_score result = confusion_matrix(y_test, y_pred) print("Confusion Matrix:") print(result) result1 = classification_report(y_test, y_pred) print("Classification Report:",) print (result1) result2 = accuracy_score(y_test,y_pred) print("Accuracy:",result2) Confusion Matrix: [[116 30] [ 46 39]] Classification Report: precision recall f1-score support 0 0.72 0.79 0.75 146 1 0.57 0.46 0.51 85 micro avg 0.67 0.67 0.67 231 macro avg 0.64 0.63 0.63 231 weighted avg 0.66 0.67 0.66 231 Accuracy: 0.670995670995671 The above decision tree can be visualized with the help of following code − from sklearn.tree import export_graphviz from sklearn.externals.six import StringIO from IPython.display import Image import pydotplus dot_data = StringIO() export_graphviz(clf, out_file=dot_data, filled=True, rounded=True, special_characters=True,feature_names = feature_cols,class_names=['0','1']) graph = pydotplus.graph_from_dot_data(dot_data.getvalue())
[ { "code": null, "e": 2785, "s": 2438, "text": "In general, Decision tree analysis is a predictive modelling tool that can be applied across many areas. Decision trees can be constructed by an algorithmic approach that can split the dataset in different ways based on different conditions. Decisions tress are the most powerful algorithms that falls under the category of supervised algorithms." }, { "code": null, "e": 3127, "s": 2785, "text": "They can be used for both classification and regression tasks. The two main entities of a tree are decision nodes, where the data is split and leaves, where we got outcome. The example of a binary tree for predicting whether a person is fit or unfit providing various information like age, eating habits and exercise habits, is given below −" }, { "code": null, "e": 3270, "s": 3127, "text": "In the above decision tree, the question are decision nodes and final outcomes are leaves. We have the following two types of decision trees −" }, { "code": null, "e": 3443, "s": 3270, "text": "Classification decision trees − In this kind of decision trees, the decision variable is categorical. The above decision tree is an example of classification decision tree." }, { "code": null, "e": 3616, "s": 3443, "text": "Classification decision trees − In this kind of decision trees, the decision variable is categorical. The above decision tree is an example of classification decision tree." }, { "code": null, "e": 3713, "s": 3616, "text": "Regression decision trees − In this kind of decision trees, the decision variable is continuous." }, { "code": null, "e": 3810, "s": 3713, "text": "Regression decision trees − In this kind of decision trees, the decision variable is continuous." }, { "code": null, "e": 3974, "s": 3810, "text": "It is the name of the cost function that is used to evaluate the binary splits in the dataset and works with the categorial target variable “Success” or “Failure”." }, { "code": null, "e": 4178, "s": 3974, "text": "Higher the value of Gini index, higher the homogeneity. A perfect Gini index value is 0 and worst is 0.5 (for 2 class problem). Gini index for a split can be calculated with the help of following steps −" }, { "code": null, "e": 4322, "s": 4178, "text": "First, calculate Gini index for sub-nodes by using the formula p^2+q^2 , which is the sum of the square of probability for success and failure." }, { "code": null, "e": 4466, "s": 4322, "text": "First, calculate Gini index for sub-nodes by using the formula p^2+q^2 , which is the sum of the square of probability for success and failure." }, { "code": null, "e": 4557, "s": 4466, "text": "Next, calculate Gini index for split using weighted Gini score of each node of that split." }, { "code": null, "e": 4648, "s": 4557, "text": "Next, calculate Gini index for split using weighted Gini score of each node of that split." }, { "code": null, "e": 4744, "s": 4648, "text": "Classification and Regression Tree (CART) algorithm uses Gini method to generate binary splits." }, { "code": null, "e": 4890, "s": 4744, "text": "A split is basically including an attribute in the dataset and a value. We can create a split in dataset with the help of following three parts −" }, { "code": null, "e": 4980, "s": 4890, "text": "Part1: Calculating Gini Score − We have just discussed this part in the previous section." }, { "code": null, "e": 5070, "s": 4980, "text": "Part1: Calculating Gini Score − We have just discussed this part in the previous section." }, { "code": null, "e": 5443, "s": 5070, "text": "Part2: Splitting a dataset − It may be defined as separating a dataset into two lists of rows having index of an attribute and a split value of that attribute. After getting the two groups - right and left, from the dataset, we can calculate the value of split by using Gini score calculated in first part. Split value will decide in which group the attribute will reside." }, { "code": null, "e": 5816, "s": 5443, "text": "Part2: Splitting a dataset − It may be defined as separating a dataset into two lists of rows having index of an attribute and a split value of that attribute. After getting the two groups - right and left, from the dataset, we can calculate the value of split by using Gini score calculated in first part. Split value will decide in which group the attribute will reside." }, { "code": null, "e": 6183, "s": 5816, "text": "Part3: Evaluating all splits − Next part after finding Gini score and splitting dataset is the evaluation of all splits. For this purpose, first, we must check every value associated with each attribute as a candidate split. Then we need to find the best possible split by evaluating the cost of the split. The best split will be used as a node in the decision tree." }, { "code": null, "e": 6550, "s": 6183, "text": "Part3: Evaluating all splits − Next part after finding Gini score and splitting dataset is the evaluation of all splits. For this purpose, first, we must check every value associated with each attribute as a candidate split. Then we need to find the best possible split by evaluating the cost of the split. The best split will be used as a node in the decision tree." }, { "code": null, "e": 6684, "s": 6550, "text": "As we know that a tree has root node and terminal nodes. After creating the root node, we can build the tree by following two parts −" }, { "code": null, "e": 6928, "s": 6684, "text": "While creating terminal nodes of decision tree, one important point is to decide when to stop growing tree or creating further terminal nodes. It can be done by using two criteria namely maximum tree depth and minimum node records as follows −" }, { "code": null, "e": 7161, "s": 6928, "text": "Maximum Tree Depth − As name suggests, this is the maximum number of the nodes in a tree after root node. We must stop adding terminal nodes once a tree reached at maximum depth i.e. once a tree got maximum number of terminal nodes." }, { "code": null, "e": 7394, "s": 7161, "text": "Maximum Tree Depth − As name suggests, this is the maximum number of the nodes in a tree after root node. We must stop adding terminal nodes once a tree reached at maximum depth i.e. once a tree got maximum number of terminal nodes." }, { "code": null, "e": 7622, "s": 7394, "text": "Minimum Node Records − It may be defined as the minimum number of training patterns that a given node is responsible for. We must stop adding terminal nodes once tree reached at these minimum node records or below this minimum." }, { "code": null, "e": 7850, "s": 7622, "text": "Minimum Node Records − It may be defined as the minimum number of training patterns that a given node is responsible for. We must stop adding terminal nodes once tree reached at these minimum node records or below this minimum." }, { "code": null, "e": 7900, "s": 7850, "text": "Terminal node is used to make a final prediction." }, { "code": null, "e": 8262, "s": 7900, "text": "As we understood about when to create terminal nodes, now we can start building our tree. Recursive splitting is a method to build the tree. In this method, once a node is created, we can create the child nodes (nodes added to an existing node) recursively on each group of data, generated by splitting the dataset, by calling the same function again and again." }, { "code": null, "e": 8437, "s": 8262, "text": "After building a decision tree, we need to make a prediction about it. Basically, prediction involves navigating the decision tree with the specifically provided row of data." }, { "code": null, "e": 8597, "s": 8437, "text": "We can make a prediction with the help of recursive function, as did above. The same prediction routine is called again with the left or the child right nodes." }, { "code": null, "e": 8678, "s": 8597, "text": "The following are some of the assumptions we make while creating decision tree −" }, { "code": null, "e": 8744, "s": 8678, "text": "While preparing decision trees, the training set is as root node." }, { "code": null, "e": 8810, "s": 8744, "text": "While preparing decision trees, the training set is as root node." }, { "code": null, "e": 8987, "s": 8810, "text": "Decision tree classifier prefers the features values to be categorical. In case if you want to use continuous values then they must be done discretized prior to model building." }, { "code": null, "e": 9164, "s": 8987, "text": "Decision tree classifier prefers the features values to be categorical. In case if you want to use continuous values then they must be done discretized prior to model building." }, { "code": null, "e": 9238, "s": 9164, "text": "Based on the attribute’s values, the records are recursively distributed." }, { "code": null, "e": 9312, "s": 9238, "text": "Based on the attribute’s values, the records are recursively distributed." }, { "code": null, "e": 9422, "s": 9312, "text": "Statistical approach will be used to place attributes at any node position i.e.as root node or internal node." }, { "code": null, "e": 9532, "s": 9422, "text": "Statistical approach will be used to place attributes at any node position i.e.as root node or internal node." }, { "code": null, "e": 9635, "s": 9532, "text": "In the following example, we are going to implement Decision Tree classifier on Pima Indian Diabetes −" }, { "code": null, "e": 9691, "s": 9635, "text": "First, start with importing necessary python packages −" }, { "code": null, "e": 9813, "s": 9691, "text": "import pandas as pd\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.model_selection import train_test_split\n" }, { "code": null, "e": 9875, "s": 9813, "text": "Next, download the iris dataset from its weblink as follows −" }, { "code": null, "e": 10065, "s": 9875, "text": "col_names = ['pregnant', 'glucose', 'bp', 'skin', 'insulin', 'bmi', 'pedigree', 'age', 'label']\npima = pd.read_csv(r\"C:\\pima-indians-diabetes.csv\", header=None, names=col_names)\npima.head()" }, { "code": null, "e": 10524, "s": 10065, "text": " pregnant glucose bp skin insulin bmi pedigree age label\n0 6 148 72 35 0 33.6 0.627 50 1\n1 1 85 66 29 0 26.6 0.351 31 0\n2 8 183 64 0 0 23.3 0.672 32 1\n3 1 89 66 23 94 28.1 0.167 21 0\n4 0 137 40 35 168 43.1 2.288 33 1\n" }, { "code": null, "e": 10594, "s": 10524, "text": "Now, split the dataset into features and target variable as follows −" }, { "code": null, "e": 10741, "s": 10594, "text": "feature_cols = ['pregnant', 'insulin', 'bmi', 'age','glucose','bp','pedigree']\nX = pima[feature_cols] # Features\ny = pima.label # Target variable\n" }, { "code": null, "e": 10889, "s": 10741, "text": "Next, we will divide the data into train and test split. The following code will split the dataset into 70% training data and 30% of testing data −" }, { "code": null, "e": 10979, "s": 10889, "text": "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)\n" }, { "code": null, "e": 11071, "s": 10979, "text": "Next, train the model with the help of DecisionTreeClassifier class of sklearn as follows −" }, { "code": null, "e": 11134, "s": 11071, "text": "clf = DecisionTreeClassifier()\nclf = clf.fit(X_train,y_train)\n" }, { "code": null, "e": 11221, "s": 11134, "text": "At last we need to make prediction. It can be done with the help of following script −" }, { "code": null, "e": 11251, "s": 11221, "text": "y_pred = clf.predict(X_test)\n" }, { "code": null, "e": 11344, "s": 11251, "text": "Next, we can get the accuracy score, confusion matrix and classification report as follows −" }, { "code": null, "e": 11675, "s": 11344, "text": "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\nresult = confusion_matrix(y_test, y_pred)\nprint(\"Confusion Matrix:\")\nprint(result)\nresult1 = classification_report(y_test, y_pred)\nprint(\"Classification Report:\",)\nprint (result1)\nresult2 = accuracy_score(y_test,y_pred)\nprint(\"Accuracy:\",result2)" }, { "code": null, "e": 12061, "s": 11675, "text": "Confusion Matrix:\n[[116 30]\n[ 46 39]]\nClassification Report:\n precision recall f1-score support\n 0 0.72 0.79 0.75 146\n 1 0.57 0.46 0.51 85\nmicro avg 0.67 0.67 0.67 231\nmacro avg 0.64 0.63 0.63 231\nweighted avg 0.66 0.67 0.66 231\n\nAccuracy: 0.670995670995671 \n" }, { "code": null, "e": 12137, "s": 12061, "text": "The above decision tree can be visualized with the help of following code −" } ]
C++ program for Complex Number Calculator
17 Jan, 2022 Pre-Requisites: Complex Numbers, Mathematics, Object-oriented Programming This is a Complex Number Calculator which performs a lot of operations which are mentioned below, to simplify our day-to-day problems in mathematics. The implementation of this calculator is done using C++ Programming Language using concepts of operator overloading in OOPs. Problem Statement: Write a program to build a Complex Number Calculator using C++ which can perform the following operations: 1. Read Complex Number: It asks the user to enter two real and imaginary numbers of Complex Numbers to perform different operations on the complex number. Example: Real Part value: 10 Img Part value: 20 Real Part value: 5 Img Part value: 7 2. Display Complex Number: if the User has entered a complex number in the above function then the function display already exists a complex number. Example: Values are: 10+i20 5+i7 3. Addition of Complex Number: It Add two Complex Numbers in such a way that the real part of 1st complex number is added to the real part of 2nd complex number and the imaginary part of 1st complex number is added to the imaginary part of 2nd complex number which the user gives as input Complex Numbers. Example: Addition is: 15+i27 4. Subtraction of Complex Number: It Subtract two Complex Numbers in such a way that the real part of 1st complex number is Subtracted to the real part of 2nd complex number and the imaginary part of 1st complex number is Subtracted to the imaginary part of 2nd complex number which user gives as input Complex Numbers. Example: Subtraction is: 5+i13 5. Multiplication of Complex Number: It Multiplies two Complex Numbers which the user gives as input. Example: Multiplication is: -90+i170 6. Division of Complex Number: It Divides two Complex Numbers which users give as input Complex Numbers. Example: Division is: 2.56757+i0.405405 7. Conjugate of Complex Number: It finds Conjugate of two Complex Numbers which means it only changes the sign of imaginary part of the complex number which user gives as input Complex Numbers. Example: Conjugate is: 10-i20 5-i7 8. Sine of Complex Number: It finds sine value of two Complex Numbers which user give as input Complex Numbers. Example: Sin of 1st Complex Number is: -1.3197e+008-i2.03544e+008 Sin of 2nd Complex Number is: -525.795+i155.537 9. Cosine of Complex Number: It finds the cosine value of two Complex Numbers which user give as input Complex Numbers. Example: Cos of 1st Complex Number is: -2.03544e+008+i1.3197e+008 Cos of 2nd Complex Number is: 155.537+i525.794 10. Tangent of Complex Number: It finds the Tangent value of two Complex Numbers which the user give as input Complex Numbers. Example: Tan of 1st Complex Number is: 7.75703e-018+i1 Tan of 2nd Complex Number is: -9.0474e-007+i1 11. Sine Hyperbolic of Complex Number: It finds Sine Hyperbolic value of two Complex Numbers which user give as input Complex Numbers. Example: Sinh of 1st Complex Number is: 4494.3+i10054.5 Sinh of 2nd Complex Number is: 55.942+i48.7549 12. Cosine Hyperbolic of Complex Number: It finds Cosine Hyperbolic value of two Complex Numbers which user give as input Complex Numbers. Example: Cosh of 1st Complex Number is: 4494.3+i10054.5 Cosh of 2nd Complex Number is: 55.947+i48.7505 13. Tangent Hyperbolic of Complex Number: It finds Tangent Hyperbolic value of two Complex Numbers which user give as input Complex Numbers. Example: Tanh of 1st Complex Number is: 1+i3.07159e-009 Tanh of 2nd Complex Number is: 0.999988+i8.99459e-005 14. Natural Log of Complex Number: It finds the Natural Log value of two Complex Numbers which the user gives as input Complex Numbers. Example: log of 1st Complex Number is: 3.1073+i1.10715 log of 2nd Complex Number is: 2.15203+i0.950547 15. Norm of Complex Number: It finds Normal of two Complex Numbers which the user give as input Complex Numbers. Example: norm of 1st Complex Number is: 500+i0 norm of 2nd Complex Number is: 74+i0 16. Absolute of Complex Number: It finds the Absolute value of two Complex Numbers which means it converts negative complex number into positive complex number and positive complex number remain the same. Example: Absolute of 1st Complex Number is: 22.3607+i0 Absolute of 2nd Complex Number is: 8.60233+i0 17. Argument of Complex Number: It finds Argument of two Complex Numbers which user give as input Complex Numbers. Example: Argument of 1st Complex Number is: 1.10715+i0 Argument of 2nd Complex Number is: 0.950547+i0 18. Power of Complex Number: It finds the Power of two Complex Numbers which the user gives as input Complex Numbers. Example: power of 1st Complex Number is: Enter Power: 2 -300+i400 power of 2nd Complex Number is: Enter Power: 3 -610+i182 19. Exponential of Complex Number: It finds Exponential of two Complex Numbers which user give as input Complex Numbers. Example: Exponential of 1st Complex Number is: 8988.61+i20109 Exponential of 2nd Complex Number is: 111.889+i97.5055 20. Square Root of Complex Number: It finds Square Root of two Complex Numbers which users give as input Complex Numbers. Example: Square root of 1st Complex Number is: 4.02248+i2.48603 Square root of 2nd Complex Number is: 2.6079+i1.34207 21. Show Real Part of Complex Number: It shows the Real Part of two Complex Numbers which the user gives as input Complex Numbers. Example: Real Value of 1st Complex Number is: 10 Real Value of 2nd Complex Number is: 5 22. Show Imaginary Part of Complex Number: It shows Imaginary Part of two Complex Numbers which the user gives as input Complex Numbers. Example: Imaginary Value of 1st Complex Number is: 20 Imaginary Value of 2nd Complex Number is: 7 Below is the implementation of the above approach: C++ // Complex Number Calculator using C++#include <cmath>#include <complex>#include <iostream>using namespace std;class com { // private variable declarations double reall, img; public: // Method to read Complex Number void read() { // Reads Real Value of Complex Number cout << "Real Part value: "; cin >> reall; // Reads Imaginary Value of Complex Number cout << "Img Part value: "; cin >> img; } // display function declaration void display(); //+ operator function declaration com operator+(com); //- operator function declaration com operator-(com); //* operator function declaration com operator*(com); // / operator function declaration com operator/(com); //~ operator function declaration com operator~(void); // sin_value function declaration com sin_value(); // cos_value function declaration com cos_value(); // tan_value function declaration com tan_value(); // sinh_value function declaration com sinh_value(); // cosh_value function declaration com cosh_value(); // tanh_value function declaration com tanh_value(); // log_value function declaration com log_value(); // norm_value function declaration com norm_value(); // abs_value function declaration com abs_value(); // arg_value function declaration com arg_value(); // power_value function declaration com power_value(); // exp_value function declaration com exp_value(); // sqrt_value function declaration com sqrt_value(); // Declare inside com class and show Real part of // complex number double get_real() { // return real part return ((*this).reall); } // Declare inside com class and // show Imaginary part of complex number double get_img() { // return img part return ((*this).img); }};// Display Entered Complex Numbervoid com::display(){ // if imaginary part is positive then // it display real + i img complex number if (img >= 0) { cout << reall << "+i" << img << endl; } // if imaginary part is negative then // it display real - i img complex number else { cout << reall << "-i" << (-1) * img << endl; }}// Add two user entered complex numbercom com::operator+(com o2){ // declare temporary variable of class data type com temp; // add real part of two complex number // and store in real part of temporary variable temp.reall = reall + o2.reall; // add imaginary part of two complex number // and store in imaginary part of temporary variable temp.img = img + o2.img; // return temporary variable to function return temp;}// Subtract two user entered complex numbercom com::operator-(com o2){ // declare temporary variable of class data type com temp; // subtract real part of two complex number // and store in real part of temporary variable temp.reall = reall - o2.reall; // subtract imaginary part of two complex number and // store in imaginary part of temporary variable temp.img = img - o2.img; // return temporary variable to function return temp;}// Multiply two user entered complex numbercom com::operator*(com o2){ // declare temporary variable of class data type com temp; // Add Multiplication of real part of two complex // number & imaginary part of two complex number and // store in real part of temporary variable temp.reall = (reall * o2.reall) + (-1 * (img * o2.img)); // Add multiplication of real part of 1st and img part // of 2nd complex number and multiplication of img part // of 1st and real part of 2nd complex number and store // in real part of temporary variable temp.img = (img * o2.reall) + (reall * o2.img); // return temporary variable to function return temp;}// Divide two user entered complex numbercom com::operator/(com o2){ // declare temporary,o,num,den // variable of class data type com o, num, den, temp; // call conjugate function and perfor conjugate // operation o = ~o2; // calculate numerator and denominator complex number num = (*this) * (o); den = o2 * o; // divide numerator real part with denominator real part // and store in real part of temporary variable temp.reall = num.reall / den.reall; // divide numerator img part with denominator img part // and store in img part of temporary variable temp.img = num.img / den.reall; // return temporary variable to function return temp;}// find conjugate of both complex numberscom com::operator~(void){ // declare temporary variable of class data type com temp; // Store real part in real part of temporary variable temp.reall = reall; // Store multiplication of -1 and img in img part of // temporary variable to make conjugate temp.img = -1 * img; // return temporary variable to function return temp;}// find sine value of both complex numberscom com::sin_value(void){ // declare temporary variable of class data type com temp; // declare cn and sam variable of complex data type complex<double> cn((*this).reall, (*this).img); complex<double> sam; // sin() function find sin value of complex number sam = sin(cn); // real and img part of sam variable store in real and // img part of temporary variable temp.reall = real(sam); temp.img = imag(sam); // return temporary variable to function return temp;}// find cosine value of both complex numberscom com::cos_value(void){ // declare temporary variable of class data type com temp; // declare cn and sam variable of complex data type complex<double> cn((*this).reall, (*this).img); complex<double> sam; // cos() function find cosin value of complex number sam = cos(cn); // real and img part of sam variable store in real and // img part of temporary variable temp.reall = real(sam); temp.img = imag(sam); // return temporary variable to function return temp;}// find tangent value of both complex numberscom com::tan_value(void){ // declare temporary variable of class data type com temp; // declare cn and sam variable of complex data type complex<double> cn((*this).reall, (*this).img); complex<double> sam; // tan() function find tangent value of complex number sam = tan(cn); // real and img part of sam variable store in real and // img part of temporary variable temp.reall = real(sam); temp.img = imag(sam); // return temporary variable to function return temp;}// find sine hyperbolic value of both complex numberscom com::sinh_value(void){ // declare temporary variable of class data type com temp; // declare cn and sam variable of complex data type complex<double> cn((*this).reall, (*this).img); complex<double> sam; // sinh() function find sine hyperbolic value of complex // number sam = sinh(cn); // real and img part of sam variable store in real and // img part of temporary variable temp.reall = real(sam); temp.img = imag(sam); // return temporary variable to function return temp;}// find cosine hyperbolic value of both complex numberscom com::cosh_value(void){ // declare temporary variable of class data type com temp; // declare cn and sam variable of complex data type complex<double> cn((*this).reall, (*this).img); complex<double> sam; // cosh() function find cosine hyperbolic value of // complex number sam = cosh(cn); // real and img part of sam variable store in real and // img part of temporary variable temp.reall = real(sam); temp.img = imag(sam); // return temporary variable to function return temp;}// it find tangent hyperbolic value of both complex numberscom com::tanh_value(void){ // declare temporary variable of class data type com temp; // declare cn and sam variable of complex data type complex<double> cn((*this).reall, (*this).img); complex<double> sam; // tanh() function find tangent hyperbolic value of // complex number sam = tanh(cn); // real and img part of sam variable store in real and // img part of temporary variable temp.reall = real(sam); temp.img = imag(sam); // return temporary variable to function return temp;}// it find natural log value of both complex numberscom com::log_value(void){ // declare temporary variable of class data type com temp; // declare cn and sam variable of complex data type complex<double> cn((*this).reall, (*this).img); complex<double> sam; // log() function find natural log value of complex // number sam = log(cn); // real and img part of sam variable store in real and // img part of temporary variable temp.reall = real(sam); temp.img = imag(sam); // return temporary variable to function return temp;}// it find Norm of both complex numberscom com::norm_value(void){ // declare temporary variable of class data type com temp; // declare cn and sam variable of complex data type complex<double> cn((*this).reall, (*this).img); complex<double> sam; // norm() function find Norm of complex number sam = norm(cn); // real and img part of sam variable store in real and // img part of temporary variable temp.reall = real(sam); temp.img = imag(sam); // return temporary variable to function return temp;}// it find Absolute of both complex numberscom com::abs_value(void){ // declare temporary variable of class data type com temp; // declare cn and sam variable of complex data type complex<double> cn((*this).reall, (*this).img); complex<double> sam; // abs() function find Absolute of complex number sam = abs(cn); // real and img part of sam variable store in real and // img part of temporary variable temp.reall = real(sam); temp.img = imag(sam); // return temporary variable to function return temp;}// it find Argument of both complex numberscom com::arg_value(void){ // declare temporary variable of class data type com temp; // declare cn and sam variable of complex data type complex<double> cn((*this).reall, (*this).img); complex<double> sam; // arg() function find Argument of complex number sam = arg(cn); // real and img part of sam variable store in real and // img part of temporary variable temp.reall = real(sam); temp.img = imag(sam); // return temporary variable to function return temp;}// it find power of both complex numberscom com::power_value(void){ // declare variable p of integer data type int p; // Enter Power cout << "Enter Power: "; cin >> p; // declare temporary variable of class data type com temp; // declare cn and sam variable of complex data type complex<double> cn((*this).reall, (*this).img); complex<double> sam; // pow() function find Power of complex number sam = pow(cn, p); // real and img part of sam variable store in real and // img part of temporary variable temp.reall = real(sam); temp.img = imag(sam); // return temporary variable to function return temp;}// it find exponential of both complex numberscom com::exp_value(void){ // declare temporary variable of class data type com temp; // declare cn and sam variable of complex data type complex<double> cn((*this).reall, (*this).img); complex<double> sam; // exp() function find Exponential of complex number sam = exp(cn); // real and img part of sam variable store in real and // img part of temporary variable temp.reall = real(sam); temp.img = imag(sam); // return temporary variable to function return temp;}// it find Square root of both complex numberscom com::sqrt_value(void){ // declare temporary variable of class data type com temp; // declare cn and sam variable of complex data type complex<double> cn((*this).reall, (*this).img); complex<double> sam; // sqrt() function find Square Root of complex number sam = sqrt(cn); // real and img part of sam variable store in real and // img part of temporary variable temp.reall = real(sam); temp.img = imag(sam); // return temporary variable to function return temp;}int main(){ cout << "**********************Operations On Complex " "Number***************************"; // Declare o1,o2 and o3 variable of class name data type com o1, o2, o3; // declare choice variable of integer type int choice; do { // Enter you choice to perform operation cout << "\nEnter Choice\n\n"; cout << "1.Read Complex Number\n\n"; cout << "2.Display Complex Number\n\n"; cout << "3.Addition of Complex Number\n\n"; cout << "4.Subtraction of Complex Number\n\n"; cout << "5.Multiplication of Complex Number\n\n"; cout << "6.Division of Complex Number\n\n"; cout << "7.Conjugate of Complex Number\n\n"; cout << "8.Sine of Complex Number\n\n"; cout << "9.Cosine of Complex Number\n\n"; cout << "10.Tangent of Complex Number\n\n"; cout << "11.Sine Hyperbolic of Complex Number\n\n"; cout << "12.Cosine Hyperbolic of Complex Number\n\n"; cout << "13.Tangent Hyperbolic of Complex " "Number\n\n"; cout << "14.Natural Log of Complex Number\n\n"; cout << "15.Norm of Complex Number\n\n"; cout << "16.Absolute of Complex Number\n\n"; cout << "17.Argument of Complex Number\n\n"; cout << "18.Power of Complex Number\n\n"; cout << "19.Exponential of Complex Number\n\n"; cout << "20.Square Root of Complex Number\n\n"; cout << "21.Show Real Values of Complex Number\n\n"; cout << "22.Show Imaginary Values of Complex " "Number\n\n"; cout << "23.Exit\n\n"; cin >> choice; cout << "\n"; // use switch case according to user input switch (choice) { case 1: // Enter value of complex number cout << "Enter Values: \n"; // call read() function o1.read(); o2.read(); break; case 2: cout << "Values are: \n"; // call display function to display complex // number o1.display(); o2.display(); break; case 3: // call operator+() function to add complex // number o3 = o1 + o2; cout << "Addition is: \n"; o3.display(); break; case 4: // call operator-() function to subtract complex // number o3 = o1 - o2; cout << "Subtraction is: \n"; o3.display(); break; case 5: // call operator*() function to Multiply complex // number o3 = o1 * o2; cout << "Multiplication is: \n"; o3.display(); break; case 6: // call operator/() function to divide complex // number o3 = o1 / o2; cout << "Division is: \n"; o3.display(); break; case 7: // call operator~() function to Find conjugate of // complex number cout << "Conjugate is: \n"; o3 = ~o1; o3.display(); o3 = ~o2; o3.display(); break; case 8: // call sin_value() function to Find sine value // of complex number cout << "Sin of 1st Complex Number is: \n"; o3 = o1.sin_value(); o3.display(); cout << "Sin of 2nd Complex Number is: \n"; o3 = o2.sin_value(); o3.display(); break; case 9: // call cos_value() function to Find cosine value // of complex number cout << "Cos of 1st Complex Number is: \n"; o3 = o1.cos_value(); o3.display(); cout << "Cos of 2nd Complex Number is: \n"; o3 = o2.cos_value(); o3.display(); break; case 10: // call tan_value() function to Find tangent // value of complex number cout << "Tan of 1st Complex Number is: \n"; o3 = o1.tan_value(); o3.display(); cout << "Tan of 2nd Complex Number is: \n"; o3 = o2.tan_value(); o3.display(); break; case 11: // call sinh_value() function to Find sine // hyperbolic value of complex number cout << "Sinh of 1st Complex Number is: \n"; o3 = o1.sinh_value(); o3.display(); cout << "Sinh of 2nd Complex Number is: \n"; o3 = o2.sinh_value(); o3.display(); break; case 12: // call cosh_value() function to Find cosine // hyperbolic value of complex number cout << "Cosh of 1st Complex Number is: \n"; o3 = o1.cosh_value(); o3.display(); cout << "Cosh of 2nd Complex Number is: \n"; o3 = o2.cosh_value(); o3.display(); break; case 13: // call tanh_value() function to Find tangent // hyperbolic value of complex number cout << "Tanh of 1st Complex Number is: \n"; o3 = o1.tanh_value(); o3.display(); cout << "Tanh of 2nd Complex Number is: \n"; o3 = o2.tanh_value(); o3.display(); break; case 14: // call log_value() function to Find log value of // complex number cout << "log of 1st Complex Number is: \n"; o3 = o1.log_value(); o3.display(); cout << "log of 2nd Complex Number is: \n"; o3 = o2.log_value(); o3.display(); break; case 15: // call norm_value() function to Find norm of // complex number cout << "norm of 1st Complex Number is: \n"; o3 = o1.norm_value(); o3.display(); cout << "norm of 2nd Complex Number is: \n"; o3 = o2.norm_value(); o3.display(); break; case 16: // call abs_value() function to Find absolute of // complex number cout << "Absolute of 1st Complex Number is: \n"; o3 = o1.abs_value(); o3.display(); cout << "Absolute of 2nd Complex Number is: \n"; o3 = o2.abs_value(); o3.display(); break; case 17: // call arg_value() function to Find argument of // complex number cout << "Argument of 1st Complex Number is: \n"; o3 = o1.arg_value(); o3.display(); cout << "Argument of 2nd Complex Number is: \n"; o3 = o2.arg_value(); o3.display(); break; case 18: // call power_value() function to Power norm of // complex number cout << "power of 1st Complex Number is: \n"; o3 = o1.power_value(); o3.display(); cout << "power of 2nd Complex Number is: \n"; o3 = o2.power_value(); o3.display(); break; case 19: // call exp_value() function to Find exponential // of complex number cout << "Exponential of 1st Complex Number is " ": \n"; o3 = o1.exp_value(); o3.display(); cout << "Exponential of 2nd Complex Number is " ": \n"; o3 = o2.exp_value(); o3.display(); break; case 20: // call sqrt_value() function to Find Square root // of complex number cout << "Square root of 1st Complex Number is " ": \n"; o3 = o1.sqrt_value(); o3.display(); cout << "Square root of 2nd Complex Number is " ": \n"; o3 = o2.sqrt_value(); o3.display(); break; case 21: // call get_real() function to get real part of // complex number cout << "Real Value of 1st Complex Number is: " << o1.get_real() << endl; cout << "Real Value of 2nd Complex Number is: " << o2.get_real() << endl; break; case 22: // call get_img() function to get imaginary part // of complex number cout << "Imaginary Value of 1st Complex Number " "is: " << o1.get_img() << endl; cout << "Imaginary Value of 2nd Complex Number " "is: " << o2.get_img() << endl; break; case 23: // it return 1 to do while() loop and stop // execution return 1; break; default: // if user enter invalid choice then it print // Enter valid option!! cout << "Enter valid option!!"; break; } } while (1); return 0;} Output Video: Output: **********************Operations On Complex Number*************************** Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 1Enter Values: Real Part value: 10 Img Part value: 20 Real Part value: 5 Img Part value: 7Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 2Values are: 10+i20 5+i7Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 3Addition is: 15+i27Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 4Subtraction is: 5+i13Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 5Multiplication is: -90+i170Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 6Division is: 2.56757+i0.405405Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 7Conjugate is: 10-i20 5-i7Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 8Sin of 1st Complex Number is: -1.3197e+008-i2.03544e+008 Sin of 2nd Complex Number is: -525.795+i155.537Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 9Cos of 1st Complex Number is: -2.03544e+008+i1.3197e+008 Cos of 2nd Complex Number is: 155.537+i525.794Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 10Tan of 1st Complex Number is: 7.75703e-018+i1 Tan of 2nd Complex Number is: -9.0474e-007+i1Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 11Sinh of 1st Complex Number is: 4494.3+i10054.5 Sinh of 2nd Complex Number is: 55.942+i48.7549Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 12Cosh of 1st Complex Number is: 4494.3+i10054.5 Cosh of 2nd Complex Number is: 55.947+i48.7505Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 13Tanh of 1st Complex Number is: 1+i3.07159e-009 Tanh of 2nd Complex Number is: 0.999988+i8.99459e-005Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 14log of 1st Complex Number is: 3.1073+i1.10715 log of 2nd Complex Number is: 2.15203+i0.950547Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 15norm of 1st Complex Number is: 500+i0 norm of 2nd Complex Number is: 74+i0Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 16Absolute of 1st Complex Number is: 22.3607+i0 Absolute of 2nd Complex Number is: 8.60233+i0Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 17Argument of 1st Complex Number is: 1.10715+i0 Argument of 2nd Complex Number is: 0.950547+i0Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 18power of 1st Complex Number is: Enter Power: 2 -300+i400 power of 2nd Complex Number is: Enter Power: 3 -610+i182Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 19Exponential of 1st Complex Number is: 8988.61+i20109 Exponential of 2nd Complex Number is: 111.889+i97.5055Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 20Square root of 1st Complex Number is: 4.02248+i2.48603 Square root of 2nd Complex Number is: 2.6079+i1.34207Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 21Real Value of 1st Complex Number is: 10 Real Value of 2nd Complex Number is: 5Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 22Imaginary Value of 1st Complex Number is: 20 Imaginary Value of 2nd Complex Number is: 7Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 23 ——————————– Process exited after 94.69 seconds with return value 1 Press any key to continue . . . varshagumber28 sweetyty surinderdawra388 simmytarika5 CPP-complex C++ Programs Mathematical Project Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert data in the map of strings? Passing a function as a parameter in C++ string::npos in C++ with Examples Reason of runtime error in C/C++ Program to delete Nth digit of a Number Program for Fibonacci numbers C++ Data Types Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string Operators in C / C++
[ { "code": null, "e": 54, "s": 26, "text": "\n17 Jan, 2022" }, { "code": null, "e": 128, "s": 54, "text": "Pre-Requisites: Complex Numbers, Mathematics, Object-oriented Programming" }, { "code": null, "e": 403, "s": 128, "text": "This is a Complex Number Calculator which performs a lot of operations which are mentioned below, to simplify our day-to-day problems in mathematics. The implementation of this calculator is done using C++ Programming Language using concepts of operator overloading in OOPs." }, { "code": null, "e": 423, "s": 403, "text": "Problem Statement: " }, { "code": null, "e": 531, "s": 423, "text": "Write a program to build a Complex Number Calculator using C++ which can perform the following operations: " }, { "code": null, "e": 686, "s": 531, "text": "1. Read Complex Number: It asks the user to enter two real and imaginary numbers of Complex Numbers to perform different operations on the complex number." }, { "code": null, "e": 817, "s": 686, "text": "Example: Real Part value: 10\n Img Part value: 20\n Real Part value: 5\n Img Part value: 7" }, { "code": null, "e": 966, "s": 817, "text": "2. Display Complex Number: if the User has entered a complex number in the above function then the function display already exists a complex number." }, { "code": null, "e": 1039, "s": 966, "text": "Example: Values are:\n 10+i20\n 5+i7" }, { "code": null, "e": 1345, "s": 1039, "text": "3. Addition of Complex Number: It Add two Complex Numbers in such a way that the real part of 1st complex number is added to the real part of 2nd complex number and the imaginary part of 1st complex number is added to the imaginary part of 2nd complex number which the user gives as input Complex Numbers." }, { "code": null, "e": 1398, "s": 1345, "text": " Example: Addition is:\n 15+i27" }, { "code": null, "e": 1718, "s": 1398, "text": "4. Subtraction of Complex Number: It Subtract two Complex Numbers in such a way that the real part of 1st complex number is Subtracted to the real part of 2nd complex number and the imaginary part of 1st complex number is Subtracted to the imaginary part of 2nd complex number which user gives as input Complex Numbers." }, { "code": null, "e": 1769, "s": 1718, "text": "Example: Subtraction is:\n 5+i13" }, { "code": null, "e": 1871, "s": 1769, "text": "5. Multiplication of Complex Number: It Multiplies two Complex Numbers which the user gives as input." }, { "code": null, "e": 1931, "s": 1871, "text": "Example: Multiplication is:\n -90+i170 " }, { "code": null, "e": 2036, "s": 1931, "text": "6. Division of Complex Number: It Divides two Complex Numbers which users give as input Complex Numbers." }, { "code": null, "e": 2099, "s": 2036, "text": "Example: Division is:\n 2.56757+i0.405405 " }, { "code": null, "e": 2293, "s": 2099, "text": "7. Conjugate of Complex Number: It finds Conjugate of two Complex Numbers which means it only changes the sign of imaginary part of the complex number which user gives as input Complex Numbers." }, { "code": null, "e": 2370, "s": 2293, "text": "Example: Conjugate is:\n 10-i20\n 5-i7 " }, { "code": null, "e": 2482, "s": 2370, "text": "8. Sine of Complex Number: It finds sine value of two Complex Numbers which user give as input Complex Numbers." }, { "code": null, "e": 2659, "s": 2482, "text": "Example: Sin of 1st Complex Number is:\n -1.3197e+008-i2.03544e+008\n Sin of 2nd Complex Number is:\n -525.795+i155.537 " }, { "code": null, "e": 2779, "s": 2659, "text": "9. Cosine of Complex Number: It finds the cosine value of two Complex Numbers which user give as input Complex Numbers." }, { "code": null, "e": 2956, "s": 2779, "text": "Example: Cos of 1st Complex Number is:\n -2.03544e+008+i1.3197e+008\n Cos of 2nd Complex Number is:\n 155.537+i525.794 " }, { "code": null, "e": 3083, "s": 2956, "text": "10. Tangent of Complex Number: It finds the Tangent value of two Complex Numbers which the user give as input Complex Numbers." }, { "code": null, "e": 3244, "s": 3083, "text": "Example: Tan of 1st Complex Number is:\n 7.75703e-018+i1\n Tan of 2nd Complex Number is:\n -9.0474e-007+i1" }, { "code": null, "e": 3379, "s": 3244, "text": "11. Sine Hyperbolic of Complex Number: It finds Sine Hyperbolic value of two Complex Numbers which user give as input Complex Numbers." }, { "code": null, "e": 3540, "s": 3379, "text": "Example: Sinh of 1st Complex Number is:\n 4494.3+i10054.5\n Sinh of 2nd Complex Number is:\n 55.942+i48.7549" }, { "code": null, "e": 3679, "s": 3540, "text": "12. Cosine Hyperbolic of Complex Number: It finds Cosine Hyperbolic value of two Complex Numbers which user give as input Complex Numbers." }, { "code": null, "e": 3833, "s": 3679, "text": "Example: Cosh of 1st Complex Number is:\n 4494.3+i10054.5\n Cosh of 2nd Complex Number is:\n 55.947+i48.7505" }, { "code": null, "e": 3974, "s": 3833, "text": "13. Tangent Hyperbolic of Complex Number: It finds Tangent Hyperbolic value of two Complex Numbers which user give as input Complex Numbers." }, { "code": null, "e": 4136, "s": 3974, "text": "Example: Tanh of 1st Complex Number is:\n 1+i3.07159e-009\n Tanh of 2nd Complex Number is:\n 0.999988+i8.99459e-005" }, { "code": null, "e": 4272, "s": 4136, "text": "14. Natural Log of Complex Number: It finds the Natural Log value of two Complex Numbers which the user gives as input Complex Numbers." }, { "code": null, "e": 4425, "s": 4272, "text": "Example: log of 1st Complex Number is:\n 3.1073+i1.10715\n log of 2nd Complex Number is:\n 2.15203+i0.950547" }, { "code": null, "e": 4538, "s": 4425, "text": "15. Norm of Complex Number: It finds Normal of two Complex Numbers which the user give as input Complex Numbers." }, { "code": null, "e": 4670, "s": 4538, "text": "Example: norm of 1st Complex Number is:\n 500+i0\n norm of 2nd Complex Number is:\n 74+i0" }, { "code": null, "e": 4876, "s": 4670, "text": "16. Absolute of Complex Number: It finds the Absolute value of two Complex Numbers which means it converts negative complex number into positive complex number and positive complex number remain the same. " }, { "code": null, "e": 5025, "s": 4876, "text": "Example: Absolute of 1st Complex Number is:\n 22.3607+i0\n Absolute of 2nd Complex Number is:\n 8.60233+i0" }, { "code": null, "e": 5140, "s": 5025, "text": "17. Argument of Complex Number: It finds Argument of two Complex Numbers which user give as input Complex Numbers." }, { "code": null, "e": 5291, "s": 5140, "text": "Example: Argument of 1st Complex Number is:\n 1.10715+i0\n Argument of 2nd Complex Number is:\n 0.950547+i0" }, { "code": null, "e": 5409, "s": 5291, "text": "18. Power of Complex Number: It finds the Power of two Complex Numbers which the user gives as input Complex Numbers." }, { "code": null, "e": 5613, "s": 5409, "text": "Example: power of 1st Complex Number is:\n Enter Power: 2\n -300+i400\n power of 2nd Complex Number is:\n Enter Power: 3\n -610+i182" }, { "code": null, "e": 5734, "s": 5613, "text": "19. Exponential of Complex Number: It finds Exponential of two Complex Numbers which user give as input Complex Numbers." }, { "code": null, "e": 5898, "s": 5734, "text": "Example: Exponential of 1st Complex Number is:\n 8988.61+i20109\n Exponential of 2nd Complex Number is:\n 111.889+i97.5055" }, { "code": null, "e": 6020, "s": 5898, "text": "20. Square Root of Complex Number: It finds Square Root of two Complex Numbers which users give as input Complex Numbers." }, { "code": null, "e": 6182, "s": 6020, "text": "Example: Square root of 1st Complex Number is:\n 4.02248+i2.48603\n Square root of 2nd Complex Number is:\n 2.6079+i1.34207" }, { "code": null, "e": 6313, "s": 6182, "text": "21. Show Real Part of Complex Number: It shows the Real Part of two Complex Numbers which the user gives as input Complex Numbers." }, { "code": null, "e": 6411, "s": 6313, "text": "Example: Real Value of 1st Complex Number is: 10\n Real Value of 2nd Complex Number is: 5" }, { "code": null, "e": 6548, "s": 6411, "text": "22. Show Imaginary Part of Complex Number: It shows Imaginary Part of two Complex Numbers which the user gives as input Complex Numbers." }, { "code": null, "e": 6656, "s": 6548, "text": "Example: Imaginary Value of 1st Complex Number is: 20\n Imaginary Value of 2nd Complex Number is: 7" }, { "code": null, "e": 6708, "s": 6656, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 6712, "s": 6708, "text": "C++" }, { "code": "// Complex Number Calculator using C++#include <cmath>#include <complex>#include <iostream>using namespace std;class com { // private variable declarations double reall, img; public: // Method to read Complex Number void read() { // Reads Real Value of Complex Number cout << \"Real Part value: \"; cin >> reall; // Reads Imaginary Value of Complex Number cout << \"Img Part value: \"; cin >> img; } // display function declaration void display(); //+ operator function declaration com operator+(com); //- operator function declaration com operator-(com); //* operator function declaration com operator*(com); // / operator function declaration com operator/(com); //~ operator function declaration com operator~(void); // sin_value function declaration com sin_value(); // cos_value function declaration com cos_value(); // tan_value function declaration com tan_value(); // sinh_value function declaration com sinh_value(); // cosh_value function declaration com cosh_value(); // tanh_value function declaration com tanh_value(); // log_value function declaration com log_value(); // norm_value function declaration com norm_value(); // abs_value function declaration com abs_value(); // arg_value function declaration com arg_value(); // power_value function declaration com power_value(); // exp_value function declaration com exp_value(); // sqrt_value function declaration com sqrt_value(); // Declare inside com class and show Real part of // complex number double get_real() { // return real part return ((*this).reall); } // Declare inside com class and // show Imaginary part of complex number double get_img() { // return img part return ((*this).img); }};// Display Entered Complex Numbervoid com::display(){ // if imaginary part is positive then // it display real + i img complex number if (img >= 0) { cout << reall << \"+i\" << img << endl; } // if imaginary part is negative then // it display real - i img complex number else { cout << reall << \"-i\" << (-1) * img << endl; }}// Add two user entered complex numbercom com::operator+(com o2){ // declare temporary variable of class data type com temp; // add real part of two complex number // and store in real part of temporary variable temp.reall = reall + o2.reall; // add imaginary part of two complex number // and store in imaginary part of temporary variable temp.img = img + o2.img; // return temporary variable to function return temp;}// Subtract two user entered complex numbercom com::operator-(com o2){ // declare temporary variable of class data type com temp; // subtract real part of two complex number // and store in real part of temporary variable temp.reall = reall - o2.reall; // subtract imaginary part of two complex number and // store in imaginary part of temporary variable temp.img = img - o2.img; // return temporary variable to function return temp;}// Multiply two user entered complex numbercom com::operator*(com o2){ // declare temporary variable of class data type com temp; // Add Multiplication of real part of two complex // number & imaginary part of two complex number and // store in real part of temporary variable temp.reall = (reall * o2.reall) + (-1 * (img * o2.img)); // Add multiplication of real part of 1st and img part // of 2nd complex number and multiplication of img part // of 1st and real part of 2nd complex number and store // in real part of temporary variable temp.img = (img * o2.reall) + (reall * o2.img); // return temporary variable to function return temp;}// Divide two user entered complex numbercom com::operator/(com o2){ // declare temporary,o,num,den // variable of class data type com o, num, den, temp; // call conjugate function and perfor conjugate // operation o = ~o2; // calculate numerator and denominator complex number num = (*this) * (o); den = o2 * o; // divide numerator real part with denominator real part // and store in real part of temporary variable temp.reall = num.reall / den.reall; // divide numerator img part with denominator img part // and store in img part of temporary variable temp.img = num.img / den.reall; // return temporary variable to function return temp;}// find conjugate of both complex numberscom com::operator~(void){ // declare temporary variable of class data type com temp; // Store real part in real part of temporary variable temp.reall = reall; // Store multiplication of -1 and img in img part of // temporary variable to make conjugate temp.img = -1 * img; // return temporary variable to function return temp;}// find sine value of both complex numberscom com::sin_value(void){ // declare temporary variable of class data type com temp; // declare cn and sam variable of complex data type complex<double> cn((*this).reall, (*this).img); complex<double> sam; // sin() function find sin value of complex number sam = sin(cn); // real and img part of sam variable store in real and // img part of temporary variable temp.reall = real(sam); temp.img = imag(sam); // return temporary variable to function return temp;}// find cosine value of both complex numberscom com::cos_value(void){ // declare temporary variable of class data type com temp; // declare cn and sam variable of complex data type complex<double> cn((*this).reall, (*this).img); complex<double> sam; // cos() function find cosin value of complex number sam = cos(cn); // real and img part of sam variable store in real and // img part of temporary variable temp.reall = real(sam); temp.img = imag(sam); // return temporary variable to function return temp;}// find tangent value of both complex numberscom com::tan_value(void){ // declare temporary variable of class data type com temp; // declare cn and sam variable of complex data type complex<double> cn((*this).reall, (*this).img); complex<double> sam; // tan() function find tangent value of complex number sam = tan(cn); // real and img part of sam variable store in real and // img part of temporary variable temp.reall = real(sam); temp.img = imag(sam); // return temporary variable to function return temp;}// find sine hyperbolic value of both complex numberscom com::sinh_value(void){ // declare temporary variable of class data type com temp; // declare cn and sam variable of complex data type complex<double> cn((*this).reall, (*this).img); complex<double> sam; // sinh() function find sine hyperbolic value of complex // number sam = sinh(cn); // real and img part of sam variable store in real and // img part of temporary variable temp.reall = real(sam); temp.img = imag(sam); // return temporary variable to function return temp;}// find cosine hyperbolic value of both complex numberscom com::cosh_value(void){ // declare temporary variable of class data type com temp; // declare cn and sam variable of complex data type complex<double> cn((*this).reall, (*this).img); complex<double> sam; // cosh() function find cosine hyperbolic value of // complex number sam = cosh(cn); // real and img part of sam variable store in real and // img part of temporary variable temp.reall = real(sam); temp.img = imag(sam); // return temporary variable to function return temp;}// it find tangent hyperbolic value of both complex numberscom com::tanh_value(void){ // declare temporary variable of class data type com temp; // declare cn and sam variable of complex data type complex<double> cn((*this).reall, (*this).img); complex<double> sam; // tanh() function find tangent hyperbolic value of // complex number sam = tanh(cn); // real and img part of sam variable store in real and // img part of temporary variable temp.reall = real(sam); temp.img = imag(sam); // return temporary variable to function return temp;}// it find natural log value of both complex numberscom com::log_value(void){ // declare temporary variable of class data type com temp; // declare cn and sam variable of complex data type complex<double> cn((*this).reall, (*this).img); complex<double> sam; // log() function find natural log value of complex // number sam = log(cn); // real and img part of sam variable store in real and // img part of temporary variable temp.reall = real(sam); temp.img = imag(sam); // return temporary variable to function return temp;}// it find Norm of both complex numberscom com::norm_value(void){ // declare temporary variable of class data type com temp; // declare cn and sam variable of complex data type complex<double> cn((*this).reall, (*this).img); complex<double> sam; // norm() function find Norm of complex number sam = norm(cn); // real and img part of sam variable store in real and // img part of temporary variable temp.reall = real(sam); temp.img = imag(sam); // return temporary variable to function return temp;}// it find Absolute of both complex numberscom com::abs_value(void){ // declare temporary variable of class data type com temp; // declare cn and sam variable of complex data type complex<double> cn((*this).reall, (*this).img); complex<double> sam; // abs() function find Absolute of complex number sam = abs(cn); // real and img part of sam variable store in real and // img part of temporary variable temp.reall = real(sam); temp.img = imag(sam); // return temporary variable to function return temp;}// it find Argument of both complex numberscom com::arg_value(void){ // declare temporary variable of class data type com temp; // declare cn and sam variable of complex data type complex<double> cn((*this).reall, (*this).img); complex<double> sam; // arg() function find Argument of complex number sam = arg(cn); // real and img part of sam variable store in real and // img part of temporary variable temp.reall = real(sam); temp.img = imag(sam); // return temporary variable to function return temp;}// it find power of both complex numberscom com::power_value(void){ // declare variable p of integer data type int p; // Enter Power cout << \"Enter Power: \"; cin >> p; // declare temporary variable of class data type com temp; // declare cn and sam variable of complex data type complex<double> cn((*this).reall, (*this).img); complex<double> sam; // pow() function find Power of complex number sam = pow(cn, p); // real and img part of sam variable store in real and // img part of temporary variable temp.reall = real(sam); temp.img = imag(sam); // return temporary variable to function return temp;}// it find exponential of both complex numberscom com::exp_value(void){ // declare temporary variable of class data type com temp; // declare cn and sam variable of complex data type complex<double> cn((*this).reall, (*this).img); complex<double> sam; // exp() function find Exponential of complex number sam = exp(cn); // real and img part of sam variable store in real and // img part of temporary variable temp.reall = real(sam); temp.img = imag(sam); // return temporary variable to function return temp;}// it find Square root of both complex numberscom com::sqrt_value(void){ // declare temporary variable of class data type com temp; // declare cn and sam variable of complex data type complex<double> cn((*this).reall, (*this).img); complex<double> sam; // sqrt() function find Square Root of complex number sam = sqrt(cn); // real and img part of sam variable store in real and // img part of temporary variable temp.reall = real(sam); temp.img = imag(sam); // return temporary variable to function return temp;}int main(){ cout << \"**********************Operations On Complex \" \"Number***************************\"; // Declare o1,o2 and o3 variable of class name data type com o1, o2, o3; // declare choice variable of integer type int choice; do { // Enter you choice to perform operation cout << \"\\nEnter Choice\\n\\n\"; cout << \"1.Read Complex Number\\n\\n\"; cout << \"2.Display Complex Number\\n\\n\"; cout << \"3.Addition of Complex Number\\n\\n\"; cout << \"4.Subtraction of Complex Number\\n\\n\"; cout << \"5.Multiplication of Complex Number\\n\\n\"; cout << \"6.Division of Complex Number\\n\\n\"; cout << \"7.Conjugate of Complex Number\\n\\n\"; cout << \"8.Sine of Complex Number\\n\\n\"; cout << \"9.Cosine of Complex Number\\n\\n\"; cout << \"10.Tangent of Complex Number\\n\\n\"; cout << \"11.Sine Hyperbolic of Complex Number\\n\\n\"; cout << \"12.Cosine Hyperbolic of Complex Number\\n\\n\"; cout << \"13.Tangent Hyperbolic of Complex \" \"Number\\n\\n\"; cout << \"14.Natural Log of Complex Number\\n\\n\"; cout << \"15.Norm of Complex Number\\n\\n\"; cout << \"16.Absolute of Complex Number\\n\\n\"; cout << \"17.Argument of Complex Number\\n\\n\"; cout << \"18.Power of Complex Number\\n\\n\"; cout << \"19.Exponential of Complex Number\\n\\n\"; cout << \"20.Square Root of Complex Number\\n\\n\"; cout << \"21.Show Real Values of Complex Number\\n\\n\"; cout << \"22.Show Imaginary Values of Complex \" \"Number\\n\\n\"; cout << \"23.Exit\\n\\n\"; cin >> choice; cout << \"\\n\"; // use switch case according to user input switch (choice) { case 1: // Enter value of complex number cout << \"Enter Values: \\n\"; // call read() function o1.read(); o2.read(); break; case 2: cout << \"Values are: \\n\"; // call display function to display complex // number o1.display(); o2.display(); break; case 3: // call operator+() function to add complex // number o3 = o1 + o2; cout << \"Addition is: \\n\"; o3.display(); break; case 4: // call operator-() function to subtract complex // number o3 = o1 - o2; cout << \"Subtraction is: \\n\"; o3.display(); break; case 5: // call operator*() function to Multiply complex // number o3 = o1 * o2; cout << \"Multiplication is: \\n\"; o3.display(); break; case 6: // call operator/() function to divide complex // number o3 = o1 / o2; cout << \"Division is: \\n\"; o3.display(); break; case 7: // call operator~() function to Find conjugate of // complex number cout << \"Conjugate is: \\n\"; o3 = ~o1; o3.display(); o3 = ~o2; o3.display(); break; case 8: // call sin_value() function to Find sine value // of complex number cout << \"Sin of 1st Complex Number is: \\n\"; o3 = o1.sin_value(); o3.display(); cout << \"Sin of 2nd Complex Number is: \\n\"; o3 = o2.sin_value(); o3.display(); break; case 9: // call cos_value() function to Find cosine value // of complex number cout << \"Cos of 1st Complex Number is: \\n\"; o3 = o1.cos_value(); o3.display(); cout << \"Cos of 2nd Complex Number is: \\n\"; o3 = o2.cos_value(); o3.display(); break; case 10: // call tan_value() function to Find tangent // value of complex number cout << \"Tan of 1st Complex Number is: \\n\"; o3 = o1.tan_value(); o3.display(); cout << \"Tan of 2nd Complex Number is: \\n\"; o3 = o2.tan_value(); o3.display(); break; case 11: // call sinh_value() function to Find sine // hyperbolic value of complex number cout << \"Sinh of 1st Complex Number is: \\n\"; o3 = o1.sinh_value(); o3.display(); cout << \"Sinh of 2nd Complex Number is: \\n\"; o3 = o2.sinh_value(); o3.display(); break; case 12: // call cosh_value() function to Find cosine // hyperbolic value of complex number cout << \"Cosh of 1st Complex Number is: \\n\"; o3 = o1.cosh_value(); o3.display(); cout << \"Cosh of 2nd Complex Number is: \\n\"; o3 = o2.cosh_value(); o3.display(); break; case 13: // call tanh_value() function to Find tangent // hyperbolic value of complex number cout << \"Tanh of 1st Complex Number is: \\n\"; o3 = o1.tanh_value(); o3.display(); cout << \"Tanh of 2nd Complex Number is: \\n\"; o3 = o2.tanh_value(); o3.display(); break; case 14: // call log_value() function to Find log value of // complex number cout << \"log of 1st Complex Number is: \\n\"; o3 = o1.log_value(); o3.display(); cout << \"log of 2nd Complex Number is: \\n\"; o3 = o2.log_value(); o3.display(); break; case 15: // call norm_value() function to Find norm of // complex number cout << \"norm of 1st Complex Number is: \\n\"; o3 = o1.norm_value(); o3.display(); cout << \"norm of 2nd Complex Number is: \\n\"; o3 = o2.norm_value(); o3.display(); break; case 16: // call abs_value() function to Find absolute of // complex number cout << \"Absolute of 1st Complex Number is: \\n\"; o3 = o1.abs_value(); o3.display(); cout << \"Absolute of 2nd Complex Number is: \\n\"; o3 = o2.abs_value(); o3.display(); break; case 17: // call arg_value() function to Find argument of // complex number cout << \"Argument of 1st Complex Number is: \\n\"; o3 = o1.arg_value(); o3.display(); cout << \"Argument of 2nd Complex Number is: \\n\"; o3 = o2.arg_value(); o3.display(); break; case 18: // call power_value() function to Power norm of // complex number cout << \"power of 1st Complex Number is: \\n\"; o3 = o1.power_value(); o3.display(); cout << \"power of 2nd Complex Number is: \\n\"; o3 = o2.power_value(); o3.display(); break; case 19: // call exp_value() function to Find exponential // of complex number cout << \"Exponential of 1st Complex Number is \" \": \\n\"; o3 = o1.exp_value(); o3.display(); cout << \"Exponential of 2nd Complex Number is \" \": \\n\"; o3 = o2.exp_value(); o3.display(); break; case 20: // call sqrt_value() function to Find Square root // of complex number cout << \"Square root of 1st Complex Number is \" \": \\n\"; o3 = o1.sqrt_value(); o3.display(); cout << \"Square root of 2nd Complex Number is \" \": \\n\"; o3 = o2.sqrt_value(); o3.display(); break; case 21: // call get_real() function to get real part of // complex number cout << \"Real Value of 1st Complex Number is: \" << o1.get_real() << endl; cout << \"Real Value of 2nd Complex Number is: \" << o2.get_real() << endl; break; case 22: // call get_img() function to get imaginary part // of complex number cout << \"Imaginary Value of 1st Complex Number \" \"is: \" << o1.get_img() << endl; cout << \"Imaginary Value of 2nd Complex Number \" \"is: \" << o2.get_img() << endl; break; case 23: // it return 1 to do while() loop and stop // execution return 1; break; default: // if user enter invalid choice then it print // Enter valid option!! cout << \"Enter valid option!!\"; break; } } while (1); return 0;}", "e": 28089, "s": 6712, "text": null }, { "code": null, "e": 28104, "s": 28089, "text": "Output Video: " }, { "code": null, "e": 28113, "s": 28104, "text": "Output: " }, { "code": null, "e": 46389, "s": 28113, "text": "**********************Operations On Complex Number*************************** Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 1Enter Values: Real Part value: 10 Img Part value: 20 Real Part value: 5 Img Part value: 7Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 2Values are: 10+i20 5+i7Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 3Addition is: 15+i27Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 4Subtraction is: 5+i13Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 5Multiplication is: -90+i170Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 6Division is: 2.56757+i0.405405Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 7Conjugate is: 10-i20 5-i7Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 8Sin of 1st Complex Number is: -1.3197e+008-i2.03544e+008 Sin of 2nd Complex Number is: -525.795+i155.537Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 9Cos of 1st Complex Number is: -2.03544e+008+i1.3197e+008 Cos of 2nd Complex Number is: 155.537+i525.794Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 10Tan of 1st Complex Number is: 7.75703e-018+i1 Tan of 2nd Complex Number is: -9.0474e-007+i1Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 11Sinh of 1st Complex Number is: 4494.3+i10054.5 Sinh of 2nd Complex Number is: 55.942+i48.7549Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 12Cosh of 1st Complex Number is: 4494.3+i10054.5 Cosh of 2nd Complex Number is: 55.947+i48.7505Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 13Tanh of 1st Complex Number is: 1+i3.07159e-009 Tanh of 2nd Complex Number is: 0.999988+i8.99459e-005Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 14log of 1st Complex Number is: 3.1073+i1.10715 log of 2nd Complex Number is: 2.15203+i0.950547Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 15norm of 1st Complex Number is: 500+i0 norm of 2nd Complex Number is: 74+i0Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 16Absolute of 1st Complex Number is: 22.3607+i0 Absolute of 2nd Complex Number is: 8.60233+i0Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 17Argument of 1st Complex Number is: 1.10715+i0 Argument of 2nd Complex Number is: 0.950547+i0Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 18power of 1st Complex Number is: Enter Power: 2 -300+i400 power of 2nd Complex Number is: Enter Power: 3 -610+i182Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 19Exponential of 1st Complex Number is: 8988.61+i20109 Exponential of 2nd Complex Number is: 111.889+i97.5055Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 20Square root of 1st Complex Number is: 4.02248+i2.48603 Square root of 2nd Complex Number is: 2.6079+i1.34207Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 21Real Value of 1st Complex Number is: 10 Real Value of 2nd Complex Number is: 5Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 22Imaginary Value of 1st Complex Number is: 20 Imaginary Value of 2nd Complex Number is: 7Enter Choice 1.Read Complex Number 2.Display Complex Number 3.Addition of Complex Number 4.Subtraction of Complex Number 5.Multiplication of Complex Number 6.Division of Complex Number 7.Conjugate of Complex Number 8.Sine of Complex Number 9.Cosine of Complex Number 10.Tangent of Complex Number 11.Sine Hyperbolic of Complex Number 12.Cosine Hyperbolic of Complex Number 13.Tangent Hyperbolic of Complex Number 14.Natural Log of Complex Number 15.Norm of Complex Number 16.Absolute of Complex Number 17.Argument of Complex Number 18.Power of Complex Number 19.Exponential of Complex Number 20.Square Root of Complex Number 21.Show Real Values of Complex Number 22.Show Imaginary Values of Complex Number 23.Exit 23 ——————————– Process exited after 94.69 seconds with return value 1 Press any key to continue . . ." }, { "code": null, "e": 46404, "s": 46389, "text": "varshagumber28" }, { "code": null, "e": 46413, "s": 46404, "text": "sweetyty" }, { "code": null, "e": 46430, "s": 46413, "text": "surinderdawra388" }, { "code": null, "e": 46443, "s": 46430, "text": "simmytarika5" }, { "code": null, "e": 46455, "s": 46443, "text": "CPP-complex" }, { "code": null, "e": 46468, "s": 46455, "text": "C++ Programs" }, { "code": null, "e": 46481, "s": 46468, "text": "Mathematical" }, { "code": null, "e": 46489, "s": 46481, "text": "Project" }, { "code": null, "e": 46502, "s": 46489, "text": "Mathematical" }, { "code": null, "e": 46600, "s": 46502, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 46642, "s": 46600, "text": "How to insert data in the map of strings?" }, { "code": null, "e": 46683, "s": 46642, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 46717, "s": 46683, "text": "string::npos in C++ with Examples" }, { "code": null, "e": 46750, "s": 46717, "text": "Reason of runtime error in C/C++" }, { "code": null, "e": 46790, "s": 46750, "text": "Program to delete Nth digit of a Number" }, { "code": null, "e": 46820, "s": 46790, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 46835, "s": 46820, "text": "C++ Data Types" }, { "code": null, "e": 46878, "s": 46835, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 46938, "s": 46878, "text": "Write a program to print all permutations of a given string" } ]
Python | Pandas Period.year
06 Jan, 2019 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Period.year attribute return an integer value representing the year the given period lies in. Syntax : Period.year Parameters : None Return : year Example #1: Use Period.year attribute to find the year the period lies in for the given Period object. # importing pandas as pdimport pandas as pd # Create the Period objectprd = pd.Period(freq ='S', year = 2000, month = 2, day = 21, hour = 8, minute = 21) # Print the Period objectprint(prd) Output : Now we will use the Period.year attribute to find the value of year # return the year valueprd.year Output : As we can see in the output, the Period.year attribute has returned 2000 indicating that the given period lies in the year of 2000. Example #2: Use Period.year attribute to find the year the period lies in for the given Period object. # importing pandas as pdimport pandas as pd # Create the Period objectprd = pd.Period(freq ='T', year = 2006, month = 10, hour = 15, minute = 49) # Print the Period objectprint(prd) Output : Now we will use the Period.year attribute to find the value of year # return the yearprd.year Output :As we can see in the output, the Period.year attribute has returned 2006 indicating that the given period lies in the year of 2006. Pandas scalar-period Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Convert integer to string in Python Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Jan, 2019" }, { "code": null, "e": 242, "s": 28, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 343, "s": 242, "text": "Pandas Period.year attribute return an integer value representing the year the given period lies in." }, { "code": null, "e": 364, "s": 343, "text": "Syntax : Period.year" }, { "code": null, "e": 382, "s": 364, "text": "Parameters : None" }, { "code": null, "e": 396, "s": 382, "text": "Return : year" }, { "code": null, "e": 499, "s": 396, "text": "Example #1: Use Period.year attribute to find the year the period lies in for the given Period object." }, { "code": "# importing pandas as pdimport pandas as pd # Create the Period objectprd = pd.Period(freq ='S', year = 2000, month = 2, day = 21, hour = 8, minute = 21) # Print the Period objectprint(prd)", "e": 708, "s": 499, "text": null }, { "code": null, "e": 717, "s": 708, "text": "Output :" }, { "code": null, "e": 785, "s": 717, "text": "Now we will use the Period.year attribute to find the value of year" }, { "code": "# return the year valueprd.year", "e": 817, "s": 785, "text": null }, { "code": null, "e": 826, "s": 817, "text": "Output :" }, { "code": null, "e": 958, "s": 826, "text": "As we can see in the output, the Period.year attribute has returned 2000 indicating that the given period lies in the year of 2000." }, { "code": null, "e": 1061, "s": 958, "text": "Example #2: Use Period.year attribute to find the year the period lies in for the given Period object." }, { "code": "# importing pandas as pdimport pandas as pd # Create the Period objectprd = pd.Period(freq ='T', year = 2006, month = 10, hour = 15, minute = 49) # Print the Period objectprint(prd)", "e": 1272, "s": 1061, "text": null }, { "code": null, "e": 1281, "s": 1272, "text": "Output :" }, { "code": null, "e": 1349, "s": 1281, "text": "Now we will use the Period.year attribute to find the value of year" }, { "code": "# return the yearprd.year", "e": 1375, "s": 1349, "text": null }, { "code": null, "e": 1515, "s": 1375, "text": "Output :As we can see in the output, the Period.year attribute has returned 2006 indicating that the given period lies in the year of 2006." }, { "code": null, "e": 1536, "s": 1515, "text": "Pandas scalar-period" }, { "code": null, "e": 1550, "s": 1536, "text": "Python-pandas" }, { "code": null, "e": 1557, "s": 1550, "text": "Python" }, { "code": null, "e": 1655, "s": 1557, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1673, "s": 1655, "text": "Python Dictionary" }, { "code": null, "e": 1715, "s": 1673, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1737, "s": 1715, "text": "Enumerate() in Python" }, { "code": null, "e": 1769, "s": 1737, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1798, "s": 1769, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1825, "s": 1798, "text": "Python Classes and Objects" }, { "code": null, "e": 1846, "s": 1825, "text": "Python OOPs Concepts" }, { "code": null, "e": 1882, "s": 1846, "text": "Convert integer to string in Python" }, { "code": null, "e": 1905, "s": 1882, "text": "Introduction To PYTHON" } ]
One-Proportion Z-Test in R Programming
22 Jul, 2020 The One proportion Z-test is used to compare an observed proportion to a theoretical one when there are only two categories. For example, we have a population of mice containing half male and half females (p = 0.5 = 50%). Some of these mice (n = 160) have developed spontaneous cancer, including 95 males and 65 females. We want to know, whether cancer affects more males than females? So in this problem: The number of successes (male with cancer) is 95 The observed proportion (po) of the male is 95/160 The observed proportion (q) of the female is 1 – po The expected proportion (pe) of the male is 0.5 (50%) The number of observations (n) is 160 The test statistic (also known as z-test) can be calculated as follow: where, po: the observed proportionq: 1 – pope: the expected proportionn: the sample size In R Language, the function used for performing a z-test is binom.test() and prop.test(). Syntax:binom.test(x, n, p = 0.5, alternative = “two.sided”)prop.test(x, n, p = NULL, alternative = “two.sided”, correct = TRUE) Parameters:x = number of successes and failures in data set.n = size of data set.p = probabilities of success. It must be in the range of 0 to 1.alternative = a character string specifying the alternative hypothesis.correct = a logical indicating whether Yates’ continuity correction should be applied where possible. Example 1:Let’s assume that 30 out of 70 people recommend Street Food to their friends. To test this claim, a random sample of 150 people obtained. Of these 150 people, 80 indicate that they recommend Street Food to their friend. Is this claim accurate? Use alpha = 0.05. Solution:Now given x=.80, P=.30, n=150. We want to know, whether the People recommend street food to their friend than healthy food? Let’s use the function prop.test() in R. # Using prop.test()prop.test(x = 80, n = 150, p = 0.3, correct = FALSE) Output: 1-sample proportions test without continuity correction data: 80 out of 150, null probability 0.3 X-squared = 38.889, df = 1, p-value = 4.489e-10 alternative hypothesis: true p is not equal to 0.3 95 percent confidence interval: 0.4536625 0.6113395 sample estimates: p 0.5333333 It returns p-value which is 4.186269 alternative hypothesis. a 95% confidence intervals. probability of success is 0.53 The p-value of the test is 4.486269, which is less than the significance level alpha = 0.05. The claim that 30 out of 70 People recommend Street Food to their friends is not accurate. Example 2:Suppose that current vitamin pills cure 80% of all cases. A new vitamin pill has been discovered or made. In a sample of 150 patients with the lack of vitamins that were treated with the new vitamins, 95 were cured. Do the results of this study support the claim that the new vitamins have a higher cure rate than the existing vitamins? Solution:Now given x=.95, P=.80, n=160. Let’s use the function prop.test() in R. # Using prop.test() prop.test(x = 95, n = 160, p = 0.8, correct = FALSE) Output: 1-sample proportions test without continuity correction data: 95 out of 160, null probability 0.8 X-squared = 42.539, df = 1, p-value = 6 . 928e-11 alternative hypothesis: true p is not equal to 0.8 95 percent confidence interval: 0.5163169 0.6667870 sample estimates: p 0.59375 It returns p-value which is 6.928462 alternative hypothesis a 95% confidence intervals. probability of success is 0.59 The p-value of the test is 6.928462, which is greater than the significance level alpha = 0.05. The claim that 95 out of 160 people cured with new vitamins are accurate. Example 3:Suppose that in India 15% of people like Work from home. In a sample of 100 people, the people who like Work from home are 25. Is this claim accurate? Solution:Now given x=.25, P=.15, n=100. Let’s use the function binom.test() in R. # Using binom.test()binom.test(x =25, n = 100, p = 0.15) Output: Exact binomial test data: 25 and 100 number of successes = 25, number of trials = 100, p-value = 0.007633 alternative hypothesis: true probability of success is not equal to 0.15 95 percent confidence interval: 0.1687797 0.3465525 sample estimates: probability of success 0.25 It returns p-value which is 0.007633 alternative hypothesis. a 95% confidence intervals. probability of success is 0.25 The p-value of the test is 0.007633 which is less than the significance level alpha = 0.05. The claim that 25 out of 100 people like work form home is not accurate. data-science Picked R Machine-Learning R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Jul, 2020" }, { "code": null, "e": 434, "s": 28, "text": "The One proportion Z-test is used to compare an observed proportion to a theoretical one when there are only two categories. For example, we have a population of mice containing half male and half females (p = 0.5 = 50%). Some of these mice (n = 160) have developed spontaneous cancer, including 95 males and 65 females. We want to know, whether cancer affects more males than females? So in this problem:" }, { "code": null, "e": 483, "s": 434, "text": "The number of successes (male with cancer) is 95" }, { "code": null, "e": 534, "s": 483, "text": "The observed proportion (po) of the male is 95/160" }, { "code": null, "e": 586, "s": 534, "text": "The observed proportion (q) of the female is 1 – po" }, { "code": null, "e": 640, "s": 586, "text": "The expected proportion (pe) of the male is 0.5 (50%)" }, { "code": null, "e": 678, "s": 640, "text": "The number of observations (n) is 160" }, { "code": null, "e": 749, "s": 678, "text": "The test statistic (also known as z-test) can be calculated as follow:" }, { "code": null, "e": 756, "s": 749, "text": "where," }, { "code": null, "e": 838, "s": 756, "text": "po: the observed proportionq: 1 – pope: the expected proportionn: the sample size" }, { "code": null, "e": 928, "s": 838, "text": "In R Language, the function used for performing a z-test is binom.test() and prop.test()." }, { "code": null, "e": 1056, "s": 928, "text": "Syntax:binom.test(x, n, p = 0.5, alternative = “two.sided”)prop.test(x, n, p = NULL, alternative = “two.sided”, correct = TRUE)" }, { "code": null, "e": 1374, "s": 1056, "text": "Parameters:x = number of successes and failures in data set.n = size of data set.p = probabilities of success. It must be in the range of 0 to 1.alternative = a character string specifying the alternative hypothesis.correct = a logical indicating whether Yates’ continuity correction should be applied where possible." }, { "code": null, "e": 1646, "s": 1374, "text": "Example 1:Let’s assume that 30 out of 70 people recommend Street Food to their friends. To test this claim, a random sample of 150 people obtained. Of these 150 people, 80 indicate that they recommend Street Food to their friend. Is this claim accurate? Use alpha = 0.05." }, { "code": null, "e": 1820, "s": 1646, "text": "Solution:Now given x=.80, P=.30, n=150. We want to know, whether the People recommend street food to their friend than healthy food? Let’s use the function prop.test() in R." }, { "code": "# Using prop.test()prop.test(x = 80, n = 150, p = 0.3, correct = FALSE)", "e": 1911, "s": 1820, "text": null }, { "code": null, "e": 1919, "s": 1911, "text": "Output:" }, { "code": null, "e": 2217, "s": 1919, "text": " 1-sample proportions test without continuity correction\ndata: 80 out of 150, null probability 0.3\nX-squared = 38.889, df = 1, p-value = 4.489e-10\nalternative hypothesis: true p is not equal to 0.3\n95 percent confidence interval:\n0.4536625 0.6113395\nsample estimates:\n p \n0.5333333\n" }, { "code": null, "e": 2254, "s": 2217, "text": "It returns p-value which is 4.186269" }, { "code": null, "e": 2278, "s": 2254, "text": "alternative hypothesis." }, { "code": null, "e": 2306, "s": 2278, "text": "a 95% confidence intervals." }, { "code": null, "e": 2337, "s": 2306, "text": "probability of success is 0.53" }, { "code": null, "e": 2521, "s": 2337, "text": "The p-value of the test is 4.486269, which is less than the significance level alpha = 0.05. The claim that 30 out of 70 People recommend Street Food to their friends is not accurate." }, { "code": null, "e": 2868, "s": 2521, "text": "Example 2:Suppose that current vitamin pills cure 80% of all cases. A new vitamin pill has been discovered or made. In a sample of 150 patients with the lack of vitamins that were treated with the new vitamins, 95 were cured. Do the results of this study support the claim that the new vitamins have a higher cure rate than the existing vitamins?" }, { "code": null, "e": 2949, "s": 2868, "text": "Solution:Now given x=.95, P=.80, n=160. Let’s use the function prop.test() in R." }, { "code": "# Using prop.test() prop.test(x = 95, n = 160, p = 0.8, correct = FALSE)", "e": 3040, "s": 2949, "text": null }, { "code": null, "e": 3048, "s": 3040, "text": "Output:" }, { "code": null, "e": 3346, "s": 3048, "text": " \n 1-sample proportions test without continuity correction\ndata: 95 out of 160, null probability 0.8\nX-squared = 42.539, df = 1, p-value = 6 . 928e-11\nalternative hypothesis: true p is not equal to 0.8\n95 percent confidence interval:\n0.5163169 0.6667870\nsample estimates:\n p \n0.59375\n" }, { "code": null, "e": 3383, "s": 3346, "text": "It returns p-value which is 6.928462" }, { "code": null, "e": 3406, "s": 3383, "text": "alternative hypothesis" }, { "code": null, "e": 3434, "s": 3406, "text": "a 95% confidence intervals." }, { "code": null, "e": 3465, "s": 3434, "text": "probability of success is 0.59" }, { "code": null, "e": 3635, "s": 3465, "text": "The p-value of the test is 6.928462, which is greater than the significance level alpha = 0.05. The claim that 95 out of 160 people cured with new vitamins are accurate." }, { "code": null, "e": 3796, "s": 3635, "text": "Example 3:Suppose that in India 15% of people like Work from home. In a sample of 100 people, the people who like Work from home are 25. Is this claim accurate?" }, { "code": null, "e": 3878, "s": 3796, "text": "Solution:Now given x=.25, P=.15, n=100. Let’s use the function binom.test() in R." }, { "code": "# Using binom.test()binom.test(x =25, n = 100, p = 0.15)", "e": 3935, "s": 3878, "text": null }, { "code": null, "e": 3943, "s": 3935, "text": "Output:" }, { "code": null, "e": 4244, "s": 3943, "text": "Exact binomial test\n\ndata: 25 and 100\nnumber of successes = 25, number of trials = 100, p-value = 0.007633\nalternative hypothesis: true probability of success is not equal to 0.15\n95 percent confidence interval:\n 0.1687797 0.3465525\nsample estimates:\nprobability of success \n 0.25 \n" }, { "code": null, "e": 4281, "s": 4244, "text": "It returns p-value which is 0.007633" }, { "code": null, "e": 4305, "s": 4281, "text": "alternative hypothesis." }, { "code": null, "e": 4333, "s": 4305, "text": "a 95% confidence intervals." }, { "code": null, "e": 4364, "s": 4333, "text": "probability of success is 0.25" }, { "code": null, "e": 4529, "s": 4364, "text": "The p-value of the test is 0.007633 which is less than the significance level alpha = 0.05. The claim that 25 out of 100 people like work form home is not accurate." }, { "code": null, "e": 4542, "s": 4529, "text": "data-science" }, { "code": null, "e": 4549, "s": 4542, "text": "Picked" }, { "code": null, "e": 4568, "s": 4549, "text": "R Machine-Learning" }, { "code": null, "e": 4579, "s": 4568, "text": "R Language" } ]
HTML | <img> alt Attribute
27 May, 2019 The <img> alt attribute is used to specify the alternate text for an image. It is useful when the image not displayed. It is used to give alternative information for an image. Syntax: <img alt="text"> Attribute Values: It contains single value text which specifies the alternative text for an image. Example: <!DOCTYPE html><html> <head> <title> HTML img alt Attribute </title></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML img alt Attribute</h2> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20190506164011/logo3.png" alt="GeeksforGeeks logo"> </body> </html> Output: Supported Browsers: The browser supported by HTML <img> alt Attribute are listed below: Google Chrome Internet Explorer Firefox Safari Opera HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of CSS (Cascading Style Sheet) How to Upload Image into Database and Display it using PHP ? How to Insert Form Data into Database using PHP ? DOM (Document Object Model) How to make elements float to center? Installation of Node.js on Linux Node.js fs.readFileSync() Method How do you run JavaScript script through the Terminal? Node.js | fs.writeFileSync() Method Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 28, "s": 0, "text": "\n27 May, 2019" }, { "code": null, "e": 204, "s": 28, "text": "The <img> alt attribute is used to specify the alternate text for an image. It is useful when the image not displayed. It is used to give alternative information for an image." }, { "code": null, "e": 212, "s": 204, "text": "Syntax:" }, { "code": null, "e": 229, "s": 212, "text": "<img alt=\"text\">" }, { "code": null, "e": 328, "s": 229, "text": "Attribute Values: It contains single value text which specifies the alternative text for an image." }, { "code": null, "e": 337, "s": 328, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML img alt Attribute </title></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML img alt Attribute</h2> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190506164011/logo3.png\" alt=\"GeeksforGeeks logo\"> </body> </html>", "e": 643, "s": 337, "text": null }, { "code": null, "e": 651, "s": 643, "text": "Output:" }, { "code": null, "e": 739, "s": 651, "text": "Supported Browsers: The browser supported by HTML <img> alt Attribute are listed below:" }, { "code": null, "e": 753, "s": 739, "text": "Google Chrome" }, { "code": null, "e": 771, "s": 753, "text": "Internet Explorer" }, { "code": null, "e": 779, "s": 771, "text": "Firefox" }, { "code": null, "e": 786, "s": 779, "text": "Safari" }, { "code": null, "e": 792, "s": 786, "text": "Opera" }, { "code": null, "e": 808, "s": 792, "text": "HTML-Attributes" }, { "code": null, "e": 813, "s": 808, "text": "HTML" }, { "code": null, "e": 830, "s": 813, "text": "Web Technologies" }, { "code": null, "e": 835, "s": 830, "text": "HTML" }, { "code": null, "e": 933, "s": 835, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 970, "s": 933, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 1031, "s": 970, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 1081, "s": 1031, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 1109, "s": 1081, "text": "DOM (Document Object Model)" }, { "code": null, "e": 1147, "s": 1109, "text": "How to make elements float to center?" }, { "code": null, "e": 1180, "s": 1147, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1213, "s": 1180, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 1268, "s": 1213, "text": "How do you run JavaScript script through the Terminal?" }, { "code": null, "e": 1304, "s": 1268, "text": "Node.js | fs.writeFileSync() Method" } ]
Data Analysis with SciPy
26 Apr, 2022 SciPy is a python library that is useful in solving many mathematical equations and algorithms. It is designed on the top of Numpy library that gives more extension of finding scientific mathematical formulae like Matrix Rank, Inverse, polynomial equations, LU Decomposition, etc. Using its high level functions will significantly reduce the complexity of the code and helps in better analyzing the data. SciPy is an interactive Python session used as a data-processing library that is made to compete with its rivalries such as MATLAB, Octave, R-Lab,etc. It has many user-friendly, efficient and easy-to-use functions that helps to solve problems like numerical integration, interpolation, optimization, linear algebra and statistics. The benefit of using SciPy library in Python while making ML models is that it also makes a strong programming language available for use in developing less complex programs and applications. # import numpy libraryimport numpy as npA = np.array([[1,2,3],[4,5,6],[7,8,8]]) Determinant of a Matrix# importing linalg function from scipyfrom scipy import linalg # Compute the determinant of a matrixlinalg.det(A)Output : 2.999999999999997 Compute pivoted LU decomposition of a matrixLU decomposition is a method that reduce matrix into constituent parts that helps in easier calculation of complex matrix operations. The decomposition methods are also called matrix factorization methods, are base of linear algebra in computers, even for basic operations such as solving systems of linear equations, calculating the inverse, and calculating the determinant of a matrix.The decomposition is:A = P L Uwhere P is a permutation matrix, L lower triangular with unit diagonal elements, and U upper triangular.P, L, U = linalg.lu(A)print(P)print(L)print(U)# print LU decompositionprint(np.dot(L,U))Output : array([[ 0., 1., 0.], [ 0., 0., 1.], [ 1., 0., 0.]]) array([[ 1. , 0. , 0. ], [ 0.14285714, 1. , 0. ], [ 0.57142857, 0.5 , 1. ]]) array([[ 7. , 8. , 8. ], [ 0. , 0.85714286, 1.85714286], [ 0. , 0. , 0.5 ]]) array([[ 7., 8., 8.], [ 1., 2., 3.], [ 4., 5., 6.]]) Eigen values and eigen vectors of this matrixeigen_values, eigen_vectors = linalg.eig(A)print(eigen_values)print(eigen_vectors)Output : array([ 15.55528261+0.j, -1.41940876+0.j, -0.13587385+0.j]) array([[-0.24043423, -0.67468642, 0.51853459], [-0.54694322, -0.23391616, -0.78895962], [-0.80190056, 0.70005819, 0.32964312]]) Solving systems of linear equations can also be donev = np.array([[2],[3],[5]])print(v)s = linalg.solve(A,v)print(s)Output : array([[2], [3], [5]]) array([[-2.33333333], [ 3.66666667], [-1. ]]) Determinant of a Matrix# importing linalg function from scipyfrom scipy import linalg # Compute the determinant of a matrixlinalg.det(A)Output : 2.999999999999997 # importing linalg function from scipyfrom scipy import linalg # Compute the determinant of a matrixlinalg.det(A) Output : 2.999999999999997 Compute pivoted LU decomposition of a matrixLU decomposition is a method that reduce matrix into constituent parts that helps in easier calculation of complex matrix operations. The decomposition methods are also called matrix factorization methods, are base of linear algebra in computers, even for basic operations such as solving systems of linear equations, calculating the inverse, and calculating the determinant of a matrix.The decomposition is:A = P L Uwhere P is a permutation matrix, L lower triangular with unit diagonal elements, and U upper triangular.P, L, U = linalg.lu(A)print(P)print(L)print(U)# print LU decompositionprint(np.dot(L,U))Output : array([[ 0., 1., 0.], [ 0., 0., 1.], [ 1., 0., 0.]]) array([[ 1. , 0. , 0. ], [ 0.14285714, 1. , 0. ], [ 0.57142857, 0.5 , 1. ]]) array([[ 7. , 8. , 8. ], [ 0. , 0.85714286, 1.85714286], [ 0. , 0. , 0.5 ]]) array([[ 7., 8., 8.], [ 1., 2., 3.], [ 4., 5., 6.]]) P, L, U = linalg.lu(A)print(P)print(L)print(U)# print LU decompositionprint(np.dot(L,U)) Output : array([[ 0., 1., 0.], [ 0., 0., 1.], [ 1., 0., 0.]]) array([[ 1. , 0. , 0. ], [ 0.14285714, 1. , 0. ], [ 0.57142857, 0.5 , 1. ]]) array([[ 7. , 8. , 8. ], [ 0. , 0.85714286, 1.85714286], [ 0. , 0. , 0.5 ]]) array([[ 7., 8., 8.], [ 1., 2., 3.], [ 4., 5., 6.]]) Eigen values and eigen vectors of this matrixeigen_values, eigen_vectors = linalg.eig(A)print(eigen_values)print(eigen_vectors)Output : array([ 15.55528261+0.j, -1.41940876+0.j, -0.13587385+0.j]) array([[-0.24043423, -0.67468642, 0.51853459], [-0.54694322, -0.23391616, -0.78895962], [-0.80190056, 0.70005819, 0.32964312]]) eigen_values, eigen_vectors = linalg.eig(A)print(eigen_values)print(eigen_vectors) Output : array([ 15.55528261+0.j, -1.41940876+0.j, -0.13587385+0.j]) array([[-0.24043423, -0.67468642, 0.51853459], [-0.54694322, -0.23391616, -0.78895962], [-0.80190056, 0.70005819, 0.32964312]]) Solving systems of linear equations can also be donev = np.array([[2],[3],[5]])print(v)s = linalg.solve(A,v)print(s)Output : array([[2], [3], [5]]) array([[-2.33333333], [ 3.66666667], [-1. ]]) v = np.array([[2],[3],[5]])print(v)s = linalg.solve(A,v)print(s) Output : array([[2], [3], [5]]) array([[-2.33333333], [ 3.66666667], [-1. ]]) SciPy has some routines for computing with sparse and potentially very large matrices. The necessary tools are in the submodule scipy.sparse.Lets look on how to construct a large sparse matrix: # import necessary modulesfrom scipy import sparse# Row-based linked list sparse matrixA = sparse.lil_matrix((1000, 1000))print(A) A[0,:100] = np.random.rand(100)A[1,100:200] = A[0,:100]A.setdiag(np.random.rand(1000))print(A) Output : <1000x1000 sparse matrix of type '' with 0 stored elements in LInked List format> <1000x1000 sparse matrix of type '' with 1199 stored elements in LInked List format> Linear Algebra for Sparse Matricesfrom scipy.sparse import linalg # Convert this matrix to Compressed Sparse Row format.A.tocsr() A = A.tocsr()b = np.random.rand(1000)ans = linalg.spsolve(A, b)# it will print ans array of 1000 sizeprint(ans)Output : array([-2.53380006e+03, -1.25513773e+03, 9.14885544e-01, 2.74521543e+00, 5.99942835e-01, 4.57778093e-01, 1.87104209e-01, 2.15228367e+00, 8.78588432e-01, 1.85105721e+03, 1.00842538e+00, 4.33970632e+00, 5.26601699e+00, 2.17572231e-01, 1.79869079e+00, 3.83800946e-01, 2.57817130e-01, 5.18025462e-01, 1.68672669e+00, 3.07971950e+00, 6.20604437e-01, 1.41365890e-01, 3.18167429e-01, 2.06457302e-01, 8.94813817e-01, 5.06084834e+00, 5.00913942e-01, 1.37391305e+00, 2.32081425e+00, 4.98093749e+00, 1.75492222e+00, 3.17278127e-01, 8.50013844e-01, 1.17524493e+00, 1.70173722e+00, .............)) Linear Algebra for Sparse Matricesfrom scipy.sparse import linalg # Convert this matrix to Compressed Sparse Row format.A.tocsr() A = A.tocsr()b = np.random.rand(1000)ans = linalg.spsolve(A, b)# it will print ans array of 1000 sizeprint(ans)Output : array([-2.53380006e+03, -1.25513773e+03, 9.14885544e-01, 2.74521543e+00, 5.99942835e-01, 4.57778093e-01, 1.87104209e-01, 2.15228367e+00, 8.78588432e-01, 1.85105721e+03, 1.00842538e+00, 4.33970632e+00, 5.26601699e+00, 2.17572231e-01, 1.79869079e+00, 3.83800946e-01, 2.57817130e-01, 5.18025462e-01, 1.68672669e+00, 3.07971950e+00, 6.20604437e-01, 1.41365890e-01, 3.18167429e-01, 2.06457302e-01, 8.94813817e-01, 5.06084834e+00, 5.00913942e-01, 1.37391305e+00, 2.32081425e+00, 4.98093749e+00, 1.75492222e+00, 3.17278127e-01, 8.50013844e-01, 1.17524493e+00, 1.70173722e+00, .............)) from scipy.sparse import linalg # Convert this matrix to Compressed Sparse Row format.A.tocsr() A = A.tocsr()b = np.random.rand(1000)ans = linalg.spsolve(A, b)# it will print ans array of 1000 sizeprint(ans) Output : array([-2.53380006e+03, -1.25513773e+03, 9.14885544e-01, 2.74521543e+00, 5.99942835e-01, 4.57778093e-01, 1.87104209e-01, 2.15228367e+00, 8.78588432e-01, 1.85105721e+03, 1.00842538e+00, 4.33970632e+00, 5.26601699e+00, 2.17572231e-01, 1.79869079e+00, 3.83800946e-01, 2.57817130e-01, 5.18025462e-01, 1.68672669e+00, 3.07971950e+00, 6.20604437e-01, 1.41365890e-01, 3.18167429e-01, 2.06457302e-01, 8.94813817e-01, 5.06084834e+00, 5.00913942e-01, 1.37391305e+00, 2.32081425e+00, 4.98093749e+00, 1.75492222e+00, 3.17278127e-01, 8.50013844e-01, 1.17524493e+00, 1.70173722e+00, .............)) When a function is very difficult to integrate analytically, one simply find a solution through numerical integration methods. SciPy has a capability for doing numerical integration also. Scipy has integration methods in scipy.integrate module. Single IntegralsThe Quad routine is the important function out of SciPy’s integration functions. If integration in over f(x) function where x ranges from a to b, then integral looks like this.The parameters of quad is scipy.integrate.quad(f, a, b), Where ‘f’ is the function to be integrated. Whereas, ‘a’ and ‘b’ are the lower and upper ranges of x limit. Let us see an example of integrating over the range of 0 and 1 with respect to dx.We will first define the function f(x)=e^(-x^2) , this is done using a lambda expression and then use quad routine.import scipy.integratef= lambda x:np.exp(-x**2)# print resultsi = scipy.integrate.quad(f, 0, 1)print(i)(0.7468241328124271, 8.291413475940725e-15) The quad function returns the two values, in which the first number is the value of integral and the second value is the probable error in the value of integral.Double IntegralsThe parameters of dblquad function is scipy.integrate.dblquad(f, a, b, g, h). Where, ‘f’ is the function to be integrated, ‘a’ and ‘b’ are the lower and upper ranges of the x variable, respectively, while ‘g’ and ‘h’ are the functions that tells the lower and upper limits of y variable.As an example, let us perform the double integral of x*y^2 over x range from 0 to 2 and y ranges from 0 to 1.We define the functions f, g, and h, using the lambda expressions. Note that even if g and h are constants, as they may be in many cases, they must be defined as functions, as we have done here for the lower limit.from scipy import integratef = lambda y, x: x*y**2i = integrate.dblquad(f, 0, 2, lambda x: 0, lambda x: 1)# print the resultsprint(i)Output : (0.6666666666666667, 7.401486830834377e-15) Single IntegralsThe Quad routine is the important function out of SciPy’s integration functions. If integration in over f(x) function where x ranges from a to b, then integral looks like this.The parameters of quad is scipy.integrate.quad(f, a, b), Where ‘f’ is the function to be integrated. Whereas, ‘a’ and ‘b’ are the lower and upper ranges of x limit. Let us see an example of integrating over the range of 0 and 1 with respect to dx.We will first define the function f(x)=e^(-x^2) , this is done using a lambda expression and then use quad routine.import scipy.integratef= lambda x:np.exp(-x**2)# print resultsi = scipy.integrate.quad(f, 0, 1)print(i)(0.7468241328124271, 8.291413475940725e-15) The quad function returns the two values, in which the first number is the value of integral and the second value is the probable error in the value of integral. import scipy.integratef= lambda x:np.exp(-x**2)# print resultsi = scipy.integrate.quad(f, 0, 1)print(i) (0.7468241328124271, 8.291413475940725e-15) The quad function returns the two values, in which the first number is the value of integral and the second value is the probable error in the value of integral. Double IntegralsThe parameters of dblquad function is scipy.integrate.dblquad(f, a, b, g, h). Where, ‘f’ is the function to be integrated, ‘a’ and ‘b’ are the lower and upper ranges of the x variable, respectively, while ‘g’ and ‘h’ are the functions that tells the lower and upper limits of y variable.As an example, let us perform the double integral of x*y^2 over x range from 0 to 2 and y ranges from 0 to 1.We define the functions f, g, and h, using the lambda expressions. Note that even if g and h are constants, as they may be in many cases, they must be defined as functions, as we have done here for the lower limit.from scipy import integratef = lambda y, x: x*y**2i = integrate.dblquad(f, 0, 2, lambda x: 0, lambda x: 1)# print the resultsprint(i)Output : (0.6666666666666667, 7.401486830834377e-15) from scipy import integratef = lambda y, x: x*y**2i = integrate.dblquad(f, 0, 2, lambda x: 0, lambda x: 1)# print the resultsprint(i) Output : (0.6666666666666667, 7.401486830834377e-15) There is a lot more that SciPy is capable of, such as Fourier Transforms, Bessel Functions, etc.You can refer the Documentation for more details! data-science Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Linear Regression Reinforcement learning Supervised and Unsupervised learning Decision Tree Introduction with example Search Algorithms in AI Read JSON file using Python Python map() function How to get column names in Pandas dataframe Python Dictionary Different ways to create Pandas Dataframe
[ { "code": null, "e": 52, "s": 24, "text": "\n26 Apr, 2022" }, { "code": null, "e": 788, "s": 52, "text": "SciPy is a python library that is useful in solving many mathematical equations and algorithms. It is designed on the top of Numpy library that gives more extension of finding scientific mathematical formulae like Matrix Rank, Inverse, polynomial equations, LU Decomposition, etc. Using its high level functions will significantly reduce the complexity of the code and helps in better analyzing the data. SciPy is an interactive Python session used as a data-processing library that is made to compete with its rivalries such as MATLAB, Octave, R-Lab,etc. It has many user-friendly, efficient and easy-to-use functions that helps to solve problems like numerical integration, interpolation, optimization, linear algebra and statistics." }, { "code": null, "e": 980, "s": 788, "text": "The benefit of using SciPy library in Python while making ML models is that it also makes a strong programming language available for use in developing less complex programs and applications." }, { "code": "# import numpy libraryimport numpy as npA = np.array([[1,2,3],[4,5,6],[7,8,8]])", "e": 1060, "s": 980, "text": null }, { "code": null, "e": 2900, "s": 1060, "text": "Determinant of a Matrix# importing linalg function from scipyfrom scipy import linalg # Compute the determinant of a matrixlinalg.det(A)Output :\n2.999999999999997\nCompute pivoted LU decomposition of a matrixLU decomposition is a method that reduce matrix into constituent parts that helps in easier calculation of complex matrix operations. The decomposition methods are also called matrix factorization methods, are base of linear algebra in computers, even for basic operations such as solving systems of linear equations, calculating the inverse, and calculating the determinant of a matrix.The decomposition is:A = P L Uwhere P is a permutation matrix, L lower triangular with unit diagonal elements, and U upper triangular.P, L, U = linalg.lu(A)print(P)print(L)print(U)# print LU decompositionprint(np.dot(L,U))Output :\narray([[ 0., 1., 0.],\n [ 0., 0., 1.],\n [ 1., 0., 0.]])\n\narray([[ 1. , 0. , 0. ],\n [ 0.14285714, 1. , 0. ],\n [ 0.57142857, 0.5 , 1. ]])\n\narray([[ 7. , 8. , 8. ],\n [ 0. , 0.85714286, 1.85714286],\n [ 0. , 0. , 0.5 ]])\n\narray([[ 7., 8., 8.],\n [ 1., 2., 3.],\n [ 4., 5., 6.]])\nEigen values and eigen vectors of this matrixeigen_values, eigen_vectors = linalg.eig(A)print(eigen_values)print(eigen_vectors)Output :\narray([ 15.55528261+0.j, -1.41940876+0.j, -0.13587385+0.j])\n\narray([[-0.24043423, -0.67468642, 0.51853459],\n [-0.54694322, -0.23391616, -0.78895962],\n [-0.80190056, 0.70005819, 0.32964312]])\nSolving systems of linear equations can also be donev = np.array([[2],[3],[5]])print(v)s = linalg.solve(A,v)print(s)Output :\narray([[2],\n [3],\n [5]])\n\narray([[-2.33333333],\n [ 3.66666667],\n [-1. ]])\n" }, { "code": null, "e": 3065, "s": 2900, "text": "Determinant of a Matrix# importing linalg function from scipyfrom scipy import linalg # Compute the determinant of a matrixlinalg.det(A)Output :\n2.999999999999997\n" }, { "code": "# importing linalg function from scipyfrom scipy import linalg # Compute the determinant of a matrixlinalg.det(A)", "e": 3180, "s": 3065, "text": null }, { "code": null, "e": 3208, "s": 3180, "text": "Output :\n2.999999999999997\n" }, { "code": null, "e": 4310, "s": 3208, "text": "Compute pivoted LU decomposition of a matrixLU decomposition is a method that reduce matrix into constituent parts that helps in easier calculation of complex matrix operations. The decomposition methods are also called matrix factorization methods, are base of linear algebra in computers, even for basic operations such as solving systems of linear equations, calculating the inverse, and calculating the determinant of a matrix.The decomposition is:A = P L Uwhere P is a permutation matrix, L lower triangular with unit diagonal elements, and U upper triangular.P, L, U = linalg.lu(A)print(P)print(L)print(U)# print LU decompositionprint(np.dot(L,U))Output :\narray([[ 0., 1., 0.],\n [ 0., 0., 1.],\n [ 1., 0., 0.]])\n\narray([[ 1. , 0. , 0. ],\n [ 0.14285714, 1. , 0. ],\n [ 0.57142857, 0.5 , 1. ]])\n\narray([[ 7. , 8. , 8. ],\n [ 0. , 0.85714286, 1.85714286],\n [ 0. , 0. , 0.5 ]])\n\narray([[ 7., 8., 8.],\n [ 1., 2., 3.],\n [ 4., 5., 6.]])\n" }, { "code": "P, L, U = linalg.lu(A)print(P)print(L)print(U)# print LU decompositionprint(np.dot(L,U))", "e": 4399, "s": 4310, "text": null }, { "code": null, "e": 4848, "s": 4399, "text": "Output :\narray([[ 0., 1., 0.],\n [ 0., 0., 1.],\n [ 1., 0., 0.]])\n\narray([[ 1. , 0. , 0. ],\n [ 0.14285714, 1. , 0. ],\n [ 0.57142857, 0.5 , 1. ]])\n\narray([[ 7. , 8. , 8. ],\n [ 0. , 0.85714286, 1.85714286],\n [ 0. , 0. , 0.5 ]])\n\narray([[ 7., 8., 8.],\n [ 1., 2., 3.],\n [ 4., 5., 6.]])\n" }, { "code": null, "e": 5193, "s": 4848, "text": "Eigen values and eigen vectors of this matrixeigen_values, eigen_vectors = linalg.eig(A)print(eigen_values)print(eigen_vectors)Output :\narray([ 15.55528261+0.j, -1.41940876+0.j, -0.13587385+0.j])\n\narray([[-0.24043423, -0.67468642, 0.51853459],\n [-0.54694322, -0.23391616, -0.78895962],\n [-0.80190056, 0.70005819, 0.32964312]])\n" }, { "code": "eigen_values, eigen_vectors = linalg.eig(A)print(eigen_values)print(eigen_vectors)", "e": 5276, "s": 5193, "text": null }, { "code": null, "e": 5494, "s": 5276, "text": "Output :\narray([ 15.55528261+0.j, -1.41940876+0.j, -0.13587385+0.j])\n\narray([[-0.24043423, -0.67468642, 0.51853459],\n [-0.54694322, -0.23391616, -0.78895962],\n [-0.80190056, 0.70005819, 0.32964312]])\n" }, { "code": null, "e": 5725, "s": 5494, "text": "Solving systems of linear equations can also be donev = np.array([[2],[3],[5]])print(v)s = linalg.solve(A,v)print(s)Output :\narray([[2],\n [3],\n [5]])\n\narray([[-2.33333333],\n [ 3.66666667],\n [-1. ]])\n" }, { "code": "v = np.array([[2],[3],[5]])print(v)s = linalg.solve(A,v)print(s)", "e": 5790, "s": 5725, "text": null }, { "code": null, "e": 5905, "s": 5790, "text": "Output :\narray([[2],\n [3],\n [5]])\n\narray([[-2.33333333],\n [ 3.66666667],\n [-1. ]])\n" }, { "code": null, "e": 6099, "s": 5905, "text": "SciPy has some routines for computing with sparse and potentially very large matrices. The necessary tools are in the submodule scipy.sparse.Lets look on how to construct a large sparse matrix:" }, { "code": "# import necessary modulesfrom scipy import sparse# Row-based linked list sparse matrixA = sparse.lil_matrix((1000, 1000))print(A) A[0,:100] = np.random.rand(100)A[1,100:200] = A[0,:100]A.setdiag(np.random.rand(1000))print(A)", "e": 6326, "s": 6099, "text": null }, { "code": null, "e": 6512, "s": 6326, "text": "Output :\n<1000x1000 sparse matrix of type ''\n with 0 stored elements in LInked List format>\n\n<1000x1000 sparse matrix of type ''\n with 1199 stored elements in LInked List format>\n" }, { "code": null, "e": 7440, "s": 6512, "text": "Linear Algebra for Sparse Matricesfrom scipy.sparse import linalg # Convert this matrix to Compressed Sparse Row format.A.tocsr() A = A.tocsr()b = np.random.rand(1000)ans = linalg.spsolve(A, b)# it will print ans array of 1000 sizeprint(ans)Output :\narray([-2.53380006e+03, -1.25513773e+03, 9.14885544e-01, 2.74521543e+00,\n 5.99942835e-01, 4.57778093e-01, 1.87104209e-01, 2.15228367e+00,\n 8.78588432e-01, 1.85105721e+03, 1.00842538e+00, 4.33970632e+00,\n 5.26601699e+00, 2.17572231e-01, 1.79869079e+00, 3.83800946e-01,\n 2.57817130e-01, 5.18025462e-01, 1.68672669e+00, 3.07971950e+00,\n 6.20604437e-01, 1.41365890e-01, 3.18167429e-01, 2.06457302e-01,\n 8.94813817e-01, 5.06084834e+00, 5.00913942e-01, 1.37391305e+00,\n 2.32081425e+00, 4.98093749e+00, 1.75492222e+00, 3.17278127e-01,\n 8.50013844e-01, 1.17524493e+00, 1.70173722e+00, .............))\n" }, { "code": null, "e": 8368, "s": 7440, "text": "Linear Algebra for Sparse Matricesfrom scipy.sparse import linalg # Convert this matrix to Compressed Sparse Row format.A.tocsr() A = A.tocsr()b = np.random.rand(1000)ans = linalg.spsolve(A, b)# it will print ans array of 1000 sizeprint(ans)Output :\narray([-2.53380006e+03, -1.25513773e+03, 9.14885544e-01, 2.74521543e+00,\n 5.99942835e-01, 4.57778093e-01, 1.87104209e-01, 2.15228367e+00,\n 8.78588432e-01, 1.85105721e+03, 1.00842538e+00, 4.33970632e+00,\n 5.26601699e+00, 2.17572231e-01, 1.79869079e+00, 3.83800946e-01,\n 2.57817130e-01, 5.18025462e-01, 1.68672669e+00, 3.07971950e+00,\n 6.20604437e-01, 1.41365890e-01, 3.18167429e-01, 2.06457302e-01,\n 8.94813817e-01, 5.06084834e+00, 5.00913942e-01, 1.37391305e+00,\n 2.32081425e+00, 4.98093749e+00, 1.75492222e+00, 3.17278127e-01,\n 8.50013844e-01, 1.17524493e+00, 1.70173722e+00, .............))\n" }, { "code": "from scipy.sparse import linalg # Convert this matrix to Compressed Sparse Row format.A.tocsr() A = A.tocsr()b = np.random.rand(1000)ans = linalg.spsolve(A, b)# it will print ans array of 1000 sizeprint(ans)", "e": 8578, "s": 8368, "text": null }, { "code": null, "e": 9263, "s": 8578, "text": "Output :\narray([-2.53380006e+03, -1.25513773e+03, 9.14885544e-01, 2.74521543e+00,\n 5.99942835e-01, 4.57778093e-01, 1.87104209e-01, 2.15228367e+00,\n 8.78588432e-01, 1.85105721e+03, 1.00842538e+00, 4.33970632e+00,\n 5.26601699e+00, 2.17572231e-01, 1.79869079e+00, 3.83800946e-01,\n 2.57817130e-01, 5.18025462e-01, 1.68672669e+00, 3.07971950e+00,\n 6.20604437e-01, 1.41365890e-01, 3.18167429e-01, 2.06457302e-01,\n 8.94813817e-01, 5.06084834e+00, 5.00913942e-01, 1.37391305e+00,\n 2.32081425e+00, 4.98093749e+00, 1.75492222e+00, 3.17278127e-01,\n 8.50013844e-01, 1.17524493e+00, 1.70173722e+00, .............))\n" }, { "code": null, "e": 9508, "s": 9263, "text": "When a function is very difficult to integrate analytically, one simply find a solution through numerical integration methods. SciPy has a capability for doing numerical integration also. Scipy has integration methods in scipy.integrate module." }, { "code": null, "e": 11185, "s": 9508, "text": "Single IntegralsThe Quad routine is the important function out of SciPy’s integration functions. If integration in over f(x) function where x ranges from a to b, then integral looks like this.The parameters of quad is scipy.integrate.quad(f, a, b), Where ‘f’ is the function to be integrated. Whereas, ‘a’ and ‘b’ are the lower and upper ranges of x limit. Let us see an example of integrating over the range of 0 and 1 with respect to dx.We will first define the function f(x)=e^(-x^2) , this is done using a lambda expression and then use quad routine.import scipy.integratef= lambda x:np.exp(-x**2)# print resultsi = scipy.integrate.quad(f, 0, 1)print(i)(0.7468241328124271, 8.291413475940725e-15)\nThe quad function returns the two values, in which the first number is the value of integral and the second value is the probable error in the value of integral.Double IntegralsThe parameters of dblquad function is scipy.integrate.dblquad(f, a, b, g, h). Where, ‘f’ is the function to be integrated, ‘a’ and ‘b’ are the lower and upper ranges of the x variable, respectively, while ‘g’ and ‘h’ are the functions that tells the lower and upper limits of y variable.As an example, let us perform the double integral of x*y^2 over x range from 0 to 2 and y ranges from 0 to 1.We define the functions f, g, and h, using the lambda expressions. Note that even if g and h are constants, as they may be in many cases, they must be defined as functions, as we have done here for the lower limit.from scipy import integratef = lambda y, x: x*y**2i = integrate.dblquad(f, 0, 2, lambda x: 0, lambda x: 1)# print the resultsprint(i)Output :\n (0.6666666666666667, 7.401486830834377e-15)\n" }, { "code": null, "e": 12049, "s": 11185, "text": "Single IntegralsThe Quad routine is the important function out of SciPy’s integration functions. If integration in over f(x) function where x ranges from a to b, then integral looks like this.The parameters of quad is scipy.integrate.quad(f, a, b), Where ‘f’ is the function to be integrated. Whereas, ‘a’ and ‘b’ are the lower and upper ranges of x limit. Let us see an example of integrating over the range of 0 and 1 with respect to dx.We will first define the function f(x)=e^(-x^2) , this is done using a lambda expression and then use quad routine.import scipy.integratef= lambda x:np.exp(-x**2)# print resultsi = scipy.integrate.quad(f, 0, 1)print(i)(0.7468241328124271, 8.291413475940725e-15)\nThe quad function returns the two values, in which the first number is the value of integral and the second value is the probable error in the value of integral." }, { "code": "import scipy.integratef= lambda x:np.exp(-x**2)# print resultsi = scipy.integrate.quad(f, 0, 1)print(i)", "e": 12153, "s": 12049, "text": null }, { "code": null, "e": 12198, "s": 12153, "text": "(0.7468241328124271, 8.291413475940725e-15)\n" }, { "code": null, "e": 12360, "s": 12198, "text": "The quad function returns the two values, in which the first number is the value of integral and the second value is the probable error in the value of integral." }, { "code": null, "e": 13174, "s": 12360, "text": "Double IntegralsThe parameters of dblquad function is scipy.integrate.dblquad(f, a, b, g, h). Where, ‘f’ is the function to be integrated, ‘a’ and ‘b’ are the lower and upper ranges of the x variable, respectively, while ‘g’ and ‘h’ are the functions that tells the lower and upper limits of y variable.As an example, let us perform the double integral of x*y^2 over x range from 0 to 2 and y ranges from 0 to 1.We define the functions f, g, and h, using the lambda expressions. Note that even if g and h are constants, as they may be in many cases, they must be defined as functions, as we have done here for the lower limit.from scipy import integratef = lambda y, x: x*y**2i = integrate.dblquad(f, 0, 2, lambda x: 0, lambda x: 1)# print the resultsprint(i)Output :\n (0.6666666666666667, 7.401486830834377e-15)\n" }, { "code": "from scipy import integratef = lambda y, x: x*y**2i = integrate.dblquad(f, 0, 2, lambda x: 0, lambda x: 1)# print the resultsprint(i)", "e": 13308, "s": 13174, "text": null }, { "code": null, "e": 13363, "s": 13308, "text": "Output :\n (0.6666666666666667, 7.401486830834377e-15)\n" }, { "code": null, "e": 13509, "s": 13363, "text": "There is a lot more that SciPy is capable of, such as Fourier Transforms, Bessel Functions, etc.You can refer the Documentation for more details!" }, { "code": null, "e": 13522, "s": 13509, "text": "data-science" }, { "code": null, "e": 13539, "s": 13522, "text": "Machine Learning" }, { "code": null, "e": 13546, "s": 13539, "text": "Python" }, { "code": null, "e": 13563, "s": 13546, "text": "Machine Learning" }, { "code": null, "e": 13661, "s": 13563, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 13684, "s": 13661, "text": "ML | Linear Regression" }, { "code": null, "e": 13707, "s": 13684, "text": "Reinforcement learning" }, { "code": null, "e": 13744, "s": 13707, "text": "Supervised and Unsupervised learning" }, { "code": null, "e": 13784, "s": 13744, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 13808, "s": 13784, "text": "Search Algorithms in AI" }, { "code": null, "e": 13836, "s": 13808, "text": "Read JSON file using Python" }, { "code": null, "e": 13858, "s": 13836, "text": "Python map() function" }, { "code": null, "e": 13902, "s": 13858, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 13920, "s": 13902, "text": "Python Dictionary" } ]
How to detect when an @Input() value changes in Angular?
28 Jul, 2020 @Input() is basically a decorator to bind a property as an input. It is used to pass data i.e property binding from one component to other or we can say, from parent to child component. It is bound with the DOM element. When the DOM element value is changed, Angular automatically updates this property with the changed value. Here we will see how can we use it. Two-way bindings with @Input() One-way binding with ngOnChange() and @Input() First, we will look at Two-way binding.Two-way binding combines input and output in a single notation using ngModel directive. The notation for two-way binding is [()].Here is how we will implement two-way binding. We have a component FormComponent (parent) and ChildComponent (child). When the user enters anything in the text input field of the parent component, the child component detects it.Implementation of Two-way binding:Here we are creating a parent component and adding child to it.form.component.html<div style="border: 1px solid rgb(46, 93, 194); height: 25vh; width: 35vw; padding: 10px 10px; margin: 20px;" > <b>Type here : </b> <input type="text" [(ngModel)]='text' /> <child [message]='text'></child> </div>In child component, we are passing a property ‘message’ which holds the value bound by the input element using ngModel. Here is the FormComponent class:form.component.tsimport { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-form', templateUrl: './form.component.html', styleUrls: ['./form.component.scss']})export class FormComponent implements OnInit { constructor() { } ngOnInit(): void { } public text : string;}This change will get reflected in child component. The ‘message’ will get displayed here. Here is the code for that:child.component.html<div style="border:1px solid rgb(53, 71, 131); width:30vw; height: 12vh; padding: 10px 10px; margin:20px"> <h4> You entered <span>{{message}}</span></h4> </div>In the ChildComponent class, we will import Input so as to detect the message from FormComponent class.child.component.tsimport { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'child', templateUrl: './child.component.html', styleUrls: ['./child.component.scss']})export class ChildComponent { //message will detect the input from FormComponent. @Input() message:string; constructor() { }}This was all about the Two-way binding. Now let’s see how to use One-way binding. Implementation of Two-way binding: Here we are creating a parent component and adding child to it.form.component.html <div style="border: 1px solid rgb(46, 93, 194); height: 25vh; width: 35vw; padding: 10px 10px; margin: 20px;" > <b>Type here : </b> <input type="text" [(ngModel)]='text' /> <child [message]='text'></child> </div> In child component, we are passing a property ‘message’ which holds the value bound by the input element using ngModel. Here is the FormComponent class: form.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-form', templateUrl: './form.component.html', styleUrls: ['./form.component.scss']})export class FormComponent implements OnInit { constructor() { } ngOnInit(): void { } public text : string;} This change will get reflected in child component. The ‘message’ will get displayed here. Here is the code for that:child.component.html <div style="border:1px solid rgb(53, 71, 131); width:30vw; height: 12vh; padding: 10px 10px; margin:20px"> <h4> You entered <span>{{message}}</span></h4> </div> In the ChildComponent class, we will import Input so as to detect the message from FormComponent class. child.component.ts import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'child', templateUrl: './child.component.html', styleUrls: ['./child.component.scss']})export class ChildComponent { //message will detect the input from FormComponent. @Input() message:string; constructor() { }} This was all about the Two-way binding. Now let’s see how to use One-way binding. Implementation of One-way binding with ngOnChange() and @Input():Here is how we will use ngOnChange() to bind the input. The code for childComponent will be same as was the case with two-way binding. However, the FormComponent will have onChange() method getting called. Here is the code for that.form.component.html<div style="border: 1px solid rgb(46, 93, 194); height: 25vh; width: 35vw; padding: 10px 10px; margin: 20px;" > <b>Type here : </b> <input type="text" [ngModel]='text' (ngModelChange)='onChange($event)' /> <child [message]='text'></child></div>Notice the difference between this component and previous code showing Two-way binding. Here, ngModel and ngModelChange both are bound with input element. Since we are using onChange(), we do not need to use @Input() to detect the change.form.component.tsimport { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-form', templateUrl: './form.component.html', styleUrls: ['./form.component.scss']})export class FormComponent implements OnInit { constructor() { } ngOnInit(): void { } public text : string; onChange(UpdatedValue : string) :void { this.text = UpdatedValue; }} Implementation of One-way binding with ngOnChange() and @Input(): Here is how we will use ngOnChange() to bind the input. The code for childComponent will be same as was the case with two-way binding. However, the FormComponent will have onChange() method getting called. Here is the code for that.form.component.html <div style="border: 1px solid rgb(46, 93, 194); height: 25vh; width: 35vw; padding: 10px 10px; margin: 20px;" > <b>Type here : </b> <input type="text" [ngModel]='text' (ngModelChange)='onChange($event)' /> <child [message]='text'></child></div> Notice the difference between this component and previous code showing Two-way binding. Here, ngModel and ngModelChange both are bound with input element. Since we are using onChange(), we do not need to use @Input() to detect the change. form.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-form', templateUrl: './form.component.html', styleUrls: ['./form.component.scss']})export class FormComponent implements OnInit { constructor() { } ngOnInit(): void { } public text : string; onChange(UpdatedValue : string) :void { this.text = UpdatedValue; }} Output: AngularJS-Misc Picked AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jul, 2020" }, { "code": null, "e": 391, "s": 28, "text": "@Input() is basically a decorator to bind a property as an input. It is used to pass data i.e property binding from one component to other or we can say, from parent to child component. It is bound with the DOM element. When the DOM element value is changed, Angular automatically updates this property with the changed value. Here we will see how can we use it." }, { "code": null, "e": 422, "s": 391, "text": "Two-way bindings with @Input()" }, { "code": null, "e": 469, "s": 422, "text": "One-way binding with ngOnChange() and @Input()" }, { "code": null, "e": 2552, "s": 469, "text": "First, we will look at Two-way binding.Two-way binding combines input and output in a single notation using ngModel directive. The notation for two-way binding is [()].Here is how we will implement two-way binding. We have a component FormComponent (parent) and ChildComponent (child). When the user enters anything in the text input field of the parent component, the child component detects it.Implementation of Two-way binding:Here we are creating a parent component and adding child to it.form.component.html<div style=\"border: 1px solid rgb(46, 93, 194); height: 25vh; width: 35vw; padding: 10px 10px; margin: 20px;\" > <b>Type here : </b> <input type=\"text\" [(ngModel)]='text' /> <child [message]='text'></child> </div>In child component, we are passing a property ‘message’ which holds the value bound by the input element using ngModel. Here is the FormComponent class:form.component.tsimport { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-form', templateUrl: './form.component.html', styleUrls: ['./form.component.scss']})export class FormComponent implements OnInit { constructor() { } ngOnInit(): void { } public text : string;}This change will get reflected in child component. The ‘message’ will get displayed here. Here is the code for that:child.component.html<div style=\"border:1px solid rgb(53, 71, 131); width:30vw; height: 12vh; padding: 10px 10px; margin:20px\"> <h4> You entered <span>{{message}}</span></h4> </div>In the ChildComponent class, we will import Input so as to detect the message from FormComponent class.child.component.tsimport { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'child', templateUrl: './child.component.html', styleUrls: ['./child.component.scss']})export class ChildComponent { //message will detect the input from FormComponent. @Input() message:string; constructor() { }}This was all about the Two-way binding. Now let’s see how to use One-way binding." }, { "code": null, "e": 2587, "s": 2552, "text": "Implementation of Two-way binding:" }, { "code": null, "e": 2670, "s": 2587, "text": "Here we are creating a parent component and adding child to it.form.component.html" }, { "code": "<div style=\"border: 1px solid rgb(46, 93, 194); height: 25vh; width: 35vw; padding: 10px 10px; margin: 20px;\" > <b>Type here : </b> <input type=\"text\" [(ngModel)]='text' /> <child [message]='text'></child> </div>", "e": 2944, "s": 2670, "text": null }, { "code": null, "e": 3097, "s": 2944, "text": "In child component, we are passing a property ‘message’ which holds the value bound by the input element using ngModel. Here is the FormComponent class:" }, { "code": null, "e": 3115, "s": 3097, "text": "form.component.ts" }, { "code": "import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-form', templateUrl: './form.component.html', styleUrls: ['./form.component.scss']})export class FormComponent implements OnInit { constructor() { } ngOnInit(): void { } public text : string;}", "e": 3398, "s": 3115, "text": null }, { "code": null, "e": 3535, "s": 3398, "text": "This change will get reflected in child component. The ‘message’ will get displayed here. Here is the code for that:child.component.html" }, { "code": "<div style=\"border:1px solid rgb(53, 71, 131); width:30vw; height: 12vh; padding: 10px 10px; margin:20px\"> <h4> You entered <span>{{message}}</span></h4> </div>", "e": 3743, "s": 3535, "text": null }, { "code": null, "e": 3847, "s": 3743, "text": "In the ChildComponent class, we will import Input so as to detect the message from FormComponent class." }, { "code": null, "e": 3866, "s": 3847, "text": "child.component.ts" }, { "code": "import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'child', templateUrl: './child.component.html', styleUrls: ['./child.component.scss']})export class ChildComponent { //message will detect the input from FormComponent. @Input() message:string; constructor() { }}", "e": 4168, "s": 3866, "text": null }, { "code": null, "e": 4250, "s": 4168, "text": "This was all about the Two-way binding. Now let’s see how to use One-way binding." }, { "code": null, "e": 5493, "s": 4250, "text": "Implementation of One-way binding with ngOnChange() and @Input():Here is how we will use ngOnChange() to bind the input. The code for childComponent will be same as was the case with two-way binding. However, the FormComponent will have onChange() method getting called. Here is the code for that.form.component.html<div style=\"border: 1px solid rgb(46, 93, 194); height: 25vh; width: 35vw; padding: 10px 10px; margin: 20px;\" > <b>Type here : </b> <input type=\"text\" [ngModel]='text' (ngModelChange)='onChange($event)' /> <child [message]='text'></child></div>Notice the difference between this component and previous code showing Two-way binding. Here, ngModel and ngModelChange both are bound with input element. Since we are using onChange(), we do not need to use @Input() to detect the change.form.component.tsimport { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-form', templateUrl: './form.component.html', styleUrls: ['./form.component.scss']})export class FormComponent implements OnInit { constructor() { } ngOnInit(): void { } public text : string; onChange(UpdatedValue : string) :void { this.text = UpdatedValue; }}" }, { "code": null, "e": 5559, "s": 5493, "text": "Implementation of One-way binding with ngOnChange() and @Input():" }, { "code": null, "e": 5811, "s": 5559, "text": "Here is how we will use ngOnChange() to bind the input. The code for childComponent will be same as was the case with two-way binding. However, the FormComponent will have onChange() method getting called. Here is the code for that.form.component.html" }, { "code": "<div style=\"border: 1px solid rgb(46, 93, 194); height: 25vh; width: 35vw; padding: 10px 10px; margin: 20px;\" > <b>Type here : </b> <input type=\"text\" [ngModel]='text' (ngModelChange)='onChange($event)' /> <child [message]='text'></child></div>", "e": 6127, "s": 5811, "text": null }, { "code": null, "e": 6366, "s": 6127, "text": "Notice the difference between this component and previous code showing Two-way binding. Here, ngModel and ngModelChange both are bound with input element. Since we are using onChange(), we do not need to use @Input() to detect the change." }, { "code": null, "e": 6384, "s": 6366, "text": "form.component.ts" }, { "code": "import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-form', templateUrl: './form.component.html', styleUrls: ['./form.component.scss']})export class FormComponent implements OnInit { constructor() { } ngOnInit(): void { } public text : string; onChange(UpdatedValue : string) :void { this.text = UpdatedValue; }}", "e": 6741, "s": 6384, "text": null }, { "code": null, "e": 6749, "s": 6741, "text": "Output:" }, { "code": null, "e": 6764, "s": 6749, "text": "AngularJS-Misc" }, { "code": null, "e": 6771, "s": 6764, "text": "Picked" }, { "code": null, "e": 6781, "s": 6771, "text": "AngularJS" }, { "code": null, "e": 6798, "s": 6781, "text": "Web Technologies" } ]
React Native style Prop
28 Apr, 2021 In React Native, we can style our application using JavaScript. All of the core components accept a prop named style. The style names and values usually match how CSS works on the web, except names are written using camel casing. The style prop can be a plain old JavaScript object. We can also pass an array of styles. Syntax: <component_tag style={styles.bigBlue}>...</component_tag> OR <component_tag style={[styles.bigBlue, styles.red]}>...</component_tag> Now let’s start with the implementation: Step 1: Open your terminal and install expo-cli by the following command.npm install -g expo-cli Step 1: Open your terminal and install expo-cli by the following command. npm install -g expo-cli Step 2: Now create a project by the following command.expo init myapp Step 2: Now create a project by the following command. expo init myapp Step 3: Now go into your project folder i.e. myappcd myapp Step 3: Now go into your project folder i.e. myapp cd myapp Project Structure: Example: Now let’s style any text or any component by using the style prop. Here we will set the background-color green to make the button center. App.js import React from 'react';import { StyleSheet, Text, View, Button, Alert } from 'react-native'; export default function App() { // Alert functionconst alert = ()=>{ Alert.alert( "GeeksforGeeks", "A Computer Science Portal", [ { text: "Cancel", }, { text: "Agree", } ] );} return ( <View style={styles.container}> <Button title={"Register"} onPress={alert}/> </View>);} const styles = StyleSheet.create({container: { flex: 1, backgroundColor: 'green', alignItems: 'center', justifyContent: 'center',},}); Start the server by using the following command. npm run android Output: If your emulator did not open automatically then you need to do it manually. First, go to your android studio and run the emulator. Now start the server again. Reference: https://reactnative.dev/docs/style Picked React-Native 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 How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array REST API (Introduction) Difference Between PUT and PATCH Request ReactJS | Router How to float three div side by side using CSS? Design a Tribute Page using HTML & CSS Roadmap to Learn JavaScript For Beginners
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Apr, 2021" }, { "code": null, "e": 258, "s": 28, "text": "In React Native, we can style our application using JavaScript. All of the core components accept a prop named style. The style names and values usually match how CSS works on the web, except names are written using camel casing." }, { "code": null, "e": 348, "s": 258, "text": "The style prop can be a plain old JavaScript object. We can also pass an array of styles." }, { "code": null, "e": 356, "s": 348, "text": "Syntax:" }, { "code": null, "e": 489, "s": 356, "text": "<component_tag style={styles.bigBlue}>...</component_tag>\nOR\n<component_tag style={[styles.bigBlue, styles.red]}>...</component_tag>" }, { "code": null, "e": 530, "s": 489, "text": "Now let’s start with the implementation:" }, { "code": null, "e": 627, "s": 530, "text": "Step 1: Open your terminal and install expo-cli by the following command.npm install -g expo-cli" }, { "code": null, "e": 701, "s": 627, "text": "Step 1: Open your terminal and install expo-cli by the following command." }, { "code": null, "e": 725, "s": 701, "text": "npm install -g expo-cli" }, { "code": null, "e": 795, "s": 725, "text": "Step 2: Now create a project by the following command.expo init myapp" }, { "code": null, "e": 850, "s": 795, "text": "Step 2: Now create a project by the following command." }, { "code": null, "e": 866, "s": 850, "text": "expo init myapp" }, { "code": null, "e": 925, "s": 866, "text": "Step 3: Now go into your project folder i.e. myappcd myapp" }, { "code": null, "e": 976, "s": 925, "text": "Step 3: Now go into your project folder i.e. myapp" }, { "code": null, "e": 985, "s": 976, "text": "cd myapp" }, { "code": null, "e": 1004, "s": 985, "text": "Project Structure:" }, { "code": null, "e": 1151, "s": 1004, "text": "Example: Now let’s style any text or any component by using the style prop. Here we will set the background-color green to make the button center." }, { "code": null, "e": 1158, "s": 1151, "text": "App.js" }, { "code": "import React from 'react';import { StyleSheet, Text, View, Button, Alert } from 'react-native'; export default function App() { // Alert functionconst alert = ()=>{ Alert.alert( \"GeeksforGeeks\", \"A Computer Science Portal\", [ { text: \"Cancel\", }, { text: \"Agree\", } ] );} return ( <View style={styles.container}> <Button title={\"Register\"} onPress={alert}/> </View>);} const styles = StyleSheet.create({container: { flex: 1, backgroundColor: 'green', alignItems: 'center', justifyContent: 'center',},});", "e": 1784, "s": 1158, "text": null }, { "code": null, "e": 1833, "s": 1784, "text": "Start the server by using the following command." }, { "code": null, "e": 1849, "s": 1833, "text": "npm run android" }, { "code": null, "e": 2018, "s": 1849, "text": "Output: If your emulator did not open automatically then you need to do it manually. First, go to your android studio and run the emulator. Now start the server again. " }, { "code": null, "e": 2064, "s": 2018, "text": "Reference: https://reactnative.dev/docs/style" }, { "code": null, "e": 2071, "s": 2064, "text": "Picked" }, { "code": null, "e": 2084, "s": 2071, "text": "React-Native" }, { "code": null, "e": 2101, "s": 2084, "text": "Web Technologies" }, { "code": null, "e": 2199, "s": 2101, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2260, "s": 2199, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2303, "s": 2260, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 2375, "s": 2303, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2415, "s": 2375, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2439, "s": 2415, "text": "REST API (Introduction)" }, { "code": null, "e": 2480, "s": 2439, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2497, "s": 2480, "text": "ReactJS | Router" }, { "code": null, "e": 2544, "s": 2497, "text": "How to float three div side by side using CSS?" }, { "code": null, "e": 2583, "s": 2544, "text": "Design a Tribute Page using HTML & CSS" } ]