title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How to implement toggle using ReactJS ?
08 Apr, 2021 If we want to implement toggle functionality to a button, then we can have states in our component that will either be true or false and based on the value of state we can implement toggle functionality. When we click on the button and the current value of the state is true then we changed it to false and vice versa. When we change the state the component will re-render and based on the value of state content will display. Creating React Application: 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 Project Structure: Example: Here we will create a button component to toggle, we will use the JavaScript this keyword as well. App.js import React from 'react' class Counter extends React.Component { render() { return( <div> <Button text = "Hello from GFG"> </Button> </div> ) }} class Button extends React.Component{ state = { textflag: false, } ToggleButton() { this.setState( {textflag : !this.state.textflag} ); } render() { return( <div> <button onClick={() => this.ToggleButton()}> { this.state.textflag === false ? "Hide":"Show" } </button> {!this.state.textflag && this.props.text} </div> ) }} export default Counter; Output: Picked React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Axios in React: A Guide for Beginners ReactJS setState() How to pass data from one component to other component in ReactJS ? Re-rendering Components in ReactJS ReactJS defaultProps Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Apr, 2021" }, { "code": null, "e": 455, "s": 28, "text": "If we want to implement toggle functionality to a button, then we can have states in our component that will either be true or false and based on the value of state we can implement toggle functionality. When we click on the button and the current value of the state is true then we changed it to false and vice versa. When we change the state the component will re-render and based on the value of state content will display." }, { "code": null, "e": 483, "s": 455, "text": "Creating React Application:" }, { "code": null, "e": 547, "s": 483, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 579, "s": 547, "text": "npx create-react-app foldername" }, { "code": null, "e": 679, "s": 579, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 693, "s": 679, "text": "cd foldername" }, { "code": null, "e": 713, "s": 693, "text": "Project Structure: " }, { "code": null, "e": 821, "s": 713, "text": "Example: Here we will create a button component to toggle, we will use the JavaScript this keyword as well." }, { "code": null, "e": 828, "s": 821, "text": "App.js" }, { "code": "import React from 'react' class Counter extends React.Component { render() { return( <div> <Button text = \"Hello from GFG\"> </Button> </div> ) }} class Button extends React.Component{ state = { textflag: false, } ToggleButton() { this.setState( {textflag : !this.state.textflag} ); } render() { return( <div> <button onClick={() => this.ToggleButton()}> { this.state.textflag === false ? \"Hide\":\"Show\" } </button> {!this.state.textflag && this.props.text} </div> ) }} export default Counter;", "e": 1542, "s": 828, "text": null }, { "code": null, "e": 1550, "s": 1542, "text": "Output:" }, { "code": null, "e": 1557, "s": 1550, "text": "Picked" }, { "code": null, "e": 1573, "s": 1557, "text": "React-Questions" }, { "code": null, "e": 1581, "s": 1573, "text": "ReactJS" }, { "code": null, "e": 1598, "s": 1581, "text": "Web Technologies" }, { "code": null, "e": 1696, "s": 1598, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1734, "s": 1696, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 1753, "s": 1734, "text": "ReactJS setState()" }, { "code": null, "e": 1821, "s": 1753, "text": "How to pass data from one component to other component in ReactJS ?" }, { "code": null, "e": 1856, "s": 1821, "text": "Re-rendering Components in ReactJS" }, { "code": null, "e": 1877, "s": 1856, "text": "ReactJS defaultProps" }, { "code": null, "e": 1910, "s": 1877, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1972, "s": 1910, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2033, "s": 1972, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2083, "s": 2033, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Reset Index in Pandas Dataframe
04 Dec, 2018 Let’s discuss how to reset index in Pandas DataFrame. Often We start with a huge dataframe in Pandas and after manipulating/filtering the dataframe, we end up with much smaller dataframe. When we look at the smaller dataframe, it might still carry the row index of the original dataframe. If the original index are numbers, now we have indexes that are not continuous. Well, pandas has reset_index() function. So to reset the index to the default integer index beginning at 0, We can simply use the reset_index() function. So let’s see the different ways we can reset the index of a DataFrame. First see original DataFrame. # Import pandas packageimport pandas as pd # Define a dictionary containing employee datadata = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj', 'Geeku'], 'Age':[27, 24, 22, 32, 15], 'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj', 'Noida'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd', '10th'] } # Convert the dictionary into DataFrame df = pd.DataFrame(data) df Output: Example #1: Make Own Index Without Removing Default index. # Import pandas packageimport pandas as pd # Define a dictionary containing employee datadata = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj', 'Geeku'], 'Age':[27, 24, 22, 32, 15], 'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj', 'Noida'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd', '10th'] } index = {'a', 'b', 'c', 'd', 'e'} # Convert the dictionary into DataFrame df = pd.DataFrame(data, index) # Make Own Index as index# In this case default index is exist df.reset_index(inplace = True) df Output: Example #2: Make Own Index and Removing Default index. # Import pandas packageimport pandas as pd # Define a dictionary containing employee datadata = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj', 'Geeku'], 'Age':[27, 24, 22, 32, 15], 'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj', 'Noida'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd', '10th'] } # Create own indexindex = {'a', 'b', 'c', 'd', 'e'} # Convert the dictionary into DataFrame # Make Own Index and Removing Default indexdf = pd.DataFrame(data, index) df Output: Example 3: Reset own index and make default index as index. # Import pandas packageimport pandas as pd # Define a dictionary containing employee datadata = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj', 'Geeku'], 'Age':[27, 24, 22, 32, 15], 'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj', 'Noida'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd', '10th'] } # Create own indexindex = {'a', 'b', 'c', 'd', 'e'} # Convert the dictionary into DataFrame df = pd.DataFrame(data, index) # remove own index with default indexdf.reset_index(inplace = True, drop = True) df Output: Example #4: Make a column of dataframe as index with remove default index. # Import pandas packageimport pandas as pd # Define a dictionary containing employee datadata = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj', 'Geeku'], 'Age':[27, 24, 22, 32, 15], 'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj', 'Noida'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd', '10th'] } # Create own indexindex = {'a', 'b', 'c', 'd', 'e'} # Convert the dictionary into DataFrame df = pd.DataFrame(data, index) # set index any column of our DF and# remove default indexdf.set_index(['Age'], inplace = True) df Output: Example 5: Make a column of dataframe as index without remove default index. # Import pandas packageimport pandas as pd # Define a dictionary containing employee datadata = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj', 'Geeku'], 'Age':[27, 24, 22, 32, 15], 'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj', 'Noida'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd', '10th'] } # Create own indexindex = {'a', 'b', 'c', 'd', 'e'} # Convert the dictionary into DataFrame df = pd.DataFrame(data, index) # set any column as index# Here we set age column as indexdf.set_index(['Age'], inplace = True) # reset index without removing default indexdf.reset_index(level =['Age'], inplace = True) df Output: pandas-dataframe-program Picked Python pandas-dataFrame Python-pandas Technical Scripter 2018 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 Iterate over a list in Python Convert integer to string in Python Python OOPs Concepts Introduction To PYTHON
[ { "code": null, "e": 54, "s": 26, "text": "\n04 Dec, 2018" }, { "code": null, "e": 242, "s": 54, "text": "Let’s discuss how to reset index in Pandas DataFrame. Often We start with a huge dataframe in Pandas and after manipulating/filtering the dataframe, we end up with much smaller dataframe." }, { "code": null, "e": 577, "s": 242, "text": "When we look at the smaller dataframe, it might still carry the row index of the original dataframe. If the original index are numbers, now we have indexes that are not continuous. Well, pandas has reset_index() function. So to reset the index to the default integer index beginning at 0, We can simply use the reset_index() function." }, { "code": null, "e": 648, "s": 577, "text": "So let’s see the different ways we can reset the index of a DataFrame." }, { "code": null, "e": 678, "s": 648, "text": "First see original DataFrame." }, { "code": "# Import pandas packageimport pandas as pd # Define a dictionary containing employee datadata = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj', 'Geeku'], 'Age':[27, 24, 22, 32, 15], 'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj', 'Noida'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd', '10th'] } # Convert the dictionary into DataFrame df = pd.DataFrame(data) df", "e": 1067, "s": 678, "text": null }, { "code": null, "e": 1075, "s": 1067, "text": "Output:" }, { "code": null, "e": 1135, "s": 1075, "text": " Example #1: Make Own Index Without Removing Default index." }, { "code": "# Import pandas packageimport pandas as pd # Define a dictionary containing employee datadata = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj', 'Geeku'], 'Age':[27, 24, 22, 32, 15], 'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj', 'Noida'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd', '10th'] } index = {'a', 'b', 'c', 'd', 'e'} # Convert the dictionary into DataFrame df = pd.DataFrame(data, index) # Make Own Index as index# In this case default index is exist df.reset_index(inplace = True) df", "e": 1661, "s": 1135, "text": null }, { "code": null, "e": 1724, "s": 1661, "text": "Output: Example #2: Make Own Index and Removing Default index." }, { "code": "# Import pandas packageimport pandas as pd # Define a dictionary containing employee datadata = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj', 'Geeku'], 'Age':[27, 24, 22, 32, 15], 'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj', 'Noida'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd', '10th'] } # Create own indexindex = {'a', 'b', 'c', 'd', 'e'} # Convert the dictionary into DataFrame # Make Own Index and Removing Default indexdf = pd.DataFrame(data, index) df", "e": 2216, "s": 1724, "text": null }, { "code": null, "e": 2224, "s": 2216, "text": "Output:" }, { "code": null, "e": 2285, "s": 2224, "text": " Example 3: Reset own index and make default index as index." }, { "code": "# Import pandas packageimport pandas as pd # Define a dictionary containing employee datadata = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj', 'Geeku'], 'Age':[27, 24, 22, 32, 15], 'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj', 'Noida'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd', '10th'] } # Create own indexindex = {'a', 'b', 'c', 'd', 'e'} # Convert the dictionary into DataFrame df = pd.DataFrame(data, index) # remove own index with default indexdf.reset_index(inplace = True, drop = True) df", "e": 2816, "s": 2285, "text": null }, { "code": null, "e": 2899, "s": 2816, "text": "Output: Example #4: Make a column of dataframe as index with remove default index." }, { "code": "# Import pandas packageimport pandas as pd # Define a dictionary containing employee datadata = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj', 'Geeku'], 'Age':[27, 24, 22, 32, 15], 'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj', 'Noida'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd', '10th'] } # Create own indexindex = {'a', 'b', 'c', 'd', 'e'} # Convert the dictionary into DataFrame df = pd.DataFrame(data, index) # set index any column of our DF and# remove default indexdf.set_index(['Age'], inplace = True) df", "e": 3445, "s": 2899, "text": null }, { "code": null, "e": 3530, "s": 3445, "text": "Output: Example 5: Make a column of dataframe as index without remove default index." }, { "code": "# Import pandas packageimport pandas as pd # Define a dictionary containing employee datadata = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj', 'Geeku'], 'Age':[27, 24, 22, 32, 15], 'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj', 'Noida'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd', '10th'] } # Create own indexindex = {'a', 'b', 'c', 'd', 'e'} # Convert the dictionary into DataFrame df = pd.DataFrame(data, index) # set any column as index# Here we set age column as indexdf.set_index(['Age'], inplace = True) # reset index without removing default indexdf.reset_index(level =['Age'], inplace = True) df", "e": 4168, "s": 3530, "text": null }, { "code": null, "e": 4176, "s": 4168, "text": "Output:" }, { "code": null, "e": 4201, "s": 4176, "text": "pandas-dataframe-program" }, { "code": null, "e": 4208, "s": 4201, "text": "Picked" }, { "code": null, "e": 4232, "s": 4208, "text": "Python pandas-dataFrame" }, { "code": null, "e": 4246, "s": 4232, "text": "Python-pandas" }, { "code": null, "e": 4270, "s": 4246, "text": "Technical Scripter 2018" }, { "code": null, "e": 4277, "s": 4270, "text": "Python" }, { "code": null, "e": 4375, "s": 4277, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4393, "s": 4375, "text": "Python Dictionary" }, { "code": null, "e": 4435, "s": 4393, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 4457, "s": 4435, "text": "Enumerate() in Python" }, { "code": null, "e": 4489, "s": 4457, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4518, "s": 4489, "text": "*args and **kwargs in Python" }, { "code": null, "e": 4545, "s": 4518, "text": "Python Classes and Objects" }, { "code": null, "e": 4575, "s": 4545, "text": "Iterate over a list in Python" }, { "code": null, "e": 4611, "s": 4575, "text": "Convert integer to string in Python" }, { "code": null, "e": 4632, "s": 4611, "text": "Python OOPs Concepts" } ]
Print path from root to a given node in a binary tree
24 Nov, 2021 Given a binary tree with distinct nodes(no two nodes have the same data values). The problem is to print the path from root to a given node x. If node x is not present then print “No Path”. Examples: Input : 1 / \ 2 3 / \ / \ 4 5 6 7 x = 5 Output : 1->2->5 Approach: Create a recursive function that traverses the different path in the binary tree to find the required node x. If node x is present then it returns true and accumulates the path nodes in some array arr[]. Else it returns false.Following are the cases during the traversal: If root = NULL, return false.push the root’s data into arr[].if root’s data = x, return true.if node x is present in root’s left or right subtree, return true.Else remove root’s data value from arr[] and return false. If root = NULL, return false. push the root’s data into arr[]. if root’s data = x, return true. if node x is present in root’s left or right subtree, return true. Else remove root’s data value from arr[] and return false. This recursive function can be accessed from other function to check whether node x is present or not and if it is present, then the path nodes can be accessed from arr[]. You can define arr[] globally or pass its reference to the recursive function. C++ Java Python3 C# Javascript // C++ implementation to print the path from root// to a given node in a binary tree#include <bits/stdc++.h>using namespace std; // structure of a node of binary treestruct Node{ int data; Node *left, *right;}; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct Node* getNode(int data){ struct Node *newNode = new Node; newNode->data = data; newNode->left = newNode->right = NULL; return newNode;} // Returns true if there is a path from root// to the given node. It also populates// 'arr' with the given pathbool hasPath(Node *root, vector<int>& arr, int x){ // if root is NULL // there is no path if (!root) return false; // push the node's value in 'arr' arr.push_back(root->data); // if it is the required node // return true if (root->data == x) return true; // else check whether the required node lies // in the left subtree or right subtree of // the current node if (hasPath(root->left, arr, x) || hasPath(root->right, arr, x)) return true; // required node does not lie either in the // left or right subtree of the current node // Thus, remove current node's value from // 'arr'and then return false arr.pop_back(); return false; } // function to print the path from root to the// given node if the node lies in the binary treevoid printPath(Node *root, int x){ // vector to store the path vector<int> arr; // if required node 'x' is present // then print the path if (hasPath(root, arr, x)) { for (int i=0; i<arr.size()-1; i++) cout << arr[i] << "->"; cout << arr[arr.size() - 1]; } // 'x' is not present in the binary tree else cout << "No Path";} // Driver program to test aboveint main(){ // binary tree formation struct Node *root = getNode(1); root->left = getNode(2); root->right = getNode(3); root->left->left = getNode(4); root->left->right = getNode(5); root->right->left = getNode(6); root->right->right = getNode(7); int x = 5; printPath(root, x); return 0;} // Java implementation to print the path from root// to a given node in a binary treeimport java.util.ArrayList;public class PrintPath { // Returns true if there is a path from root // to the given node. It also populates // 'arr' with the given path public static boolean hasPath(Node root, ArrayList<Integer> arr, int x) { // if root is NULL // there is no path if (root==null) return false; // push the node's value in 'arr' arr.add(root.data); // if it is the required node // return true if (root.data == x) return true; // else check whether the required node lies // in the left subtree or right subtree of // the current node if (hasPath(root.left, arr, x) || hasPath(root.right, arr, x)) return true; // required node does not lie either in the // left or right subtree of the current node // Thus, remove current node's value from // 'arr'and then return false arr.remove(arr.size()-1); return false; } // function to print the path from root to the // given node if the node lies in the binary tree public static void printPath(Node root, int x) { // ArrayList to store the path ArrayList<Integer> arr=new ArrayList<>(); // if required node 'x' is present // then print the path if (hasPath(root, arr, x)) { for (int i=0; i<arr.size()-1; i++) System.out.print(arr.get(i)+"->"); System.out.print(arr.get(arr.size() - 1)); } // 'x' is not present in the binary tree else System.out.print("No Path"); } public static void main(String args[]) { Node root=new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(6); root.right.right = new Node(7); int x=5; printPath(root, x); }} // A node of binary treeclass Node{ int data; Node left, right; Node(int data) { this.data=data; left=right=null; }};//This code is contributed by Gaurav Tiwari # Python3 implementation to print the path from# root to a given node in a binary tree # Helper Class that allocates a new node# with the given data and None left and# right pointers.class getNode: def __init__(self, data): self.data = data self.left = self.right = None # Returns true if there is a path from# root to the given node. It also# populates 'arr' with the given pathdef hasPath(root, arr, x): # if root is None there is no path if (not root): return False # push the node's value in 'arr' arr.append(root.data) # if it is the required node # return true if (root.data == x): return True # else check whether the required node # lies in the left subtree or right # subtree of the current node if (hasPath(root.left, arr, x) or hasPath(root.right, arr, x)): return True # required node does not lie either in # the left or right subtree of the current # node. Thus, remove current node's value # from 'arr'and then return false arr.pop(-1) return False # function to print the path from root to# the given node if the node lies in# the binary treedef printPath(root, x): # vector to store the path arr = [] # if required node 'x' is present # then print the path if (hasPath(root, arr, x)): for i in range(len(arr) - 1): print(arr[i], end = "->") print(arr[len(arr) - 1]) # 'x' is not present in the # binary tree else: print("No Path") # Driver Codeif __name__ == '__main__': # binary tree formation root = getNode(1) root.left = getNode(2) root.right = getNode(3) root.left.left = getNode(4) root.left.right = getNode(5) root.right.left = getNode(6) root.right.right = getNode(7) x = 5 printPath(root, x) # This code is contributed by PranchalK // C# implementation to print the path from root// to a given node in a binary treeusing System;using System.Collections;using System.Collections.Generic; class PrintPath{ // A node of binary treepublic class Node{ public int data; public Node left, right; public Node(int data) { this.data = data; left = right = null; }} // Returns true if there is a path from root // to the given node. It also populates // 'arr' with the given path public static Boolean hasPath(Node root, List<int> arr, int x) { // if root is NULL // there is no path if (root == null) return false; // push the node's value in 'arr' arr.Add(root.data); // if it is the required node // return true if (root.data == x) return true; // else check whether the required node lies // in the left subtree or right subtree of // the current node if (hasPath(root.left, arr, x) || hasPath(root.right, arr, x)) return true; // required node does not lie either in the // left or right subtree of the current node // Thus, remove current node's value from // 'arr'and then return false arr.RemoveAt(arr.Count - 1); return false; } // function to print the path from root to the // given node if the node lies in the binary tree public static void printPath(Node root, int x) { // List to store the path List<int> arr = new List<int>(); // if required node 'x' is present // then print the path if (hasPath(root, arr, x)) { for (int i = 0; i < arr.Count - 1; i++) Console.Write(arr[i]+"->"); Console.Write(arr[arr.Count - 1]); } // 'x' is not present in the binary tree else Console.Write("No Path"); } // Driver code public static void Main(String []args) { Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(6); root.right.right = new Node(7); int x=5; printPath(root, x); }} // This code is contributed by Arnab Kundu <script> // Javascript implementation to print// the path from root to a given node// in a binary treeclass Node{ constructor(data) { this.left = null; this.right = null; this.data = data; }} // Returns true if there is a path from root// to the given node. It also populates // 'arr' with the given pathfunction hasPath(root, arr, x){ // If root is NULL // there is no path if (root == null) return false; // Push the node's value in 'arr' arr.push(root.data); // If it is the required node // return true if (root.data == x) return true; // Else check whether the required node lies // in the left subtree or right subtree of // the current node if (hasPath(root.left, arr, x) || hasPath(root.right, arr, x)) return true; // Required node does not lie either in the // left or right subtree of the current node // Thus, remove current node's value from // 'arr'and then return false arr.pop(); return false; } // Function to print the path from root to the// given node if the node lies in the binary treefunction printPath(root, x){ // ArrayList to store the path let arr = []; // If required node 'x' is present // then print the path if (hasPath(root, arr, x)) { for(let i = 0; i < arr.length - 1; i++) document.write(arr[i] + "->"); document.write(arr[arr.length - 1]); } // 'x' is not present in the binary tree else document.write("No Path");} // Driver codelet root = new Node(1);root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.left.right = new Node(5);root.right.left = new Node(6);root.right.right = new Node(7); let x = 5;printPath(root, x); // This code is contributed by divyeshrabadiya07 </script> Output: 1->2->5 Time complexity: O(n) in worst case, where n is the number of nodes in the binary tree. This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. _Gaurav_Tiwari PranchalKatiyar andrew1234 nidhi_biet divyeshrabadiya07 snehilgupta92 Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. AVL Tree | Set 1 (Insertion) Introduction to Data Structures What is Data Structure: Types, Classifications and Applications A program to check if a binary tree is BST or not Decision Tree Top 50 Tree Coding Problems for Interviews Segment Tree | Set 1 (Sum of given range) Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash) Complexity of different operations in Binary tree, Binary Search Tree and AVL tree Sorted Array to Balanced BST
[ { "code": null, "e": 54, "s": 26, "text": "\n24 Nov, 2021" }, { "code": null, "e": 244, "s": 54, "text": "Given a binary tree with distinct nodes(no two nodes have the same data values). The problem is to print the path from root to a given node x. If node x is not present then print “No Path”." }, { "code": null, "e": 255, "s": 244, "text": "Examples: " }, { "code": null, "e": 406, "s": 255, "text": "Input : 1\n / \\\n 2 3\n / \\ / \\\n 4 5 6 7\n\n x = 5\n\nOutput : 1->2->5" }, { "code": null, "e": 689, "s": 406, "text": "Approach: Create a recursive function that traverses the different path in the binary tree to find the required node x. If node x is present then it returns true and accumulates the path nodes in some array arr[]. Else it returns false.Following are the cases during the traversal: " }, { "code": null, "e": 907, "s": 689, "text": "If root = NULL, return false.push the root’s data into arr[].if root’s data = x, return true.if node x is present in root’s left or right subtree, return true.Else remove root’s data value from arr[] and return false." }, { "code": null, "e": 937, "s": 907, "text": "If root = NULL, return false." }, { "code": null, "e": 970, "s": 937, "text": "push the root’s data into arr[]." }, { "code": null, "e": 1003, "s": 970, "text": "if root’s data = x, return true." }, { "code": null, "e": 1070, "s": 1003, "text": "if node x is present in root’s left or right subtree, return true." }, { "code": null, "e": 1129, "s": 1070, "text": "Else remove root’s data value from arr[] and return false." }, { "code": null, "e": 1381, "s": 1129, "text": "This recursive function can be accessed from other function to check whether node x is present or not and if it is present, then the path nodes can be accessed from arr[]. You can define arr[] globally or pass its reference to the recursive function. " }, { "code": null, "e": 1385, "s": 1381, "text": "C++" }, { "code": null, "e": 1390, "s": 1385, "text": "Java" }, { "code": null, "e": 1398, "s": 1390, "text": "Python3" }, { "code": null, "e": 1401, "s": 1398, "text": "C#" }, { "code": null, "e": 1412, "s": 1401, "text": "Javascript" }, { "code": "// C++ implementation to print the path from root// to a given node in a binary tree#include <bits/stdc++.h>using namespace std; // structure of a node of binary treestruct Node{ int data; Node *left, *right;}; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct Node* getNode(int data){ struct Node *newNode = new Node; newNode->data = data; newNode->left = newNode->right = NULL; return newNode;} // Returns true if there is a path from root// to the given node. It also populates// 'arr' with the given pathbool hasPath(Node *root, vector<int>& arr, int x){ // if root is NULL // there is no path if (!root) return false; // push the node's value in 'arr' arr.push_back(root->data); // if it is the required node // return true if (root->data == x) return true; // else check whether the required node lies // in the left subtree or right subtree of // the current node if (hasPath(root->left, arr, x) || hasPath(root->right, arr, x)) return true; // required node does not lie either in the // left or right subtree of the current node // Thus, remove current node's value from // 'arr'and then return false arr.pop_back(); return false; } // function to print the path from root to the// given node if the node lies in the binary treevoid printPath(Node *root, int x){ // vector to store the path vector<int> arr; // if required node 'x' is present // then print the path if (hasPath(root, arr, x)) { for (int i=0; i<arr.size()-1; i++) cout << arr[i] << \"->\"; cout << arr[arr.size() - 1]; } // 'x' is not present in the binary tree else cout << \"No Path\";} // Driver program to test aboveint main(){ // binary tree formation struct Node *root = getNode(1); root->left = getNode(2); root->right = getNode(3); root->left->left = getNode(4); root->left->right = getNode(5); root->right->left = getNode(6); root->right->right = getNode(7); int x = 5; printPath(root, x); return 0;}", "e": 3609, "s": 1412, "text": null }, { "code": "// Java implementation to print the path from root// to a given node in a binary treeimport java.util.ArrayList;public class PrintPath { // Returns true if there is a path from root // to the given node. It also populates // 'arr' with the given path public static boolean hasPath(Node root, ArrayList<Integer> arr, int x) { // if root is NULL // there is no path if (root==null) return false; // push the node's value in 'arr' arr.add(root.data); // if it is the required node // return true if (root.data == x) return true; // else check whether the required node lies // in the left subtree or right subtree of // the current node if (hasPath(root.left, arr, x) || hasPath(root.right, arr, x)) return true; // required node does not lie either in the // left or right subtree of the current node // Thus, remove current node's value from // 'arr'and then return false arr.remove(arr.size()-1); return false; } // function to print the path from root to the // given node if the node lies in the binary tree public static void printPath(Node root, int x) { // ArrayList to store the path ArrayList<Integer> arr=new ArrayList<>(); // if required node 'x' is present // then print the path if (hasPath(root, arr, x)) { for (int i=0; i<arr.size()-1; i++) System.out.print(arr.get(i)+\"->\"); System.out.print(arr.get(arr.size() - 1)); } // 'x' is not present in the binary tree else System.out.print(\"No Path\"); } public static void main(String args[]) { Node root=new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(6); root.right.right = new Node(7); int x=5; printPath(root, x); }} // A node of binary treeclass Node{ int data; Node left, right; Node(int data) { this.data=data; left=right=null; }};//This code is contributed by Gaurav Tiwari", "e": 5943, "s": 3609, "text": null }, { "code": "# Python3 implementation to print the path from# root to a given node in a binary tree # Helper Class that allocates a new node# with the given data and None left and# right pointers.class getNode: def __init__(self, data): self.data = data self.left = self.right = None # Returns true if there is a path from# root to the given node. It also# populates 'arr' with the given pathdef hasPath(root, arr, x): # if root is None there is no path if (not root): return False # push the node's value in 'arr' arr.append(root.data) # if it is the required node # return true if (root.data == x): return True # else check whether the required node # lies in the left subtree or right # subtree of the current node if (hasPath(root.left, arr, x) or hasPath(root.right, arr, x)): return True # required node does not lie either in # the left or right subtree of the current # node. Thus, remove current node's value # from 'arr'and then return false arr.pop(-1) return False # function to print the path from root to# the given node if the node lies in# the binary treedef printPath(root, x): # vector to store the path arr = [] # if required node 'x' is present # then print the path if (hasPath(root, arr, x)): for i in range(len(arr) - 1): print(arr[i], end = \"->\") print(arr[len(arr) - 1]) # 'x' is not present in the # binary tree else: print(\"No Path\") # Driver Codeif __name__ == '__main__': # binary tree formation root = getNode(1) root.left = getNode(2) root.right = getNode(3) root.left.left = getNode(4) root.left.right = getNode(5) root.right.left = getNode(6) root.right.right = getNode(7) x = 5 printPath(root, x) # This code is contributed by PranchalK", "e": 7854, "s": 5943, "text": null }, { "code": "// C# implementation to print the path from root// to a given node in a binary treeusing System;using System.Collections;using System.Collections.Generic; class PrintPath{ // A node of binary treepublic class Node{ public int data; public Node left, right; public Node(int data) { this.data = data; left = right = null; }} // Returns true if there is a path from root // to the given node. It also populates // 'arr' with the given path public static Boolean hasPath(Node root, List<int> arr, int x) { // if root is NULL // there is no path if (root == null) return false; // push the node's value in 'arr' arr.Add(root.data); // if it is the required node // return true if (root.data == x) return true; // else check whether the required node lies // in the left subtree or right subtree of // the current node if (hasPath(root.left, arr, x) || hasPath(root.right, arr, x)) return true; // required node does not lie either in the // left or right subtree of the current node // Thus, remove current node's value from // 'arr'and then return false arr.RemoveAt(arr.Count - 1); return false; } // function to print the path from root to the // given node if the node lies in the binary tree public static void printPath(Node root, int x) { // List to store the path List<int> arr = new List<int>(); // if required node 'x' is present // then print the path if (hasPath(root, arr, x)) { for (int i = 0; i < arr.Count - 1; i++) Console.Write(arr[i]+\"->\"); Console.Write(arr[arr.Count - 1]); } // 'x' is not present in the binary tree else Console.Write(\"No Path\"); } // Driver code public static void Main(String []args) { Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(6); root.right.right = new Node(7); int x=5; printPath(root, x); }} // This code is contributed by Arnab Kundu", "e": 10295, "s": 7854, "text": null }, { "code": "<script> // Javascript implementation to print// the path from root to a given node// in a binary treeclass Node{ constructor(data) { this.left = null; this.right = null; this.data = data; }} // Returns true if there is a path from root// to the given node. It also populates // 'arr' with the given pathfunction hasPath(root, arr, x){ // If root is NULL // there is no path if (root == null) return false; // Push the node's value in 'arr' arr.push(root.data); // If it is the required node // return true if (root.data == x) return true; // Else check whether the required node lies // in the left subtree or right subtree of // the current node if (hasPath(root.left, arr, x) || hasPath(root.right, arr, x)) return true; // Required node does not lie either in the // left or right subtree of the current node // Thus, remove current node's value from // 'arr'and then return false arr.pop(); return false; } // Function to print the path from root to the// given node if the node lies in the binary treefunction printPath(root, x){ // ArrayList to store the path let arr = []; // If required node 'x' is present // then print the path if (hasPath(root, arr, x)) { for(let i = 0; i < arr.length - 1; i++) document.write(arr[i] + \"->\"); document.write(arr[arr.length - 1]); } // 'x' is not present in the binary tree else document.write(\"No Path\");} // Driver codelet root = new Node(1);root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.left.right = new Node(5);root.right.left = new Node(6);root.right.right = new Node(7); let x = 5;printPath(root, x); // This code is contributed by divyeshrabadiya07 </script>", "e": 12186, "s": 10295, "text": null }, { "code": null, "e": 12195, "s": 12186, "text": "Output: " }, { "code": null, "e": 12203, "s": 12195, "text": "1->2->5" }, { "code": null, "e": 12291, "s": 12203, "text": "Time complexity: O(n) in worst case, where n is the number of nodes in the binary tree." }, { "code": null, "e": 12713, "s": 12291, "text": "This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 12728, "s": 12713, "text": "_Gaurav_Tiwari" }, { "code": null, "e": 12744, "s": 12728, "text": "PranchalKatiyar" }, { "code": null, "e": 12755, "s": 12744, "text": "andrew1234" }, { "code": null, "e": 12766, "s": 12755, "text": "nidhi_biet" }, { "code": null, "e": 12784, "s": 12766, "text": "divyeshrabadiya07" }, { "code": null, "e": 12798, "s": 12784, "text": "snehilgupta92" }, { "code": null, "e": 12803, "s": 12798, "text": "Tree" }, { "code": null, "e": 12808, "s": 12803, "text": "Tree" }, { "code": null, "e": 12906, "s": 12808, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 12935, "s": 12906, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 12967, "s": 12935, "text": "Introduction to Data Structures" }, { "code": null, "e": 13031, "s": 12967, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 13081, "s": 13031, "text": "A program to check if a binary tree is BST or not" }, { "code": null, "e": 13095, "s": 13081, "text": "Decision Tree" }, { "code": null, "e": 13138, "s": 13095, "text": "Top 50 Tree Coding Problems for Interviews" }, { "code": null, "e": 13180, "s": 13138, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 13250, "s": 13180, "text": "Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)" }, { "code": null, "e": 13333, "s": 13250, "text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree" } ]
VB.Net - TreeView Control
The TreeView control is used to display hierarchical representations of items similar to the ways the files and folders are displayed in the left pane of the Windows Explorer. Each node may contain one or more child nodes. Let's click on a TreeView control from the Toolbox and place it on the form. The following are some of the commonly used properties of the TreeView control − BackColor Gets or sets the background color for the control. BackgroundImage Gets or set the background image for the TreeView control. BackgroundImageLayout Gets or sets the layout of the background image for the TreeView control. BorderStyle Gets or sets the border style of the tree view control. CheckBoxes Gets or sets a value indicating whether check boxes are displayed next to the tree nodes in the tree view control. DataBindings Gets the data bindings for the control. Font Gets or sets the font of the text displayed by the control. FontHeight Gets or sets the height of the font of the control. ForeColor The current foreground color for this control, which is the color the control uses to draw its text. ItemHeight Gets or sets the height of each tree node in the tree view control. Nodes Gets the collection of tree nodes that are assigned to the tree view control. PathSeparator Gets or sets the delimiter string that the tree node path uses. RightToLeftLayout Gets or sets a value that indicates whether the TreeView should be laid out from right-to-left. Scrollable Gets or sets a value indicating whether the tree view control displays scroll bars when they are needed. SelectedImageIndex Gets or sets the image list index value of the image that is displayed when a tree node is selected. SelectedImageKey Gets or sets the key of the default image shown when a TreeNode is in a selected state. SelectedNode Gets or sets the tree node that is currently selected in the tree view control. ShowLines Gets or sets a value indicating whether lines are drawn between tree nodes in the tree view control. ShowNodeToolTips Gets or sets a value indicating ToolTips are shown when the mouse pointer hovers over a TreeNode. ShowPlusMinus Gets or sets a value indicating whether plus-sign (+) and minus-sign (-) buttons are displayed next to tree nodes that contain child tree nodes. ShowRootLines Gets or sets a value indicating whether lines are drawn between the tree nodes that are at the root of the tree view. Sorted Gets or sets a value indicating whether the tree nodes in the tree view are sorted. StateImageList Gets or sets the image list that is used to indicate the state of the TreeView and its nodes. Text Gets or sets the text of the TreeView. TopNode Gets or sets the first fully-visible tree node in the tree view control. TreeViewNodeSorter Gets or sets the implementation of IComparer to perform a custom sort of the TreeView nodes. VisibleCount Gets the number of tree nodes that can be fully visible in the tree view control. The following are some of the commonly used methods of the TreeView control − CollapseAll Collapses all the nodes including all child nodes in the tree view control. ExpandAll Expands all the nodes. GetNodeAt Gets the node at the specified location. GetNodeCount Gets the number of tree nodes. Sort Sorts all the items in the tree view control. ToString Returns a string containing the name of the control. The following are some of the commonly used events of the TreeView control − AfterCheck Occurs after the tree node check box is checked. AfterCollapse Occurs after the tree node is collapsed. AfterExpand Occurs after the tree node is expanded. AfterSelect Occurs after the tree node is selected. BeforeCheck Occurs before the tree node check box is checked. BeforeCollapse Occurs before the tree node is collapsed. BeforeExpand Occurs before the tree node is expanded. BeforeLabelEdit Occurs before the tree node label text is edited. BeforeSelect Occurs before the tree node is selected. ItemDrag Occurs when the user begins dragging a node. NodeMouseClick Occurs when the user clicks a TreeNode with the mouse. NodeMouseDoubleClick Occurs when the user double-clicks a TreeNode with the mouse. NodeMouseHover Occurs when the mouse hovers over a TreeNode. PaddingChanged Occurs when the value of the Padding property changes. Paint Occurs when the TreeView is drawn. RightToLeftLayoutChanged Occurs when the value of the RightToLeftLayout property changes. TextChanged Occurs when the Text property changes. The TreeNode class represents a node of a TreeView. Each node in a TreeView control is an object of the TreeNode class. To be able to use a TreeView control we need to have a look at some commonly used properties and methods of the TreeNode class. The following are some of the commonly used properties of the TreeNode class − BackColor Gets or sets the background color of the tree node. Checked Gets or sets a value indicating whether the tree node is in a checked state. ContextMenu Gets the shortcut menu that is associated with this tree node. ContextMenuStrip Gets or sets the shortcut menu associated with this tree node. FirstNode Gets the first child tree node in the tree node collection. FullPath Gets the path from the root tree node to the current tree node. Index Gets the position of the tree node in the tree node collection. IsEditing Gets a value indicating whether the tree node is in an editable state. IsExpanded Gets a value indicating whether the tree node is in the expanded state. IsSelected Gets a value indicating whether the tree node is in the selected state. IsVisible Gets a value indicating whether the tree node is visible or partially visible. LastNode Gets the last child tree node. Level Gets the zero-based depth of the tree node in the TreeView control. Name Gets or sets the name of the tree node. NextNode Gets the next sibling tree node. Nodes Gets the collection of TreeNode objects assigned to the current tree node. Parent Gets the parent tree node of the current tree node. PrevNode Gets the previous sibling tree node. PrevVisibleNode Gets the previous visible tree node. Tag Gets or sets the object that contains data about the tree node. Text Gets or sets the text displayed in the label of the tree node. ToolTipText Gets or sets the text that appears when the mouse pointer hovers over a TreeNode. TreeView Gets the parent tree view that the tree node is assigned to. The following are some of the commonly used methods of the TreeNode class − Collapse Collapses the tree node. Expand Expands the tree node. ExpandAll Expands all the child tree nodes. GetNodeCount Returns the number of child tree nodes. Remove Removes the current tree node from the tree view control. Toggle Toggles the tree node to either the expanded or collapsed state. ToString Returns a string that represents the current object. In this example, let us create a tree view at runtime. Let's double click on the Form and put the follow code in the opened window. Public Class Form1 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load 'create a new TreeView Dim TreeView1 As TreeView TreeView1 = New TreeView() TreeView1.Location = New Point(10, 10) TreeView1.Size = New Size(150, 150) Me.Controls.Add(TreeView1) TreeView1.Nodes.Clear() 'Creating the root node Dim root = New TreeNode("Application") TreeView1.Nodes.Add(root) TreeView1.Nodes(0).Nodes.Add(New TreeNode("Project 1")) 'Creating child nodes under the first child For loopindex As Integer = 1 To 4 TreeView1.Nodes(0).Nodes(0).Nodes.Add(New _ TreeNode("Sub Project" & Str(loopindex))) Next loopindex ' creating child nodes under the root TreeView1.Nodes(0).Nodes.Add(New TreeNode("Project 6")) 'creating child nodes under the created child node For loopindex As Integer = 1 To 3 TreeView1.Nodes(0).Nodes(1).Nodes.Add(New _ TreeNode("Project File" & Str(loopindex))) Next loopindex ' Set the caption bar text of the form. Me.Text = "tutorialspoint.com" End Sub End Class When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show the following window − You can expand the nodes to see the child nodes −
[ { "code": null, "e": 2657, "s": 2434, "text": "The TreeView control is used to display hierarchical representations of items similar to the ways the files and folders are displayed in the left pane of the Windows Explorer. Each node may contain one or more child nodes." }, { "code": null, "e": 2734, "s": 2657, "text": "Let's click on a TreeView control from the Toolbox and place it on the form." }, { "code": null, "e": 2815, "s": 2734, "text": "The following are some of the commonly used properties of the TreeView control −" }, { "code": null, "e": 2825, "s": 2815, "text": "BackColor" }, { "code": null, "e": 2876, "s": 2825, "text": "Gets or sets the background color for the control." }, { "code": null, "e": 2892, "s": 2876, "text": "BackgroundImage" }, { "code": null, "e": 2951, "s": 2892, "text": "Gets or set the background image for the TreeView control." }, { "code": null, "e": 2973, "s": 2951, "text": "BackgroundImageLayout" }, { "code": null, "e": 3047, "s": 2973, "text": "Gets or sets the layout of the background image for the TreeView control." }, { "code": null, "e": 3059, "s": 3047, "text": "BorderStyle" }, { "code": null, "e": 3115, "s": 3059, "text": "Gets or sets the border style of the tree view control." }, { "code": null, "e": 3126, "s": 3115, "text": "CheckBoxes" }, { "code": null, "e": 3241, "s": 3126, "text": "Gets or sets a value indicating whether check boxes are displayed next to the tree nodes in the tree view control." }, { "code": null, "e": 3254, "s": 3241, "text": "DataBindings" }, { "code": null, "e": 3294, "s": 3254, "text": "Gets the data bindings for the control." }, { "code": null, "e": 3299, "s": 3294, "text": "Font" }, { "code": null, "e": 3359, "s": 3299, "text": "Gets or sets the font of the text displayed by the control." }, { "code": null, "e": 3370, "s": 3359, "text": "FontHeight" }, { "code": null, "e": 3422, "s": 3370, "text": "Gets or sets the height of the font of the control." }, { "code": null, "e": 3432, "s": 3422, "text": "ForeColor" }, { "code": null, "e": 3533, "s": 3432, "text": "The current foreground color for this control, which is the color the control uses to draw its text." }, { "code": null, "e": 3544, "s": 3533, "text": "ItemHeight" }, { "code": null, "e": 3612, "s": 3544, "text": "Gets or sets the height of each tree node in the tree view control." }, { "code": null, "e": 3618, "s": 3612, "text": "Nodes" }, { "code": null, "e": 3696, "s": 3618, "text": "Gets the collection of tree nodes that are assigned to the tree view control." }, { "code": null, "e": 3710, "s": 3696, "text": "PathSeparator" }, { "code": null, "e": 3774, "s": 3710, "text": "Gets or sets the delimiter string that the tree node path uses." }, { "code": null, "e": 3792, "s": 3774, "text": "RightToLeftLayout" }, { "code": null, "e": 3888, "s": 3792, "text": "Gets or sets a value that indicates whether the TreeView should be laid out from right-to-left." }, { "code": null, "e": 3899, "s": 3888, "text": "Scrollable" }, { "code": null, "e": 4004, "s": 3899, "text": "Gets or sets a value indicating whether the tree view control displays scroll bars when they are needed." }, { "code": null, "e": 4023, "s": 4004, "text": "SelectedImageIndex" }, { "code": null, "e": 4124, "s": 4023, "text": "Gets or sets the image list index value of the image that is displayed when a tree node is selected." }, { "code": null, "e": 4141, "s": 4124, "text": "SelectedImageKey" }, { "code": null, "e": 4229, "s": 4141, "text": "Gets or sets the key of the default image shown when a TreeNode is in a selected state." }, { "code": null, "e": 4242, "s": 4229, "text": "SelectedNode" }, { "code": null, "e": 4322, "s": 4242, "text": "Gets or sets the tree node that is currently selected in the tree view control." }, { "code": null, "e": 4332, "s": 4322, "text": "ShowLines" }, { "code": null, "e": 4433, "s": 4332, "text": "Gets or sets a value indicating whether lines are drawn between tree nodes in the tree view control." }, { "code": null, "e": 4450, "s": 4433, "text": "ShowNodeToolTips" }, { "code": null, "e": 4548, "s": 4450, "text": "Gets or sets a value indicating ToolTips are shown when the mouse pointer hovers over a TreeNode." }, { "code": null, "e": 4562, "s": 4548, "text": "ShowPlusMinus" }, { "code": null, "e": 4707, "s": 4562, "text": "Gets or sets a value indicating whether plus-sign (+) and minus-sign (-) buttons are displayed next to tree nodes that contain child tree nodes." }, { "code": null, "e": 4721, "s": 4707, "text": "ShowRootLines" }, { "code": null, "e": 4839, "s": 4721, "text": "Gets or sets a value indicating whether lines are drawn between the tree nodes that are at the root of the tree view." }, { "code": null, "e": 4846, "s": 4839, "text": "Sorted" }, { "code": null, "e": 4930, "s": 4846, "text": "Gets or sets a value indicating whether the tree nodes in the tree view are sorted." }, { "code": null, "e": 4945, "s": 4930, "text": "StateImageList" }, { "code": null, "e": 5040, "s": 4945, "text": "Gets or sets the image list that is used to indicate the state of the TreeView and its nodes. " }, { "code": null, "e": 5045, "s": 5040, "text": "Text" }, { "code": null, "e": 5084, "s": 5045, "text": "Gets or sets the text of the TreeView." }, { "code": null, "e": 5092, "s": 5084, "text": "TopNode" }, { "code": null, "e": 5165, "s": 5092, "text": "Gets or sets the first fully-visible tree node in the tree view control." }, { "code": null, "e": 5184, "s": 5165, "text": "TreeViewNodeSorter" }, { "code": null, "e": 5277, "s": 5184, "text": "Gets or sets the implementation of IComparer to perform a custom sort of the TreeView nodes." }, { "code": null, "e": 5290, "s": 5277, "text": "VisibleCount" }, { "code": null, "e": 5372, "s": 5290, "text": "Gets the number of tree nodes that can be fully visible in the tree view control." }, { "code": null, "e": 5450, "s": 5372, "text": "The following are some of the commonly used methods of the TreeView control −" }, { "code": null, "e": 5462, "s": 5450, "text": "CollapseAll" }, { "code": null, "e": 5538, "s": 5462, "text": "Collapses all the nodes including all child nodes in the tree view control." }, { "code": null, "e": 5548, "s": 5538, "text": "ExpandAll" }, { "code": null, "e": 5571, "s": 5548, "text": "Expands all the nodes." }, { "code": null, "e": 5581, "s": 5571, "text": "GetNodeAt" }, { "code": null, "e": 5622, "s": 5581, "text": "Gets the node at the specified location." }, { "code": null, "e": 5635, "s": 5622, "text": "GetNodeCount" }, { "code": null, "e": 5666, "s": 5635, "text": "Gets the number of tree nodes." }, { "code": null, "e": 5671, "s": 5666, "text": "Sort" }, { "code": null, "e": 5717, "s": 5671, "text": "Sorts all the items in the tree view control." }, { "code": null, "e": 5726, "s": 5717, "text": "ToString" }, { "code": null, "e": 5779, "s": 5726, "text": "Returns a string containing the name of the control." }, { "code": null, "e": 5856, "s": 5779, "text": "The following are some of the commonly used events of the TreeView control −" }, { "code": null, "e": 5867, "s": 5856, "text": "AfterCheck" }, { "code": null, "e": 5916, "s": 5867, "text": "Occurs after the tree node check box is checked." }, { "code": null, "e": 5930, "s": 5916, "text": "AfterCollapse" }, { "code": null, "e": 5971, "s": 5930, "text": "Occurs after the tree node is collapsed." }, { "code": null, "e": 5983, "s": 5971, "text": "AfterExpand" }, { "code": null, "e": 6023, "s": 5983, "text": "Occurs after the tree node is expanded." }, { "code": null, "e": 6035, "s": 6023, "text": "AfterSelect" }, { "code": null, "e": 6075, "s": 6035, "text": "Occurs after the tree node is selected." }, { "code": null, "e": 6087, "s": 6075, "text": "BeforeCheck" }, { "code": null, "e": 6137, "s": 6087, "text": "Occurs before the tree node check box is checked." }, { "code": null, "e": 6152, "s": 6137, "text": "BeforeCollapse" }, { "code": null, "e": 6194, "s": 6152, "text": "Occurs before the tree node is collapsed." }, { "code": null, "e": 6207, "s": 6194, "text": "BeforeExpand" }, { "code": null, "e": 6248, "s": 6207, "text": "Occurs before the tree node is expanded." }, { "code": null, "e": 6264, "s": 6248, "text": "BeforeLabelEdit" }, { "code": null, "e": 6314, "s": 6264, "text": "Occurs before the tree node label text is edited." }, { "code": null, "e": 6327, "s": 6314, "text": "BeforeSelect" }, { "code": null, "e": 6368, "s": 6327, "text": "Occurs before the tree node is selected." }, { "code": null, "e": 6377, "s": 6368, "text": "ItemDrag" }, { "code": null, "e": 6422, "s": 6377, "text": "Occurs when the user begins dragging a node." }, { "code": null, "e": 6437, "s": 6422, "text": "NodeMouseClick" }, { "code": null, "e": 6492, "s": 6437, "text": "Occurs when the user clicks a TreeNode with the mouse." }, { "code": null, "e": 6513, "s": 6492, "text": "NodeMouseDoubleClick" }, { "code": null, "e": 6575, "s": 6513, "text": "Occurs when the user double-clicks a TreeNode with the mouse." }, { "code": null, "e": 6590, "s": 6575, "text": "NodeMouseHover" }, { "code": null, "e": 6636, "s": 6590, "text": "Occurs when the mouse hovers over a TreeNode." }, { "code": null, "e": 6651, "s": 6636, "text": "PaddingChanged" }, { "code": null, "e": 6706, "s": 6651, "text": "Occurs when the value of the Padding property changes." }, { "code": null, "e": 6712, "s": 6706, "text": "Paint" }, { "code": null, "e": 6747, "s": 6712, "text": "Occurs when the TreeView is drawn." }, { "code": null, "e": 6772, "s": 6747, "text": "RightToLeftLayoutChanged" }, { "code": null, "e": 6837, "s": 6772, "text": "Occurs when the value of the RightToLeftLayout property changes." }, { "code": null, "e": 6849, "s": 6837, "text": "TextChanged" }, { "code": null, "e": 6888, "s": 6849, "text": "Occurs when the Text property changes." }, { "code": null, "e": 7136, "s": 6888, "text": "The TreeNode class represents a node of a TreeView. Each node in a TreeView control is an object of the TreeNode class. To be able to use a TreeView control we need to have a look at some commonly used properties and methods of the TreeNode class." }, { "code": null, "e": 7215, "s": 7136, "text": "The following are some of the commonly used properties of the TreeNode class −" }, { "code": null, "e": 7225, "s": 7215, "text": "BackColor" }, { "code": null, "e": 7277, "s": 7225, "text": "Gets or sets the background color of the tree node." }, { "code": null, "e": 7285, "s": 7277, "text": "Checked" }, { "code": null, "e": 7362, "s": 7285, "text": "Gets or sets a value indicating whether the tree node is in a checked state." }, { "code": null, "e": 7374, "s": 7362, "text": "ContextMenu" }, { "code": null, "e": 7437, "s": 7374, "text": "Gets the shortcut menu that is associated with this tree node." }, { "code": null, "e": 7454, "s": 7437, "text": "ContextMenuStrip" }, { "code": null, "e": 7517, "s": 7454, "text": "Gets or sets the shortcut menu associated with this tree node." }, { "code": null, "e": 7527, "s": 7517, "text": "FirstNode" }, { "code": null, "e": 7587, "s": 7527, "text": "Gets the first child tree node in the tree node collection." }, { "code": null, "e": 7596, "s": 7587, "text": "FullPath" }, { "code": null, "e": 7660, "s": 7596, "text": "Gets the path from the root tree node to the current tree node." }, { "code": null, "e": 7666, "s": 7660, "text": "Index" }, { "code": null, "e": 7730, "s": 7666, "text": "Gets the position of the tree node in the tree node collection." }, { "code": null, "e": 7740, "s": 7730, "text": "IsEditing" }, { "code": null, "e": 7811, "s": 7740, "text": "Gets a value indicating whether the tree node is in an editable state." }, { "code": null, "e": 7822, "s": 7811, "text": "IsExpanded" }, { "code": null, "e": 7894, "s": 7822, "text": "Gets a value indicating whether the tree node is in the expanded state." }, { "code": null, "e": 7905, "s": 7894, "text": "IsSelected" }, { "code": null, "e": 7977, "s": 7905, "text": "Gets a value indicating whether the tree node is in the selected state." }, { "code": null, "e": 7987, "s": 7977, "text": "IsVisible" }, { "code": null, "e": 8066, "s": 7987, "text": "Gets a value indicating whether the tree node is visible or partially visible." }, { "code": null, "e": 8075, "s": 8066, "text": "LastNode" }, { "code": null, "e": 8106, "s": 8075, "text": "Gets the last child tree node." }, { "code": null, "e": 8112, "s": 8106, "text": "Level" }, { "code": null, "e": 8180, "s": 8112, "text": "Gets the zero-based depth of the tree node in the TreeView control." }, { "code": null, "e": 8185, "s": 8180, "text": "Name" }, { "code": null, "e": 8225, "s": 8185, "text": "Gets or sets the name of the tree node." }, { "code": null, "e": 8234, "s": 8225, "text": "NextNode" }, { "code": null, "e": 8267, "s": 8234, "text": "Gets the next sibling tree node." }, { "code": null, "e": 8273, "s": 8267, "text": "Nodes" }, { "code": null, "e": 8348, "s": 8273, "text": "Gets the collection of TreeNode objects assigned to the current tree node." }, { "code": null, "e": 8355, "s": 8348, "text": "Parent" }, { "code": null, "e": 8407, "s": 8355, "text": "Gets the parent tree node of the current tree node." }, { "code": null, "e": 8416, "s": 8407, "text": "PrevNode" }, { "code": null, "e": 8453, "s": 8416, "text": "Gets the previous sibling tree node." }, { "code": null, "e": 8469, "s": 8453, "text": "PrevVisibleNode" }, { "code": null, "e": 8506, "s": 8469, "text": "Gets the previous visible tree node." }, { "code": null, "e": 8510, "s": 8506, "text": "Tag" }, { "code": null, "e": 8574, "s": 8510, "text": "Gets or sets the object that contains data about the tree node." }, { "code": null, "e": 8579, "s": 8574, "text": "Text" }, { "code": null, "e": 8642, "s": 8579, "text": "Gets or sets the text displayed in the label of the tree node." }, { "code": null, "e": 8654, "s": 8642, "text": "ToolTipText" }, { "code": null, "e": 8736, "s": 8654, "text": "Gets or sets the text that appears when the mouse pointer hovers over a TreeNode." }, { "code": null, "e": 8745, "s": 8736, "text": "TreeView" }, { "code": null, "e": 8806, "s": 8745, "text": "Gets the parent tree view that the tree node is assigned to." }, { "code": null, "e": 8882, "s": 8806, "text": "The following are some of the commonly used methods of the TreeNode class −" }, { "code": null, "e": 8891, "s": 8882, "text": "Collapse" }, { "code": null, "e": 8916, "s": 8891, "text": "Collapses the tree node." }, { "code": null, "e": 8923, "s": 8916, "text": "Expand" }, { "code": null, "e": 8946, "s": 8923, "text": "Expands the tree node." }, { "code": null, "e": 8956, "s": 8946, "text": "ExpandAll" }, { "code": null, "e": 8990, "s": 8956, "text": "Expands all the child tree nodes." }, { "code": null, "e": 9003, "s": 8990, "text": "GetNodeCount" }, { "code": null, "e": 9043, "s": 9003, "text": "Returns the number of child tree nodes." }, { "code": null, "e": 9050, "s": 9043, "text": "Remove" }, { "code": null, "e": 9108, "s": 9050, "text": "Removes the current tree node from the tree view control." }, { "code": null, "e": 9115, "s": 9108, "text": "Toggle" }, { "code": null, "e": 9180, "s": 9115, "text": "Toggles the tree node to either the expanded or collapsed state." }, { "code": null, "e": 9189, "s": 9180, "text": "ToString" }, { "code": null, "e": 9242, "s": 9189, "text": "Returns a string that represents the current object." }, { "code": null, "e": 9374, "s": 9242, "text": "In this example, let us create a tree view at runtime. Let's double click on the Form and put the follow code in the opened window." }, { "code": null, "e": 10565, "s": 9374, "text": "Public Class Form1\n Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load\n 'create a new TreeView\n Dim TreeView1 As TreeView\n TreeView1 = New TreeView()\n TreeView1.Location = New Point(10, 10)\n TreeView1.Size = New Size(150, 150)\n \n Me.Controls.Add(TreeView1)\n TreeView1.Nodes.Clear()\n 'Creating the root node\n Dim root = New TreeNode(\"Application\")\n TreeView1.Nodes.Add(root)\n TreeView1.Nodes(0).Nodes.Add(New TreeNode(\"Project 1\"))\n 'Creating child nodes under the first child\n \n For loopindex As Integer = 1 To 4\n TreeView1.Nodes(0).Nodes(0).Nodes.Add(New _\n TreeNode(\"Sub Project\" & Str(loopindex)))\n Next loopindex\n ' creating child nodes under the root\n TreeView1.Nodes(0).Nodes.Add(New TreeNode(\"Project 6\"))\n 'creating child nodes under the created child node\n \n For loopindex As Integer = 1 To 3\n TreeView1.Nodes(0).Nodes(1).Nodes.Add(New _\n TreeNode(\"Project File\" & Str(loopindex)))\n Next loopindex\n ' Set the caption bar text of the form. \n Me.Text = \"tutorialspoint.com\"\n End Sub\nEnd Class" }, { "code": null, "e": 10711, "s": 10565, "text": "When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show the following window −" } ]
Reader-Writers solution using Monitors
16 Aug, 2019 Prerequisite – Process Synchronization, Monitors, Readers-Writers ProblemConsidering a shared Database our objectives are: Readers can access database only when there are no writers. Writers can access database only when there are no readers or writers. Only one thread can manipulate the state variables at a time. Basic structure of a solution – Reader() Wait until no writers Access database Check out – wake up a waiting writer Writer() Wait until no active readers or writers Access database Check out – wake up waiting readers or writer –Now let’s suppose that a writer is active and a mixture of readers and writers now show up.Who should get in next?–Or suppose that a writer is waiting and an endless of stream of readers keep showing up.Would it be fair for them to become active?So we’ll implement a kind of back-and-forth form of fairness: Once a reader is waiting, readers will get in next. If a writer is waiting, one writer will get in next. Implementation of the solution using monitors:- The methods should be executed with mutual exclusion i.e. At each point in time, at most one thread may be executing any of its methods.Monitors also provide a mechanism for threads to temporarily give up exclusive access, in order to wait for some condition to be met, before regaining exclusive access and resuming their task.Monitors also have a mechanism for signaling other threads that such conditions have been met.So in this implementation only mutual exclusion is not enough. Threads attempting an operation may need to wait until some assertion P holds true.While a thread is waiting upon a condition variable, that thread is not considered to occupy the monitor, and so other threads may enter the monitor to change the monitor’s state. The methods should be executed with mutual exclusion i.e. At each point in time, at most one thread may be executing any of its methods. Monitors also provide a mechanism for threads to temporarily give up exclusive access, in order to wait for some condition to be met, before regaining exclusive access and resuming their task. Monitors also have a mechanism for signaling other threads that such conditions have been met. So in this implementation only mutual exclusion is not enough. Threads attempting an operation may need to wait until some assertion P holds true. While a thread is waiting upon a condition variable, that thread is not considered to occupy the monitor, and so other threads may enter the monitor to change the monitor’s state. Code – // STATE VARIABLES// Number of active readers; initially = 0int NReaders = 0; // Number of waiting readers; initially = 0int WaitingReaders = 0; // Number of active writers; initially = 0int NWriters = 0; // Number of waiting writers; initially = 0int WaitingWriters = 0; Condition canRead = NULL;Condition canWrite = NULL; Void BeginWrite(){ // A writer can enter if there are no other // active writers and no readers are waiting if (NWriters == 1 || NReaders > 0) { ++WaitingWriters; wait(CanWrite); --WaitingWriters; } NWriters = 1;} Void EndWrite(){ NWriters = 0; // Checks to see if any readers are waiting if (WaitingReaders) Signal(CanRead); else Signal(CanWrite);} Void BeginRead(){ // A reader can enter if there are no writers // active or waiting, so we can have // many readers active all at once if (NWriters == 1 || WaitingWriters > 0) { ++WaitingReaders; // Otherwise, a reader waits (maybe many do) Wait(CanRead); --WaitingReaders; } ++NReaders; Signal(CanRead);} Void EndRead(){ // When a reader finishes, if it was the last reader, // it lets a writer in (if any is there). if (--NReaders == 0) Signal(CanWrite);} Understanding the solution:- It wants to be fair. If a writer is waiting, readers queue up.If a reader (or another writer) is active or waiting, writers queue up.This is mostly fair, although once it lets a reader in, it lets ALL waiting readers in all at once, even if some showed up “after” other waiting writers. If a writer is waiting, readers queue up. If a reader (or another writer) is active or waiting, writers queue up. This is mostly fair, although once it lets a reader in, it lets ALL waiting readers in all at once, even if some showed up “after” other waiting writers. The code is “simplified” because we know there can only be one writer at a time. It also takes advantage of the fact that signal is a no-op if nobody is waiting. In the “EndWrite” code (it signals CanWrite without checking for waiting writers)In the EndRead code (same thing)In StartRead (signals CanRead at the end) In the “EndWrite” code (it signals CanWrite without checking for waiting writers) In the EndRead code (same thing) In StartRead (signals CanRead at the end) With Semaphores we never did have a “fair” solution of this sort. In fact it can be done but the code is quite tricky. Here the straightforward solution works in the desired way! Monitors are less error-prone and also easier to understand. GATE CS Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Normal Forms in DBMS Page Replacement Algorithms in Operating Systems Inter Process Communication (IPC) Differences between TCP and UDP Introduction of Operating System - Set 1 Banker's Algorithm in Operating System Page Replacement Algorithms in Operating Systems Disk Scheduling Algorithms File Allocation Methods Paging in Operating System
[ { "code": null, "e": 54, "s": 26, "text": "\n16 Aug, 2019" }, { "code": null, "e": 177, "s": 54, "text": "Prerequisite – Process Synchronization, Monitors, Readers-Writers ProblemConsidering a shared Database our objectives are:" }, { "code": null, "e": 237, "s": 177, "text": "Readers can access database only when there are no writers." }, { "code": null, "e": 308, "s": 237, "text": "Writers can access database only when there are no readers or writers." }, { "code": null, "e": 370, "s": 308, "text": "Only one thread can manipulate the state variables at a time." }, { "code": null, "e": 402, "s": 370, "text": "Basic structure of a solution –" }, { "code": null, "e": 616, "s": 402, "text": "Reader()\n Wait until no writers\n Access database\n Check out – wake up a waiting writer\nWriter()\n Wait until no active readers or writers\n Access database\n Check out – wake up waiting readers or writer\n" }, { "code": null, "e": 925, "s": 616, "text": "–Now let’s suppose that a writer is active and a mixture of readers and writers now show up.Who should get in next?–Or suppose that a writer is waiting and an endless of stream of readers keep showing up.Would it be fair for them to become active?So we’ll implement a kind of back-and-forth form of fairness:" }, { "code": null, "e": 977, "s": 925, "text": "Once a reader is waiting, readers will get in next." }, { "code": null, "e": 1030, "s": 977, "text": "If a writer is waiting, one writer will get in next." }, { "code": null, "e": 1078, "s": 1030, "text": "Implementation of the solution using monitors:-" }, { "code": null, "e": 1826, "s": 1078, "text": "The methods should be executed with mutual exclusion i.e. At each point in time, at most one thread may be executing any of its methods.Monitors also provide a mechanism for threads to temporarily give up exclusive access, in order to wait for some condition to be met, before regaining exclusive access and resuming their task.Monitors also have a mechanism for signaling other threads that such conditions have been met.So in this implementation only mutual exclusion is not enough. Threads attempting an operation may need to wait until some assertion P holds true.While a thread is waiting upon a condition variable, that thread is not considered to occupy the monitor, and so other threads may enter the monitor to change the monitor’s state." }, { "code": null, "e": 1963, "s": 1826, "text": "The methods should be executed with mutual exclusion i.e. At each point in time, at most one thread may be executing any of its methods." }, { "code": null, "e": 2156, "s": 1963, "text": "Monitors also provide a mechanism for threads to temporarily give up exclusive access, in order to wait for some condition to be met, before regaining exclusive access and resuming their task." }, { "code": null, "e": 2251, "s": 2156, "text": "Monitors also have a mechanism for signaling other threads that such conditions have been met." }, { "code": null, "e": 2398, "s": 2251, "text": "So in this implementation only mutual exclusion is not enough. Threads attempting an operation may need to wait until some assertion P holds true." }, { "code": null, "e": 2578, "s": 2398, "text": "While a thread is waiting upon a condition variable, that thread is not considered to occupy the monitor, and so other threads may enter the monitor to change the monitor’s state." }, { "code": null, "e": 2585, "s": 2578, "text": "Code –" }, { "code": "// STATE VARIABLES// Number of active readers; initially = 0int NReaders = 0; // Number of waiting readers; initially = 0int WaitingReaders = 0; // Number of active writers; initially = 0int NWriters = 0; // Number of waiting writers; initially = 0int WaitingWriters = 0; Condition canRead = NULL;Condition canWrite = NULL; Void BeginWrite(){ // A writer can enter if there are no other // active writers and no readers are waiting if (NWriters == 1 || NReaders > 0) { ++WaitingWriters; wait(CanWrite); --WaitingWriters; } NWriters = 1;} Void EndWrite(){ NWriters = 0; // Checks to see if any readers are waiting if (WaitingReaders) Signal(CanRead); else Signal(CanWrite);} Void BeginRead(){ // A reader can enter if there are no writers // active or waiting, so we can have // many readers active all at once if (NWriters == 1 || WaitingWriters > 0) { ++WaitingReaders; // Otherwise, a reader waits (maybe many do) Wait(CanRead); --WaitingReaders; } ++NReaders; Signal(CanRead);} Void EndRead(){ // When a reader finishes, if it was the last reader, // it lets a writer in (if any is there). if (--NReaders == 0) Signal(CanWrite);}", "e": 3883, "s": 2585, "text": null }, { "code": null, "e": 3912, "s": 3883, "text": "Understanding the solution:-" }, { "code": null, "e": 3933, "s": 3912, "text": "It wants to be fair." }, { "code": null, "e": 4199, "s": 3933, "text": "If a writer is waiting, readers queue up.If a reader (or another writer) is active or waiting, writers queue up.This is mostly fair, although once it lets a reader in, it lets ALL waiting readers in all at once, even if some showed up “after” other waiting writers." }, { "code": null, "e": 4241, "s": 4199, "text": "If a writer is waiting, readers queue up." }, { "code": null, "e": 4313, "s": 4241, "text": "If a reader (or another writer) is active or waiting, writers queue up." }, { "code": null, "e": 4467, "s": 4313, "text": "This is mostly fair, although once it lets a reader in, it lets ALL waiting readers in all at once, even if some showed up “after” other waiting writers." }, { "code": null, "e": 4548, "s": 4467, "text": "The code is “simplified” because we know there can only be one writer at a time." }, { "code": null, "e": 4629, "s": 4548, "text": "It also takes advantage of the fact that signal is a no-op if nobody is waiting." }, { "code": null, "e": 4784, "s": 4629, "text": "In the “EndWrite” code (it signals CanWrite without checking for waiting writers)In the EndRead code (same thing)In StartRead (signals CanRead at the end)" }, { "code": null, "e": 4866, "s": 4784, "text": "In the “EndWrite” code (it signals CanWrite without checking for waiting writers)" }, { "code": null, "e": 4899, "s": 4866, "text": "In the EndRead code (same thing)" }, { "code": null, "e": 4941, "s": 4899, "text": "In StartRead (signals CanRead at the end)" }, { "code": null, "e": 5181, "s": 4941, "text": "With Semaphores we never did have a “fair” solution of this sort. In fact it can be done but the code is quite tricky. Here the straightforward solution works in the desired way! Monitors are less error-prone and also easier to understand." }, { "code": null, "e": 5189, "s": 5181, "text": "GATE CS" }, { "code": null, "e": 5207, "s": 5189, "text": "Operating Systems" }, { "code": null, "e": 5225, "s": 5207, "text": "Operating Systems" }, { "code": null, "e": 5323, "s": 5225, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5344, "s": 5323, "text": "Normal Forms in DBMS" }, { "code": null, "e": 5393, "s": 5344, "text": "Page Replacement Algorithms in Operating Systems" }, { "code": null, "e": 5427, "s": 5393, "text": "Inter Process Communication (IPC)" }, { "code": null, "e": 5459, "s": 5427, "text": "Differences between TCP and UDP" }, { "code": null, "e": 5500, "s": 5459, "text": "Introduction of Operating System - Set 1" }, { "code": null, "e": 5539, "s": 5500, "text": "Banker's Algorithm in Operating System" }, { "code": null, "e": 5588, "s": 5539, "text": "Page Replacement Algorithms in Operating Systems" }, { "code": null, "e": 5615, "s": 5588, "text": "Disk Scheduling Algorithms" }, { "code": null, "e": 5639, "s": 5615, "text": "File Allocation Methods" } ]
Python PIL | Image.convert() Method
26 Jul, 2019 PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images. Image.convert() Returns a converted copy of this image. For the “P” mode, this method translates pixels through the palette. If mode is omitted, a mode is chosen so that all information in the image and the palette can be represented without a palette. Syntax: Image.convert(mode=None, matrix=None, dither=None, palette=0, colors=256) Parameters:mode – The requested mode. See: Modes.matrix – An optional conversion matrix. If given, this should be 4- or 12-tuple containing floating point values.dither – Dithering method, used when converting from mode “RGB” to “P” or from “RGB” or “L” to “1”. Available methods are NONE or FLOYDSTEINBERG (default).palette – Palette to use when converting from mode “RGB” to “P”. Available palettes are WEB or ADAPTIVE.colors – Number of colors to use for the ADAPTIVE palette. Defaults to 256. Returns: An Image object. Image Used: # importing image class from PIL packagefrom PIL import Image # creating image objectimg = Image.open(r"C:\Users\System-Pc\Desktop\scene3.jpg") # using convert method for img1img1 = img.convert("L")img1.show() # using convert method for img2 img2 = img.convert("1")img2.show() Output1: Output2: Another Example: Taking another image. Image Used: # importing image class from PIL packagefrom PIL import Image # creating image objectimg = Image.open(r"C:\Users\System-Pc\Desktop\scene4.jpg") # using convert method for img1img1 = img.convert("L")img1.show() # using convert method for img2 img2 = img.convert("1")img2.show() Output1: Output2: Python-pil Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 54, "s": 26, "text": "\n26 Jul, 2019" }, { "code": null, "e": 381, "s": 54, "text": "PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images." }, { "code": null, "e": 634, "s": 381, "text": "Image.convert() Returns a converted copy of this image. For the “P” mode, this method translates pixels through the palette. If mode is omitted, a mode is chosen so that all information in the image and the palette can be represented without a palette." }, { "code": null, "e": 716, "s": 634, "text": "Syntax: Image.convert(mode=None, matrix=None, dither=None, palette=0, colors=256)" }, { "code": null, "e": 1213, "s": 716, "text": "Parameters:mode – The requested mode. See: Modes.matrix – An optional conversion matrix. If given, this should be 4- or 12-tuple containing floating point values.dither – Dithering method, used when converting from mode “RGB” to “P” or from “RGB” or “L” to “1”. Available methods are NONE or FLOYDSTEINBERG (default).palette – Palette to use when converting from mode “RGB” to “P”. Available palettes are WEB or ADAPTIVE.colors – Number of colors to use for the ADAPTIVE palette. Defaults to 256." }, { "code": null, "e": 1239, "s": 1213, "text": "Returns: An Image object." }, { "code": null, "e": 1251, "s": 1239, "text": "Image Used:" }, { "code": " # importing image class from PIL packagefrom PIL import Image # creating image objectimg = Image.open(r\"C:\\Users\\System-Pc\\Desktop\\scene3.jpg\") # using convert method for img1img1 = img.convert(\"L\")img1.show() # using convert method for img2 img2 = img.convert(\"1\")img2.show()", "e": 1536, "s": 1251, "text": null }, { "code": null, "e": 1545, "s": 1536, "text": "Output1:" }, { "code": null, "e": 1554, "s": 1545, "text": "Output2:" }, { "code": null, "e": 1593, "s": 1554, "text": "Another Example: Taking another image." }, { "code": null, "e": 1605, "s": 1593, "text": "Image Used:" }, { "code": " # importing image class from PIL packagefrom PIL import Image # creating image objectimg = Image.open(r\"C:\\Users\\System-Pc\\Desktop\\scene4.jpg\") # using convert method for img1img1 = img.convert(\"L\")img1.show() # using convert method for img2 img2 = img.convert(\"1\")img2.show()", "e": 1890, "s": 1605, "text": null }, { "code": null, "e": 1899, "s": 1890, "text": "Output1:" }, { "code": null, "e": 1908, "s": 1899, "text": "Output2:" }, { "code": null, "e": 1919, "s": 1908, "text": "Python-pil" }, { "code": null, "e": 1926, "s": 1919, "text": "Python" }, { "code": null, "e": 2024, "s": 1926, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2042, "s": 2024, "text": "Python Dictionary" }, { "code": null, "e": 2084, "s": 2042, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2106, "s": 2084, "text": "Enumerate() in Python" }, { "code": null, "e": 2141, "s": 2106, "text": "Read a file line by line in Python" }, { "code": null, "e": 2167, "s": 2141, "text": "Python String | replace()" }, { "code": null, "e": 2199, "s": 2167, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2228, "s": 2199, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2255, "s": 2228, "text": "Python Classes and Objects" }, { "code": null, "e": 2285, "s": 2255, "text": "Iterate over a list in Python" } ]
PostGIS, A Complete Workflow. Tackle geospatial challenges with... | by Farzin Ashouri | Towards Data Science
If you have separate shapefiles for world countries and major cities, you can view and query the data using ArcGIS, QGIS, or any other GIS software package. You can download the data from here (made with Natural Earth). For instance, you can perform the following operations: Use the identify tool to get some information about the feature you clicked Determine or set which Spatial Reference System the data is referring to Reproject your data Compute distance and area Compute centroid Perform buffer analysis The good news is that you can do all these operations with PostGIS. A question may arise on the necessity of performing all these operations on a spatial database. What’s the point of reformulating our problem in PostGIS when we can do it easily in an open-source or proprietary software package? PostGIS would come in handy when you want to develop your web, mobile, or desktop app. The data we are using here consists of just a limited number of static records. In some cases, you may find yourself in a situation where there is a continuous data flow. Desktop GIS tools may not be appropriate to digest this kind of data and perform (near) real-time analysis. When dealing with a geospatial problem, there are four significant steps you can consider to answer the question correctly: ModellingPreparation and loading the dataWrite a query to solve the problemView the results Modelling Preparation and loading the data Write a query to solve the problem View the results I depicted the steps on a diagram for you: We will go through all these steps and try to tackle the challenges proposed earlier. Modelling is the process of translating the real world into a model that is composed of database objects. In other words, a model, by definition, is the simplified representation of reality. For example, you’ll represent the countries as polygons and cities as points. You’ll then create a table for each. You need to store some information about each record. You may not be able to keep all the information about them, so you’ll choose the ones that help you with the problem at hand or problems that may arise later. At the first step, you need to create a database and a schema to hold your data. A schema is a container that logically segments objects (tables, functions, views, and so on) for better management. There is a default public schema in the database you create in PostgreSQL, but I’d instead create a new one. Keep in mind that it is up to you to what extent you want to simplify the real world in your model. Modelling is inherently a tradeoff between simplicity and adequacy. Even though all models have flaws, they provide us with a more cost-effective approach. It would be best if you created a database and a schema first: CREATE DATABASE postgis_training; CREATE SCHEMA postgis1; PostGIS functions and operations would not work by default, and you need to enable PostGIS in your database to make them work: CREATE EXTENSION postgis; We need to create two tables to house world countries and cities data: CREATE TABLE postgis1.countries ( id serial, formal_name VARCHAR(50) PRIMARY key, country_iso3 CHAR(3), population INT, gdp INT, economy VARCHAR(50), income_group VARCHAR(50), continent VARCHAR(50), subregion VARCHAR(50), region_world_bank VARCHAR(50), geog geography(multipolygon, 4326));CREATE TABLE postgis1.cities ( id SERIAL PRIMARY KEY, city_name VARCHAR(50), country_iso3_code CHAR(3), featurecla VARCHAR(50), population INT, geog GEOGRAPHY(POINT, 4326)); Take a look at shapefiles that you have already downloaded. We do not need all the fields that they have provided. We choose the ones that are appropriate for our problem. I think the column names in the tables we created are intuitive enough, and there is no need for any explanations except for just a few of them. Columns country_iso3 and country_iso_code here denote Alpha-3 codes, which are three-letter country codes defined in ISO 3166–1 published by the International Organization for Standardization (ISO). I intentionally have chosen different names here to avoid confusion. You can use the same names for columns that have the same meaning. You can see the ERD representation of our database in Figure 2. For those of you who may not be familiar with the spatial_ref_sys table, it is a table in every PostGIS enabled database that lists all the valid SRID values and their corresponding proj4text representation of a Spatial Reference System (SRS). Let’s import all your shapefiles as it is directly into our database. When we import data directly from an external file, we normally call it a staging table. A staging table is just a temporary table containing the raw data. They are used to populate the main tables in the model we already designed. To import the ne_50m_populated_places.shp shapefile, we use a command-line utility called shp2pgsql that come with PostGIS installation. Navigate to your shapefiles folder in the command-line tool of your operating system and run the following command: shp2pgsql -s 4326 -I -G ne_50m_populated_places.shp postgis1.cities_staging > staging_cities.sql It would create a file called staging_cities.sql in the same folder. We are telling that the SRID of the table we want to create is 4326 (-s 4326). We Create a spatial index on the geocolumn by adding -I as an option. We add -G option which means we are using the geography type. You can do much more with this command, but we decided to keep things simple here. The next step is to run created SQL file to make the postgis1.cities_staging table. You can use the built-in psql command-line utility to do that: psql -h localhost -d postgis_training -U postgres -f staging_cities.sql Do the same for the ne_110m_admin_0_countries.shp table with the following commands: shp2pgsql -s 4326 -I -G ne_110m_admin_0_countries.shp postgis1.countries_staging > staging_countries.sqlpsql -h localhost -d postgis_training -U postgres -f staging_countries.sql Now that we have imported our shapefiles, it is about time to populate the tables we created in our model. INSERT INTO postgis1.countries ( formal_name, country_iso3, population, gdp, economy, income_group, continent, subregion, region_world_bank, geog)SELECT name_sort, adm0_a3, pop_est, gdp_md_est, economy, income_grp, continent, subregion, region_wb, geogFROM postgis1.countries_staging;INSERT INTO postgis1.cities ( city_name, country_iso3_code, featurecla, population, geog)SELECT NAME, SOV_a3, FEATURECLA, POP_OTHER, geogFROM postgis1.cities_staging; We just selected the corresponding columns from staging tables to populate our main tables. We have covered how to model a spatial problem and populate it with real-world data. In the next section of this article, we will deal with some common questions that you may come up with. Now our model and database are ready to run spatial SQL queries to answer different questions. Here we have some questions to answer, and we will go through each of them: Select and create a table of all European countries As an ice-breaker, we would like to return European countries. We don’t use any spatial functions here: SELECT * INTO postgis1.eu_countriesFROM postgis1.countriesWHERE continent = 'Europe' Select all the cities that reside inside European countries Now we select all the cities that intersect with European countries. Since we need both tables, we have to join the tables: SELECT postgis1.cities.* INTO postgis1.eu_citiesFROM postgis1.cities INNER JOIN postgis1.eu_countries ON ST_Intersects( postgis1.cities.geog, postgis1.eu_countries.geog ); Reproject European cities and countries tables and store them as separate geometry tables If you want to reproject a geography table into a projected coordinate reference system, you convert the geography column into a geometry column. Then the geog column name may be misleading. At first, let’s rename the geog column in both tables into geom: ALTER TABLE postgis1.eu_cities RENAME COLUMN geog TO geom;ALTER TABLE postgis1.eu_countries RENAME COLUMN geog TO geom; Notice that we renamed our columns to geom, but they still inherently contain geography data. We don’t let this situation last any longer and transform it into World Mercator (SRID 3395) which is a projected coordinate reference system: ALTER TABLE postgis1.eu_cities ALTER COLUMN geom TYPE geometry(POINT, 3395) USING ST_Transform(geom::geometry, 3395);ALTER TABLE postgis1.eu_countries ALTER COLUMN geom TYPE geometry(MULTIPOLYGON, 3395) USING ST_Transform(geom::geometry, 3395); Now we have fully transformed our European tables into World Mercator and geometry data type. Many PostGIS functions do not support geography type. Besides, many spatial calculations are inherently performed correctly on a projected CRS. We consider these two tables for the rest of the operations. Export newly created tables as shapefiles You can make use of another command-line utility called pgsql2shp to export spatial tables to shapefiles. Run the following commands in the command-line tool available on your operating system. Make sure to make a folder called shp in the same folder you are running the commands: pgsql2shp -f ./shp/eu_cities_shp -h localhost -u postgres postgis_training postgis1.eu_citiespgsql2shp -f eu_countries_shp -h localhost -u postgres postgis_training postgis1.eu_countries The commands will create shapefiles of cities and countries in the shp folder. The format of the pgsql2shp command is as follows: pgsql2shp [options] database [schema.]table The options seem intuitive enough, but I elaborate on them to make everything clear: -f use this option to specify the shapefile name and address you want to create-h use this option to specify the database host to connect to-u use this option to connect to the database as the specified user You might want to consider some other options, but the specified options are enough for what we want to do. Identify the country that a particular point is located Consider having coordinates in a geodetic coordinate system (WGS84 lon/lat SRID of 4326) in which longitude = 32.6542 and latitude = 50.9533. We want to know which country this point lies in. What we want to do is comparable to identify tool in most GIS software packages. Notice that our dataset no longer uses the SRID of 4326. We need to transform the point into World Mercator (SRID 3395) on the fly: WITH identify AS( SELECT ST_Transform( ST_SetSRID( ST_Point(32.6542, 50.9533), 4326 ), 3395 ) AS ipoint)SELECT postgis1.eu_countries.*FROM postgis1.eu_countries, identifyWHERE ST_Within(ipoint, geom) We used a CTE to define and transform a point. ST_Within(geometry A, geometry B) returns TRUE if geometry A is entirely inside geometry B. This function will help us find the country we are looking for. Find the area of a country PostGIS has a ST_Area function that is used to determine the area of a polygon. It returns the area with units specified by the SRID. Once more, we need to transform the SRID on the fly: WITH identify AS( SELECT ST_Transform( ST_SetSRID( ST_Point(32.6542, 50.9533), 4326 ), 3395 ) AS ipoint)SELECT ST_Area(geom)FROM postgis1.eu_countries, identifyWHERE ST_Within(ipoint, geom) The identify CTE part is just for finding the country, followed by a piece of code to determine the area. If we run this code, it returns 1394397442159.71, and the unit is in square meters, equivalent to 1394.39 square kilometres. If you google the size of Ukraine, you get quite a different figure. The area of Ukraine is 603.63 square kilometres. We computed a figure that is over two times the actual figure. How can this be justified? The fact of the matter is that World Mercator (SRID 3395) does not preserve the area. From the equator outward, the area of polygons rises much faster than the actual number. That’s why Greenland looks much larger on many world maps. To get an accurate area, we need to use an equal-area Spatial Reference System. I chose Europe Albers Equal Area Conic (SRID 102013) for that. It covers the whole of Europe and hopefully preserves the area of polygons. We need an on-the-fly transformation of Ukrain polygon in our query: WITH identify AS( SELECT ST_Transform( ST_SetSRID( ST_Point(32.6542, 50.9533), 4326 ), 3395 ) AS ipoint)SELECT ST_Area( ST_Transform(geom, 3035) )FROM postgis1.eu_countries, identifyWHERE ST_Within(ipoint, geom) The result is 601914411764.12 square meters is equivalent to 601.91 square kilometres. It is comparable to the official area of the country (603.63 km2), and the slight difference is most likely due to inaccurate polygons on the map. Still, there is a second option. The area and distance measurements (especially over the large areas) are guaranteed to be accurate when using the geography type. Moreover, the curvature of the earth is considered. To take advantage of geography type, let’s look at the countries table in our original model and see if we can solve the problem. Nevertheless, not all spatial functions, including ST_Distance are supported by geography type. We can opt for ST_Covers that works well with geography type: WITH identify AS( SELECT ST_SetSRID( ST_Point(32.6542, 50.9533), 4326 ) AS ipoint)SELECT ST_Area(geog)FROM postgis1.countries, identifyWHERE ST_Covers(geog, ipoint) Find the distance between Berlin and London. We have learned from the previous challenge that for measurements over large areas, geography data type might be a suitable option: SELECT ST_Distance(a.geog, b.geog)From postgis1.cities a, postgis1.cities bWHERE a.city_name = 'Berlin' AND b.city_name = 'London' Since you want to find the distance between two points in the same table, you must reference the same table twice. ST_Distance would make use of the ellipsoidal model and can be considered accurate enough for many applications. The query would return 933677.99m, which seems reasonable. Sometimes PostGIS is called GIS without GIS. A visual representation of spatial data is critical to understanding any geospatial problem. Without seeing it on a map, you won’t be able to fully understand the situation. However, spatial databases aren’t designed to visualize spatial data. You can, however, find a way around this. Some GIS software packages can connect directly to PostGIS to show spatial tables and queries. My favourite is QGIS. Click and select View > Panels > Browser. It will open Browser Panel for you if it is not opened by default. In the Browser Panel, you can find PostGIS. Right-click on that and choose New Connection. In the dialogue box, fill the options like I did (Figure 3) and test the connection. If the connection to add was successful, you could hit the ok button to make the connection. A new connection with the name you have chosen (in my case: postgis_conn) would appear under the PostGIS branch of the Browser panel. You can find your schemas and tables of the postgis1 database (Figure 4). If you double-click on any of the tables, it will be shown on the map canvas and added to the layer panel. Layers can be turned on and off, exported, and used almost as you would shapefiles. What if we want to show the result of a query on a map? To accomplish that, choose Database > DB Manager... from the main menu. In the DB Manager, select Database > SQL Window. According to Figure 5, we wrote a simple query to return Asian countries, and then I hit execute. Then I checked the Load as a layer checkbox, filled the necessary fields and clicked Load. Surprisingly, if you check the layer panel once more, you can find a new layer with the name you have chosen (here, layer name is: Asian_Query) on the layer panel. With the aid of simple examples, we examined the entire workflow of tackling a spatial problem using PostGIS. PostGIS can do a lot more, but the workflow is the same for many spatial challenges.
[ { "code": null, "e": 267, "s": 47, "text": "If you have separate shapefiles for world countries and major cities, you can view and query the data using ArcGIS, QGIS, or any other GIS software package. You can download the data from here (made with Natural Earth)." }, { "code": null, "e": 323, "s": 267, "text": "For instance, you can perform the following operations:" }, { "code": null, "e": 399, "s": 323, "text": "Use the identify tool to get some information about the feature you clicked" }, { "code": null, "e": 472, "s": 399, "text": "Determine or set which Spatial Reference System the data is referring to" }, { "code": null, "e": 492, "s": 472, "text": "Reproject your data" }, { "code": null, "e": 518, "s": 492, "text": "Compute distance and area" }, { "code": null, "e": 535, "s": 518, "text": "Compute centroid" }, { "code": null, "e": 559, "s": 535, "text": "Perform buffer analysis" }, { "code": null, "e": 856, "s": 559, "text": "The good news is that you can do all these operations with PostGIS. A question may arise on the necessity of performing all these operations on a spatial database. What’s the point of reformulating our problem in PostGIS when we can do it easily in an open-source or proprietary software package?" }, { "code": null, "e": 1222, "s": 856, "text": "PostGIS would come in handy when you want to develop your web, mobile, or desktop app. The data we are using here consists of just a limited number of static records. In some cases, you may find yourself in a situation where there is a continuous data flow. Desktop GIS tools may not be appropriate to digest this kind of data and perform (near) real-time analysis." }, { "code": null, "e": 1346, "s": 1222, "text": "When dealing with a geospatial problem, there are four significant steps you can consider to answer the question correctly:" }, { "code": null, "e": 1438, "s": 1346, "text": "ModellingPreparation and loading the dataWrite a query to solve the problemView the results" }, { "code": null, "e": 1448, "s": 1438, "text": "Modelling" }, { "code": null, "e": 1481, "s": 1448, "text": "Preparation and loading the data" }, { "code": null, "e": 1516, "s": 1481, "text": "Write a query to solve the problem" }, { "code": null, "e": 1533, "s": 1516, "text": "View the results" }, { "code": null, "e": 1576, "s": 1533, "text": "I depicted the steps on a diagram for you:" }, { "code": null, "e": 1662, "s": 1576, "text": "We will go through all these steps and try to tackle the challenges proposed earlier." }, { "code": null, "e": 2181, "s": 1662, "text": "Modelling is the process of translating the real world into a model that is composed of database objects. In other words, a model, by definition, is the simplified representation of reality. For example, you’ll represent the countries as polygons and cities as points. You’ll then create a table for each. You need to store some information about each record. You may not be able to keep all the information about them, so you’ll choose the ones that help you with the problem at hand or problems that may arise later." }, { "code": null, "e": 2807, "s": 2181, "text": "At the first step, you need to create a database and a schema to hold your data. A schema is a container that logically segments objects (tables, functions, views, and so on) for better management. There is a default public schema in the database you create in PostgreSQL, but I’d instead create a new one. Keep in mind that it is up to you to what extent you want to simplify the real world in your model. Modelling is inherently a tradeoff between simplicity and adequacy. Even though all models have flaws, they provide us with a more cost-effective approach. It would be best if you created a database and a schema first:" }, { "code": null, "e": 2866, "s": 2807, "text": " CREATE DATABASE postgis_training; CREATE SCHEMA postgis1;" }, { "code": null, "e": 2993, "s": 2866, "text": "PostGIS functions and operations would not work by default, and you need to enable PostGIS in your database to make them work:" }, { "code": null, "e": 3019, "s": 2993, "text": "CREATE EXTENSION postgis;" }, { "code": null, "e": 3090, "s": 3019, "text": "We need to create two tables to house world countries and cities data:" }, { "code": null, "e": 3570, "s": 3090, "text": "CREATE TABLE postgis1.countries ( id serial, formal_name VARCHAR(50) PRIMARY key, country_iso3 CHAR(3), population INT, gdp INT, economy VARCHAR(50), income_group VARCHAR(50), continent VARCHAR(50), subregion VARCHAR(50), region_world_bank VARCHAR(50), geog geography(multipolygon, 4326));CREATE TABLE postgis1.cities ( id SERIAL PRIMARY KEY, city_name VARCHAR(50), country_iso3_code CHAR(3), featurecla VARCHAR(50), population INT, geog GEOGRAPHY(POINT, 4326));" }, { "code": null, "e": 4222, "s": 3570, "text": "Take a look at shapefiles that you have already downloaded. We do not need all the fields that they have provided. We choose the ones that are appropriate for our problem. I think the column names in the tables we created are intuitive enough, and there is no need for any explanations except for just a few of them. Columns country_iso3 and country_iso_code here denote Alpha-3 codes, which are three-letter country codes defined in ISO 3166–1 published by the International Organization for Standardization (ISO). I intentionally have chosen different names here to avoid confusion. You can use the same names for columns that have the same meaning." }, { "code": null, "e": 4530, "s": 4222, "text": "You can see the ERD representation of our database in Figure 2. For those of you who may not be familiar with the spatial_ref_sys table, it is a table in every PostGIS enabled database that lists all the valid SRID values and their corresponding proj4text representation of a Spatial Reference System (SRS)." }, { "code": null, "e": 5085, "s": 4530, "text": "Let’s import all your shapefiles as it is directly into our database. When we import data directly from an external file, we normally call it a staging table. A staging table is just a temporary table containing the raw data. They are used to populate the main tables in the model we already designed. To import the ne_50m_populated_places.shp shapefile, we use a command-line utility called shp2pgsql that come with PostGIS installation. Navigate to your shapefiles folder in the command-line tool of your operating system and run the following command:" }, { "code": null, "e": 5182, "s": 5085, "text": "shp2pgsql -s 4326 -I -G ne_50m_populated_places.shp postgis1.cities_staging > staging_cities.sql" }, { "code": null, "e": 5692, "s": 5182, "text": "It would create a file called staging_cities.sql in the same folder. We are telling that the SRID of the table we want to create is 4326 (-s 4326). We Create a spatial index on the geocolumn by adding -I as an option. We add -G option which means we are using the geography type. You can do much more with this command, but we decided to keep things simple here. The next step is to run created SQL file to make the postgis1.cities_staging table. You can use the built-in psql command-line utility to do that:" }, { "code": null, "e": 5764, "s": 5692, "text": "psql -h localhost -d postgis_training -U postgres -f staging_cities.sql" }, { "code": null, "e": 5849, "s": 5764, "text": "Do the same for the ne_110m_admin_0_countries.shp table with the following commands:" }, { "code": null, "e": 6028, "s": 5849, "text": "shp2pgsql -s 4326 -I -G ne_110m_admin_0_countries.shp postgis1.countries_staging > staging_countries.sqlpsql -h localhost -d postgis_training -U postgres -f staging_countries.sql" }, { "code": null, "e": 6135, "s": 6028, "text": "Now that we have imported our shapefiles, it is about time to populate the tables we created in our model." }, { "code": null, "e": 6611, "s": 6135, "text": "INSERT INTO postgis1.countries ( formal_name, country_iso3, population, gdp, economy, income_group, continent, subregion, region_world_bank, geog)SELECT name_sort, adm0_a3, pop_est, gdp_md_est, economy, income_grp, continent, subregion, region_wb, geogFROM postgis1.countries_staging;INSERT INTO postgis1.cities ( city_name, country_iso3_code, featurecla, population, geog)SELECT NAME, SOV_a3, FEATURECLA, POP_OTHER, geogFROM postgis1.cities_staging;" }, { "code": null, "e": 6703, "s": 6611, "text": "We just selected the corresponding columns from staging tables to populate our main tables." }, { "code": null, "e": 6892, "s": 6703, "text": "We have covered how to model a spatial problem and populate it with real-world data. In the next section of this article, we will deal with some common questions that you may come up with." }, { "code": null, "e": 7063, "s": 6892, "text": "Now our model and database are ready to run spatial SQL queries to answer different questions. Here we have some questions to answer, and we will go through each of them:" }, { "code": null, "e": 7115, "s": 7063, "text": "Select and create a table of all European countries" }, { "code": null, "e": 7219, "s": 7115, "text": "As an ice-breaker, we would like to return European countries. We don’t use any spatial functions here:" }, { "code": null, "e": 7310, "s": 7219, "text": "SELECT * INTO postgis1.eu_countriesFROM postgis1.countriesWHERE continent = 'Europe'" }, { "code": null, "e": 7370, "s": 7310, "text": "Select all the cities that reside inside European countries" }, { "code": null, "e": 7494, "s": 7370, "text": "Now we select all the cities that intersect with European countries. Since we need both tables, we have to join the tables:" }, { "code": null, "e": 7682, "s": 7494, "text": "SELECT postgis1.cities.* INTO postgis1.eu_citiesFROM postgis1.cities INNER JOIN postgis1.eu_countries ON ST_Intersects( postgis1.cities.geog, postgis1.eu_countries.geog );" }, { "code": null, "e": 7772, "s": 7682, "text": "Reproject European cities and countries tables and store them as separate geometry tables" }, { "code": null, "e": 8028, "s": 7772, "text": "If you want to reproject a geography table into a projected coordinate reference system, you convert the geography column into a geometry column. Then the geog column name may be misleading. At first, let’s rename the geog column in both tables into geom:" }, { "code": null, "e": 8152, "s": 8028, "text": "ALTER TABLE postgis1.eu_cities RENAME COLUMN geog TO geom;ALTER TABLE postgis1.eu_countries RENAME COLUMN geog TO geom;" }, { "code": null, "e": 8389, "s": 8152, "text": "Notice that we renamed our columns to geom, but they still inherently contain geography data. We don’t let this situation last any longer and transform it into World Mercator (SRID 3395) which is a projected coordinate reference system:" }, { "code": null, "e": 8641, "s": 8389, "text": "ALTER TABLE postgis1.eu_cities ALTER COLUMN geom TYPE geometry(POINT, 3395) USING ST_Transform(geom::geometry, 3395);ALTER TABLE postgis1.eu_countries ALTER COLUMN geom TYPE geometry(MULTIPOLYGON, 3395) USING ST_Transform(geom::geometry, 3395);" }, { "code": null, "e": 8940, "s": 8641, "text": "Now we have fully transformed our European tables into World Mercator and geometry data type. Many PostGIS functions do not support geography type. Besides, many spatial calculations are inherently performed correctly on a projected CRS. We consider these two tables for the rest of the operations." }, { "code": null, "e": 8982, "s": 8940, "text": "Export newly created tables as shapefiles" }, { "code": null, "e": 9263, "s": 8982, "text": "You can make use of another command-line utility called pgsql2shp to export spatial tables to shapefiles. Run the following commands in the command-line tool available on your operating system. Make sure to make a folder called shp in the same folder you are running the commands:" }, { "code": null, "e": 9450, "s": 9263, "text": "pgsql2shp -f ./shp/eu_cities_shp -h localhost -u postgres postgis_training postgis1.eu_citiespgsql2shp -f eu_countries_shp -h localhost -u postgres postgis_training postgis1.eu_countries" }, { "code": null, "e": 9529, "s": 9450, "text": "The commands will create shapefiles of cities and countries in the shp folder." }, { "code": null, "e": 9580, "s": 9529, "text": "The format of the pgsql2shp command is as follows:" }, { "code": null, "e": 9624, "s": 9580, "text": "pgsql2shp [options] database [schema.]table" }, { "code": null, "e": 9709, "s": 9624, "text": "The options seem intuitive enough, but I elaborate on them to make everything clear:" }, { "code": null, "e": 9917, "s": 9709, "text": "-f use this option to specify the shapefile name and address you want to create-h use this option to specify the database host to connect to-u use this option to connect to the database as the specified user" }, { "code": null, "e": 10025, "s": 9917, "text": "You might want to consider some other options, but the specified options are enough for what we want to do." }, { "code": null, "e": 10081, "s": 10025, "text": "Identify the country that a particular point is located" }, { "code": null, "e": 10354, "s": 10081, "text": "Consider having coordinates in a geodetic coordinate system (WGS84 lon/lat SRID of 4326) in which longitude = 32.6542 and latitude = 50.9533. We want to know which country this point lies in. What we want to do is comparable to identify tool in most GIS software packages." }, { "code": null, "e": 10486, "s": 10354, "text": "Notice that our dataset no longer uses the SRID of 4326. We need to transform the point into World Mercator (SRID 3395) on the fly:" }, { "code": null, "e": 10728, "s": 10486, "text": "WITH identify AS( SELECT ST_Transform( ST_SetSRID( ST_Point(32.6542, 50.9533), 4326 ), 3395 ) AS ipoint)SELECT postgis1.eu_countries.*FROM postgis1.eu_countries, identifyWHERE ST_Within(ipoint, geom)" }, { "code": null, "e": 10931, "s": 10728, "text": "We used a CTE to define and transform a point. ST_Within(geometry A, geometry B) returns TRUE if geometry A is entirely inside geometry B. This function will help us find the country we are looking for." }, { "code": null, "e": 10958, "s": 10931, "text": "Find the area of a country" }, { "code": null, "e": 11145, "s": 10958, "text": "PostGIS has a ST_Area function that is used to determine the area of a polygon. It returns the area with units specified by the SRID. Once more, we need to transform the SRID on the fly:" }, { "code": null, "e": 11377, "s": 11145, "text": "WITH identify AS( SELECT ST_Transform( ST_SetSRID( ST_Point(32.6542, 50.9533), 4326 ), 3395 ) AS ipoint)SELECT ST_Area(geom)FROM postgis1.eu_countries, identifyWHERE ST_Within(ipoint, geom)" }, { "code": null, "e": 11816, "s": 11377, "text": "The identify CTE part is just for finding the country, followed by a piece of code to determine the area. If we run this code, it returns 1394397442159.71, and the unit is in square meters, equivalent to 1394.39 square kilometres. If you google the size of Ukraine, you get quite a different figure. The area of Ukraine is 603.63 square kilometres. We computed a figure that is over two times the actual figure. How can this be justified?" }, { "code": null, "e": 12338, "s": 11816, "text": "The fact of the matter is that World Mercator (SRID 3395) does not preserve the area. From the equator outward, the area of polygons rises much faster than the actual number. That’s why Greenland looks much larger on many world maps. To get an accurate area, we need to use an equal-area Spatial Reference System. I chose Europe Albers Equal Area Conic (SRID 102013) for that. It covers the whole of Europe and hopefully preserves the area of polygons. We need an on-the-fly transformation of Ukrain polygon in our query:" }, { "code": null, "e": 12596, "s": 12338, "text": "WITH identify AS( SELECT ST_Transform( ST_SetSRID( ST_Point(32.6542, 50.9533), 4326 ), 3395 ) AS ipoint)SELECT ST_Area( ST_Transform(geom, 3035) )FROM postgis1.eu_countries, identifyWHERE ST_Within(ipoint, geom)" }, { "code": null, "e": 12830, "s": 12596, "text": "The result is 601914411764.12 square meters is equivalent to 601.91 square kilometres. It is comparable to the official area of the country (603.63 km2), and the slight difference is most likely due to inaccurate polygons on the map." }, { "code": null, "e": 13333, "s": 12830, "text": "Still, there is a second option. The area and distance measurements (especially over the large areas) are guaranteed to be accurate when using the geography type. Moreover, the curvature of the earth is considered. To take advantage of geography type, let’s look at the countries table in our original model and see if we can solve the problem. Nevertheless, not all spatial functions, including ST_Distance are supported by geography type. We can opt for ST_Covers that works well with geography type:" }, { "code": null, "e": 13522, "s": 13333, "text": "WITH identify AS( SELECT ST_SetSRID( ST_Point(32.6542, 50.9533), 4326 ) AS ipoint)SELECT ST_Area(geog)FROM postgis1.countries, identifyWHERE ST_Covers(geog, ipoint)" }, { "code": null, "e": 13567, "s": 13522, "text": "Find the distance between Berlin and London." }, { "code": null, "e": 13699, "s": 13567, "text": "We have learned from the previous challenge that for measurements over large areas, geography data type might be a suitable option:" }, { "code": null, "e": 13836, "s": 13699, "text": "SELECT ST_Distance(a.geog, b.geog)From postgis1.cities a, postgis1.cities bWHERE a.city_name = 'Berlin' AND b.city_name = 'London'" }, { "code": null, "e": 14123, "s": 13836, "text": "Since you want to find the distance between two points in the same table, you must reference the same table twice. ST_Distance would make use of the ellipsoidal model and can be considered accurate enough for many applications. The query would return 933677.99m, which seems reasonable." }, { "code": null, "e": 14571, "s": 14123, "text": "Sometimes PostGIS is called GIS without GIS. A visual representation of spatial data is critical to understanding any geospatial problem. Without seeing it on a map, you won’t be able to fully understand the situation. However, spatial databases aren’t designed to visualize spatial data. You can, however, find a way around this. Some GIS software packages can connect directly to PostGIS to show spatial tables and queries. My favourite is QGIS." }, { "code": null, "e": 14949, "s": 14571, "text": "Click and select View > Panels > Browser. It will open Browser Panel for you if it is not opened by default. In the Browser Panel, you can find PostGIS. Right-click on that and choose New Connection. In the dialogue box, fill the options like I did (Figure 3) and test the connection. If the connection to add was successful, you could hit the ok button to make the connection." }, { "code": null, "e": 15348, "s": 14949, "text": "A new connection with the name you have chosen (in my case: postgis_conn) would appear under the PostGIS branch of the Browser panel. You can find your schemas and tables of the postgis1 database (Figure 4). If you double-click on any of the tables, it will be shown on the map canvas and added to the layer panel. Layers can be turned on and off, exported, and used almost as you would shapefiles." }, { "code": null, "e": 15525, "s": 15348, "text": "What if we want to show the result of a query on a map? To accomplish that, choose Database > DB Manager... from the main menu. In the DB Manager, select Database > SQL Window." }, { "code": null, "e": 15878, "s": 15525, "text": "According to Figure 5, we wrote a simple query to return Asian countries, and then I hit execute. Then I checked the Load as a layer checkbox, filled the necessary fields and clicked Load. Surprisingly, if you check the layer panel once more, you can find a new layer with the name you have chosen (here, layer name is: Asian_Query) on the layer panel." } ]
Check whether a given array is a k sorted array or not - GeeksforGeeks
21 Apr, 2022 Given an array of n distinct elements. Check whether the given array is a k sorted array or not. A k sorted array is an array where each element is at most k distances away from its target position in the sorted array. For example, let us consider k is 2, an element at index 7 in the sorted array, can be at indexes 5, 6, 7, 8, 9 in the given array. Examples: Input : arr[] = {3, 2, 1, 5, 6, 4}, k = 2 Output : Yes Every element is at most 2 distance away from its target position in the sorted array. Input : arr[] = {13, 8, 10, 7, 15, 14, 12}, k = 3 Output : No 13 is more than k = 3 distance away from its target position in the sorted array. Copy elements of the original array arr[] to an auxiliary array aux[]. Sort aux[]. Now, for each element at index i in arr[], find its index j in aux[] using Binary Search. If for any element k < abs(i-j), then arr[] is not a k sorted array. Else it is a k sorted array. Here abs are the absolute value. C++ Java Python3 C# Javascript // C++ implementation to check whether the given array// is a k sorted array or not#include <bits / stdc++.h>using namespace std; // function to find index of element 'x' in sorted 'arr'// uses binary search techniqueint binarySearch(int arr[], int low, int high, int x){ while (low <= high) { int mid = (low + high) / 2; if (arr[mid] == x) return mid; else if (arr[mid] > x) high = mid - 1; else low = mid + 1; }} // function to check whether the given array is// a 'k' sorted array or notstring isKSortedArray(int arr[], int n, int k){ // auxiliary array 'aux' int aux[n]; // copy elements of 'arr' to 'aux' for (int i = 0; i<n; i++) aux[i] = arr[i]; // sort 'aux' sort(aux, aux + n); // for every element of 'arr' at index 'i', // find its index 'j' in 'aux' for (int i = 0; i<n; i++) { // index of arr[i] in sorted array 'aux' int j = binarySearch(aux, 0, n-1, arr[i]); // if abs(i-j) > k, then that element is // not at-most k distance away from its // target position. Thus, 'arr' is not a // k sorted array if (abs(i - j) > k) return "No"; } // 'arr' is a k sorted array return "Yes"; } // Driver program to test aboveint main(){ int arr[] = {3, 2, 1, 5, 6, 4}; int n = sizeof(arr) / sizeof(arr[0]); int k = 2; cout << "Is it a k sorted array?: " << isKSortedArray(arr, n, k); return 0; } // Java implementation to check whether the given array// is a k sorted array or not import java.util.Arrays; class Test{ // Method to check whether the given array is // a 'k' sorted array or not static String isKSortedArray(int arr[], int n, int k) { // auxiliary array 'aux' int aux[] = new int[n]; // copy elements of 'arr' to 'aux' for (int i = 0; i<n; i++) aux[i] = arr[i]; // sort 'aux' Arrays.sort(aux); // for every element of 'arr' at index 'i', // find its index 'j' in 'aux' for (int i = 0; i<n; i++) { // index of arr[i] in sorted array 'aux' int j = Arrays.binarySearch(aux,arr[i]); // if abs(i-j) > k, then that element is // not at-most k distance away from its // target position. Thus, 'arr' is not a // k sorted array if (Math.abs(i - j) > k) return "No"; } // 'arr' is a k sorted array return "Yes"; } // Driver method public static void main(String args[]) { int arr[] = {3, 2, 1, 5, 6, 4}; int k = 2; System.out.println("Is it a k sorted array ?: " + isKSortedArray(arr, arr.length, k)); }} # Python 3 implementation to check# whether the given array is a k# sorted array or not # function to find index of element# 'x' in sorted 'arr' uses binary# search techniquedef binarySearch(arr, low, high, x): while (low <= high): mid = int((low + high) / 2) if (arr[mid] == x): return mid elif(arr[mid] > x): high = mid - 1 else: low = mid + 1 # function to check whether the given# array is a 'k' sorted array or notdef isKSortedArray(arr, n, k): # auxiliary array 'aux' aux = [0 for i in range(n)] # copy elements of 'arr' to 'aux' for i in range(0, n, 1): aux[i] = arr[i] # sort 'aux' aux.sort(reverse = False) # for every element of 'arr' at # index 'i', find its index 'j' in 'aux' for i in range(0, n, 1): # index of arr[i] in sorted # array 'aux' j = binarySearch(aux, 0, n - 1, arr[i]) # if abs(i-j) > k, then that element is # not at-most k distance away from its # target position. Thus, 'arr' is not a # k sorted array if (abs(i - j) > k): return "No" # 'arr' is a k sorted array return "Yes" # Driver Codeif __name__ == '__main__': arr = [3, 2, 1, 5, 6, 4] n = len(arr) k = 2 print("Is it a k sorted array?:", isKSortedArray(arr, n, k)) # This code is contributed by# Shashank_Sharma // C# implementation to check// whether the given array is a// k sorted array or notusing System;using System.Collections; class GFG { // Method to check whether the given // array is a 'k' sorted array or not static String isKSortedArray(int []arr, int n, int k) { // auxiliary array 'aux' int []aux = new int[n]; // copy elements of 'arr' to 'aux' for (int i = 0; i<n; i++) aux[i] = arr[i]; // sort 'aux' Array.Sort(aux); // for every element of 'arr' at index // 'i', find its index 'j' in 'aux' for (int i = 0; i<n; i++) { // index of arr[i] in sorted array 'aux' int j = Array.BinarySearch(aux,arr[i]); // if abs(i-j) > k, then that element is // not at-most k distance away from its // target position. Thus, 'arr' is not a // k sorted array if (Math.Abs(i - j) > k) return "No"; } // 'arr' is a k sorted array return "Yes"; } // Driver method public static void Main() { int []arr = {3, 2, 1, 5, 6, 4}; int k = 2; Console.WriteLine("Is it a k sorted array ?: " + isKSortedArray(arr, arr.Length, k)); }} // This code is contributed by Sam007 <script> // Javascript implementation to check whether the given array// is a k sorted array or not // function to find index of element 'x' in sorted 'arr'// uses binary search techniquefunction binarySearch(arr, low, high, x){ while (low <= high) { var mid = parseInt((low + high) / 2); if (arr[mid] == x) return mid; else if (arr[mid] > x) high = mid - 1; else low = mid + 1; }} // function to check whether the given array is// a 'k' sorted array or notfunction isKSortedArray(arr, n, k){ // auxiliary array 'aux' var aux = Array(n); // copy elements of 'arr' to 'aux' for (var i = 0; i<n; i++) aux[i] = arr[i]; // sort 'aux' aux.sort((a,b)=> a-b) // for every element of 'arr' at index 'i', // find its index 'j' in 'aux' for (var i = 0; i<n; i++) { // index of arr[i] in sorted array 'aux' var j = binarySearch(aux, 0, n-1, arr[i]); // if abs(i-j) > k, then that element is // not at-most k distance away from its // target position. Thus, 'arr' is not a // k sorted array if (Math.abs(i - j) > k) return "No"; } // 'arr' is a k sorted array return "Yes"; } // Driver program to test abovevar arr = [3, 2, 1, 5, 6, 4];var n = arr.length;var k = 2;document.write( "Is it a k sorted array?: " + isKSortedArray(arr, n, k)); </script> Output: Is it a k sorted array?: Yes Time Complexity: O(nlogn) Auxiliary space: O(n) Another Approach can be to store the corresponding indices of elements into the aux array. Then simply check if abs ( i – aux[i].second ) <= k, return “No” if the condition is not satisfied. It is slightly faster than the approach mentioned above as we don’t have to perform binary search to check the distance from original index, though the “O notation” would remain same. C++ Python3 #include <bits/stdc++.h>using namespace std; string isKSortedArray(int arr[], int n, int k){ // creating an array to store value, index of the original array vector<pair<int, int>> aux; for(int i=0;i<n;i++){ aux.push_back({arr[i], i}); // pushing the elements and index of arr to aux } // sorting the aux array sort(aux.begin(), aux.end()); // for every element, check if the absolute value of (currIndex-originalIndex) <= k // if not, then return "NO" for(auto i=0;i<n;i++){ if(abs(i-aux[i].second)>k) return "No"; } // If all elements satisfy the condition, the loop will terminate and // "Yes" will be returned. return "Yes";} int main() { int arr[] = {3, 2, 1, 5, 6, 4}; // input array int n = sizeof(arr)/sizeof(int); // number of elements in array(arr) int k = 2; // value to check is array is "k" sorted cout<<isKSortedArray(arr, n, k); // prints "Yes" since the input array is k-sorted return 0;} # Python code for the same approachdef isKSortedArray(arr, n, k): # creating an array to store value, index of the original array aux = [] for i in range(n): aux.append([arr[i], i]) # pushing the elements and index of arr to aux # sorting the aux array aux.sort() # for every element, check if the absolute value of (currIndex-originalIndex) <= k # if not, then return "NO" for i in range(n): if(abs(i-aux[i][1])>k): return "No" # If all elements satisfy the condition, the loop will terminate and # "Yes" will be returned. return "Yes" # driver code arr = [3, 2, 1, 5, 6, 4] # input arrayn = len(arr) # number of elements in array(arr)k = 2 # value to check is array is "k" sorted print(isKSortedArray(arr, n, k)) # prints "Yes" since the input array is k-sorted # This code is contributed by shinjanpatra Output: Yes Time Complexity: O(nlogn) Space Complexity: O(n) This article is contributed by Ayush Jauhari and Naman Monga. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Sam007 Shashank_Sharma rutvik_56 naman_monga Binary Search Arrays Sorting Arrays Sorting Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Next Greater Element Window Sliding Technique Count pairs with given sum Program to find sum of elements in a given array Reversal algorithm for array rotation
[ { "code": null, "e": 24429, "s": 24401, "text": "\n21 Apr, 2022" }, { "code": null, "e": 24780, "s": 24429, "text": "Given an array of n distinct elements. Check whether the given array is a k sorted array or not. A k sorted array is an array where each element is at most k distances away from its target position in the sorted array. For example, let us consider k is 2, an element at index 7 in the sorted array, can be at indexes 5, 6, 7, 8, 9 in the given array." }, { "code": null, "e": 24791, "s": 24780, "text": "Examples: " }, { "code": null, "e": 25079, "s": 24791, "text": "Input : arr[] = {3, 2, 1, 5, 6, 4}, k = 2\nOutput : Yes\nEvery element is at most 2 distance away\nfrom its target position in the sorted array.\n\nInput : arr[] = {13, 8, 10, 7, 15, 14, 12}, k = 3\nOutput : No\n13 is more than k = 3 distance away\nfrom its target position in the sorted array. " }, { "code": null, "e": 25383, "s": 25079, "text": "Copy elements of the original array arr[] to an auxiliary array aux[]. Sort aux[]. Now, for each element at index i in arr[], find its index j in aux[] using Binary Search. If for any element k < abs(i-j), then arr[] is not a k sorted array. Else it is a k sorted array. Here abs are the absolute value." }, { "code": null, "e": 25387, "s": 25383, "text": "C++" }, { "code": null, "e": 25392, "s": 25387, "text": "Java" }, { "code": null, "e": 25400, "s": 25392, "text": "Python3" }, { "code": null, "e": 25403, "s": 25400, "text": "C#" }, { "code": null, "e": 25414, "s": 25403, "text": "Javascript" }, { "code": "// C++ implementation to check whether the given array// is a k sorted array or not#include <bits / stdc++.h>using namespace std; // function to find index of element 'x' in sorted 'arr'// uses binary search techniqueint binarySearch(int arr[], int low, int high, int x){ while (low <= high) { int mid = (low + high) / 2; if (arr[mid] == x) return mid; else if (arr[mid] > x) high = mid - 1; else low = mid + 1; }} // function to check whether the given array is// a 'k' sorted array or notstring isKSortedArray(int arr[], int n, int k){ // auxiliary array 'aux' int aux[n]; // copy elements of 'arr' to 'aux' for (int i = 0; i<n; i++) aux[i] = arr[i]; // sort 'aux' sort(aux, aux + n); // for every element of 'arr' at index 'i', // find its index 'j' in 'aux' for (int i = 0; i<n; i++) { // index of arr[i] in sorted array 'aux' int j = binarySearch(aux, 0, n-1, arr[i]); // if abs(i-j) > k, then that element is // not at-most k distance away from its // target position. Thus, 'arr' is not a // k sorted array if (abs(i - j) > k) return \"No\"; } // 'arr' is a k sorted array return \"Yes\"; } // Driver program to test aboveint main(){ int arr[] = {3, 2, 1, 5, 6, 4}; int n = sizeof(arr) / sizeof(arr[0]); int k = 2; cout << \"Is it a k sorted array?: \" << isKSortedArray(arr, n, k); return 0; }", "e": 26962, "s": 25414, "text": null }, { "code": "// Java implementation to check whether the given array// is a k sorted array or not import java.util.Arrays; class Test{ // Method to check whether the given array is // a 'k' sorted array or not static String isKSortedArray(int arr[], int n, int k) { // auxiliary array 'aux' int aux[] = new int[n]; // copy elements of 'arr' to 'aux' for (int i = 0; i<n; i++) aux[i] = arr[i]; // sort 'aux' Arrays.sort(aux); // for every element of 'arr' at index 'i', // find its index 'j' in 'aux' for (int i = 0; i<n; i++) { // index of arr[i] in sorted array 'aux' int j = Arrays.binarySearch(aux,arr[i]); // if abs(i-j) > k, then that element is // not at-most k distance away from its // target position. Thus, 'arr' is not a // k sorted array if (Math.abs(i - j) > k) return \"No\"; } // 'arr' is a k sorted array return \"Yes\"; } // Driver method public static void main(String args[]) { int arr[] = {3, 2, 1, 5, 6, 4}; int k = 2; System.out.println(\"Is it a k sorted array ?: \" + isKSortedArray(arr, arr.length, k)); }}", "e": 28315, "s": 26962, "text": null }, { "code": "# Python 3 implementation to check# whether the given array is a k# sorted array or not # function to find index of element# 'x' in sorted 'arr' uses binary# search techniquedef binarySearch(arr, low, high, x): while (low <= high): mid = int((low + high) / 2) if (arr[mid] == x): return mid elif(arr[mid] > x): high = mid - 1 else: low = mid + 1 # function to check whether the given# array is a 'k' sorted array or notdef isKSortedArray(arr, n, k): # auxiliary array 'aux' aux = [0 for i in range(n)] # copy elements of 'arr' to 'aux' for i in range(0, n, 1): aux[i] = arr[i] # sort 'aux' aux.sort(reverse = False) # for every element of 'arr' at # index 'i', find its index 'j' in 'aux' for i in range(0, n, 1): # index of arr[i] in sorted # array 'aux' j = binarySearch(aux, 0, n - 1, arr[i]) # if abs(i-j) > k, then that element is # not at-most k distance away from its # target position. Thus, 'arr' is not a # k sorted array if (abs(i - j) > k): return \"No\" # 'arr' is a k sorted array return \"Yes\" # Driver Codeif __name__ == '__main__': arr = [3, 2, 1, 5, 6, 4] n = len(arr) k = 2 print(\"Is it a k sorted array?:\", isKSortedArray(arr, n, k)) # This code is contributed by# Shashank_Sharma", "e": 29758, "s": 28315, "text": null }, { "code": "// C# implementation to check// whether the given array is a// k sorted array or notusing System;using System.Collections; class GFG { // Method to check whether the given // array is a 'k' sorted array or not static String isKSortedArray(int []arr, int n, int k) { // auxiliary array 'aux' int []aux = new int[n]; // copy elements of 'arr' to 'aux' for (int i = 0; i<n; i++) aux[i] = arr[i]; // sort 'aux' Array.Sort(aux); // for every element of 'arr' at index // 'i', find its index 'j' in 'aux' for (int i = 0; i<n; i++) { // index of arr[i] in sorted array 'aux' int j = Array.BinarySearch(aux,arr[i]); // if abs(i-j) > k, then that element is // not at-most k distance away from its // target position. Thus, 'arr' is not a // k sorted array if (Math.Abs(i - j) > k) return \"No\"; } // 'arr' is a k sorted array return \"Yes\"; } // Driver method public static void Main() { int []arr = {3, 2, 1, 5, 6, 4}; int k = 2; Console.WriteLine(\"Is it a k sorted array ?: \" + isKSortedArray(arr, arr.Length, k)); }} // This code is contributed by Sam007", "e": 31138, "s": 29758, "text": null }, { "code": "<script> // Javascript implementation to check whether the given array// is a k sorted array or not // function to find index of element 'x' in sorted 'arr'// uses binary search techniquefunction binarySearch(arr, low, high, x){ while (low <= high) { var mid = parseInt((low + high) / 2); if (arr[mid] == x) return mid; else if (arr[mid] > x) high = mid - 1; else low = mid + 1; }} // function to check whether the given array is// a 'k' sorted array or notfunction isKSortedArray(arr, n, k){ // auxiliary array 'aux' var aux = Array(n); // copy elements of 'arr' to 'aux' for (var i = 0; i<n; i++) aux[i] = arr[i]; // sort 'aux' aux.sort((a,b)=> a-b) // for every element of 'arr' at index 'i', // find its index 'j' in 'aux' for (var i = 0; i<n; i++) { // index of arr[i] in sorted array 'aux' var j = binarySearch(aux, 0, n-1, arr[i]); // if abs(i-j) > k, then that element is // not at-most k distance away from its // target position. Thus, 'arr' is not a // k sorted array if (Math.abs(i - j) > k) return \"No\"; } // 'arr' is a k sorted array return \"Yes\"; } // Driver program to test abovevar arr = [3, 2, 1, 5, 6, 4];var n = arr.length;var k = 2;document.write( \"Is it a k sorted array?: \" + isKSortedArray(arr, n, k)); </script>", "e": 32604, "s": 31138, "text": null }, { "code": null, "e": 32613, "s": 32604, "text": "Output: " }, { "code": null, "e": 32642, "s": 32613, "text": "Is it a k sorted array?: Yes" }, { "code": null, "e": 32690, "s": 32642, "text": "Time Complexity: O(nlogn) Auxiliary space: O(n)" }, { "code": null, "e": 33066, "s": 32690, "text": "Another Approach can be to store the corresponding indices of elements into the aux array. Then simply check if abs ( i – aux[i].second ) <= k, return “No” if the condition is not satisfied. It is slightly faster than the approach mentioned above as we don’t have to perform binary search to check the distance from original index, though the “O notation” would remain same." }, { "code": null, "e": 33070, "s": 33066, "text": "C++" }, { "code": null, "e": 33078, "s": 33070, "text": "Python3" }, { "code": "#include <bits/stdc++.h>using namespace std; string isKSortedArray(int arr[], int n, int k){ // creating an array to store value, index of the original array vector<pair<int, int>> aux; for(int i=0;i<n;i++){ aux.push_back({arr[i], i}); // pushing the elements and index of arr to aux } // sorting the aux array sort(aux.begin(), aux.end()); // for every element, check if the absolute value of (currIndex-originalIndex) <= k // if not, then return \"NO\" for(auto i=0;i<n;i++){ if(abs(i-aux[i].second)>k) return \"No\"; } // If all elements satisfy the condition, the loop will terminate and // \"Yes\" will be returned. return \"Yes\";} int main() { int arr[] = {3, 2, 1, 5, 6, 4}; // input array int n = sizeof(arr)/sizeof(int); // number of elements in array(arr) int k = 2; // value to check is array is \"k\" sorted cout<<isKSortedArray(arr, n, k); // prints \"Yes\" since the input array is k-sorted return 0;}", "e": 34048, "s": 33078, "text": null }, { "code": "# Python code for the same approachdef isKSortedArray(arr, n, k): # creating an array to store value, index of the original array aux = [] for i in range(n): aux.append([arr[i], i]) # pushing the elements and index of arr to aux # sorting the aux array aux.sort() # for every element, check if the absolute value of (currIndex-originalIndex) <= k # if not, then return \"NO\" for i in range(n): if(abs(i-aux[i][1])>k): return \"No\" # If all elements satisfy the condition, the loop will terminate and # \"Yes\" will be returned. return \"Yes\" # driver code arr = [3, 2, 1, 5, 6, 4] # input arrayn = len(arr) # number of elements in array(arr)k = 2 # value to check is array is \"k\" sorted print(isKSortedArray(arr, n, k)) # prints \"Yes\" since the input array is k-sorted # This code is contributed by shinjanpatra", "e": 34918, "s": 34048, "text": null }, { "code": null, "e": 34926, "s": 34918, "text": "Output:" }, { "code": null, "e": 34930, "s": 34926, "text": "Yes" }, { "code": null, "e": 34956, "s": 34930, "text": "Time Complexity: O(nlogn)" }, { "code": null, "e": 34979, "s": 34956, "text": "Space Complexity: O(n)" }, { "code": null, "e": 35417, "s": 34979, "text": "This article is contributed by Ayush Jauhari and Naman Monga. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 35424, "s": 35417, "text": "Sam007" }, { "code": null, "e": 35440, "s": 35424, "text": "Shashank_Sharma" }, { "code": null, "e": 35450, "s": 35440, "text": "rutvik_56" }, { "code": null, "e": 35462, "s": 35450, "text": "naman_monga" }, { "code": null, "e": 35476, "s": 35462, "text": "Binary Search" }, { "code": null, "e": 35483, "s": 35476, "text": "Arrays" }, { "code": null, "e": 35491, "s": 35483, "text": "Sorting" }, { "code": null, "e": 35498, "s": 35491, "text": "Arrays" }, { "code": null, "e": 35506, "s": 35498, "text": "Sorting" }, { "code": null, "e": 35520, "s": 35506, "text": "Binary Search" }, { "code": null, "e": 35618, "s": 35520, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35627, "s": 35618, "text": "Comments" }, { "code": null, "e": 35640, "s": 35627, "text": "Old Comments" }, { "code": null, "e": 35661, "s": 35640, "text": "Next Greater Element" }, { "code": null, "e": 35686, "s": 35661, "text": "Window Sliding Technique" }, { "code": null, "e": 35713, "s": 35686, "text": "Count pairs with given sum" }, { "code": null, "e": 35762, "s": 35713, "text": "Program to find sum of elements in a given array" } ]
Creating child process using fork() in Python - GeeksforGeeks
12 Dec, 2017 Create a child process and display process id of both parent and child process. Fork system call use for creates a new process, which is called child process, which runs concurrently with process (which process called system call fork) and this process is called parent process. After a new child process created, both processes will execute the next instruction following the fork() system call. Library used :os : The OS module in Python provides a way of using operating system dependent functionality. The functions that the OS module provides allows you to interface with the underlying operating system that Python is running on; be that Windows, Mac or Linux. It can be imported as – import os fork() : fork() is an operation whereby a process creates a copy of itself. It is usually a system call, implemented in the kernel. getpid() : getpid() returns the process ID (PID) of the calling process.Below is Python program implementing above :# Python code to create child process import os def parent_child(): n = os.fork() # n greater than 0 means parent process if n > 0: print("Parent process and id is : ", os.getpid()) # n equals to 0 means child process else: print("Child process and id is : ", os.getpid()) # Driver codeparent_child()Output :Child process and id is : 32523 Parent process and id is : 32524 Note : Output can vary time to time, machine to machine or process to process.My Personal Notes arrow_drop_upSave Below is Python program implementing above : # Python code to create child process import os def parent_child(): n = os.fork() # n greater than 0 means parent process if n > 0: print("Parent process and id is : ", os.getpid()) # n equals to 0 means child process else: print("Child process and id is : ", os.getpid()) # Driver codeparent_child() Output : Child process and id is : 32523 Parent process and id is : 32524 Note : Output can vary time to time, machine to machine or process to process. Python-Library system-programming Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Reading and Writing to text files in Python sum() function in Python Create a Pandas DataFrame from Lists How to drop one or multiple columns in Pandas Dataframe *args and **kwargs in Python
[ { "code": null, "e": 23983, "s": 23955, "text": "\n12 Dec, 2017" }, { "code": null, "e": 24063, "s": 23983, "text": "Create a child process and display process id of both parent and child process." }, { "code": null, "e": 24380, "s": 24063, "text": "Fork system call use for creates a new process, which is called child process, which runs concurrently with process (which process called system call fork) and this process is called parent process. After a new child process created, both processes will execute the next instruction following the fork() system call." }, { "code": null, "e": 24674, "s": 24380, "text": "Library used :os : The OS module in Python provides a way of using operating system dependent functionality. The functions that the OS module provides allows you to interface with the underlying operating system that Python is running on; be that Windows, Mac or Linux. It can be imported as –" }, { "code": null, "e": 24685, "s": 24674, "text": "import os\n" }, { "code": null, "e": 24817, "s": 24685, "text": "fork() : fork() is an operation whereby a process creates a copy of itself. It is usually a system call, implemented in the kernel." }, { "code": null, "e": 25466, "s": 24817, "text": "getpid() : getpid() returns the process ID (PID) of the calling process.Below is Python program implementing above :# Python code to create child process import os def parent_child(): n = os.fork() # n greater than 0 means parent process if n > 0: print(\"Parent process and id is : \", os.getpid()) # n equals to 0 means child process else: print(\"Child process and id is : \", os.getpid()) # Driver codeparent_child()Output :Child process and id is : 32523\nParent process and id is : 32524\nNote : Output can vary time to time, machine to machine or process to process.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 25511, "s": 25466, "text": "Below is Python program implementing above :" }, { "code": "# Python code to create child process import os def parent_child(): n = os.fork() # n greater than 0 means parent process if n > 0: print(\"Parent process and id is : \", os.getpid()) # n equals to 0 means child process else: print(\"Child process and id is : \", os.getpid()) # Driver codeparent_child()", "e": 25856, "s": 25511, "text": null }, { "code": null, "e": 25865, "s": 25856, "text": "Output :" }, { "code": null, "e": 25933, "s": 25865, "text": "Child process and id is : 32523\nParent process and id is : 32524\n" }, { "code": null, "e": 26012, "s": 25933, "text": "Note : Output can vary time to time, machine to machine or process to process." }, { "code": null, "e": 26027, "s": 26012, "text": "Python-Library" }, { "code": null, "e": 26046, "s": 26027, "text": "system-programming" }, { "code": null, "e": 26053, "s": 26046, "text": "Python" }, { "code": null, "e": 26151, "s": 26053, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26160, "s": 26151, "text": "Comments" }, { "code": null, "e": 26173, "s": 26160, "text": "Old Comments" }, { "code": null, "e": 26191, "s": 26173, "text": "Python Dictionary" }, { "code": null, "e": 26213, "s": 26191, "text": "Enumerate() in Python" }, { "code": null, "e": 26245, "s": 26213, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26287, "s": 26245, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26313, "s": 26287, "text": "Python String | replace()" }, { "code": null, "e": 26357, "s": 26313, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 26382, "s": 26357, "text": "sum() function in Python" }, { "code": null, "e": 26419, "s": 26382, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 26475, "s": 26419, "text": "How to drop one or multiple columns in Pandas Dataframe" } ]
How to UNPIVOT results in Oracle?
Problem: You want to UNPIVOT results in Oracle. Solution The UNPIVOT clause is new for Oracle Database 11g and enables you to flip the columns into rows in the output from a query, and, at the same time,allow you to run an aggregation function on the data. Consider a table called customer which has below data stored inside. SELECT * FROM customers; SELECT * FROM customers; 1 tammy.bryant@internalmail Tammy Bryant 2 roy.white@internalmail Roy White 3 gary.jenkins@internalmail Gary Jenkins 4 victor.morris@internalmail Victor Morris 5 beverly.hughes@internalmail Beverly Hughes 1 tammy.bryant@internalmail Tammy Bryant 2 roy.white@internalmail Roy White 3 gary.jenkins@internalmail Gary Jenkins 4 victor.morris@internalmail Victor Morris 5 beverly.hughes@internalmail Beverly Hughes In the customer table we can see that full name has First name and last name , now lets seperate the First Name and Last Name into different columns. SELECT full_name, SUBSTR(full_name,1,INSTR(full_name,' ',1,1)-1) first_name, SUBSTR(full_name,INSTR(full_name,' ',-1) + 1) last_name FROM customers; SELECT full_name, SUBSTR(full_name,1,INSTR(full_name,' ',1,1)-1) first_name, SUBSTR(full_name,INSTR(full_name,' ',-1) + 1) last_name FROM customers; Tammy Bryant Tammy Bryant Roy White Roy White Gary Jenkins Gary Jenkins Victor Morris Victor Morris Beverly Hughes Beverly Hughes Evelyn Torres Evelyn Torres Tammy Bryant Tammy Bryant Roy White Roy White Gary Jenkins Gary Jenkins Victor Morris Victor Morris Beverly Hughes Beverly Hughes Evelyn Torres Evelyn Torres Now if we want these first name and last name columns to be coverted into a one single column , we can use UNPIVOT function of oracle. SELECT DISTINCT new_column FROM ( SELECT full_name, SUBSTR(full_name,1,INSTR(full_name,' ',1,1)-1) first_name, SUBSTR(full_name,INSTR(full_name,' ',-1) + 1) last_name FROM customers ) UNPIVOT (new_column FOR ref_col2 IN (first_name,last_name)); SELECT DISTINCT new_column FROM ( SELECT full_name, SUBSTR(full_name,1,INSTR(full_name,' ',1,1)-1) first_name, SUBSTR(full_name,INSTR(full_name,' ',-1) + 1) last_name FROM customers ) UNPIVOT (new_column FOR ref_col2 IN (first_name,last_name)); Roy Beverly Carl Sanchez Evans Martinez Dennis Brown Deborah Carolyn Bennett Jack Roy Beverly Carl Sanchez Evans Martinez Dennis Brown Deborah Carolyn Bennett Jack create table customers ( customer_id integer generated by default on null as identity, email_address varchar2(255 char) not null, full_name varchar2(255 char) not null) ; insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (1,'tammy.bryant@internalmail','Tammy Bryant'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (2,'roy.white@internalmail','Roy White'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (3,'gary.jenkins@internalmail','Gary Jenkins'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (4,'victor.morris@internalmail','Victor Morris'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (5,'beverly.hughes@internalmail','Beverly Hughes'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (6,'evelyn.torres@internalmail','Evelyn Torres'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (7,'carl.lee@internalmail','Carl Lee'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (8,'douglas.flores@internalmail','Douglas Flores'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (9,'norma.robinson@internalmail','Norma Robinson'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (10,'gregory.sanchez@internalmail','Gregory Sanchez'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (11,'judy.evans@internalmail','Judy Evans'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (12,'jean.patterson@internalmail','Jean Patterson'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (13,'michelle.ramirez@internalmail','Michelle Ramirez'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (14,'elizabeth.martinez@internalmail','Elizabeth Martinez'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (15,'walter.rogers@internalmail','Walter Rogers'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (16,'ralph.foster@internalmail','Ralph Foster'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (17,'tina.simmons@internalmail','Tina Simmons'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (18,'peter.jones@internalmail','Peter Jones'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (19,'kathryn.rogers@internalmail','Kathryn Rogers'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (20,'dennis.lopez@internalmail','Dennis Lopez'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (21,'martha.baker@internalmail','Martha Baker'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (22,'raymond.bailey@internalmail','Raymond Bailey'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (23,'christopher.allen@internalmail','Christopher Allen'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (24,'jonathan.coleman@internalmail','Jonathan Coleman'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (25,'walter.turner@internalmail','Walter Turner'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (26,'anna.murphy@internalmail','Anna Murphy'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (27,'carol.alexander@internalmail','Carol Alexander'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (28,'teresa.brown@internalmail','Teresa Brown'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (29,'beverly.rivera@internalmail','Beverly Rivera'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (30,'lisa.hughes@internalmail','Lisa Hughes'); COMMIT; create table customers ( customer_id integer generated by default on null as identity, email_address varchar2(255 char) not null, full_name varchar2(255 char) not null) ; insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (1,'tammy.bryant@internalmail','Tammy Bryant'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (2,'roy.white@internalmail','Roy White'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (3,'gary.jenkins@internalmail','Gary Jenkins'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (4,'victor.morris@internalmail','Victor Morris'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (5,'beverly.hughes@internalmail','Beverly Hughes'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (6,'evelyn.torres@internalmail','Evelyn Torres'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (7,'carl.lee@internalmail','Carl Lee'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (8,'douglas.flores@internalmail','Douglas Flores'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (9,'norma.robinson@internalmail','Norma Robinson'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (10,'gregory.sanchez@internalmail','Gregory Sanchez'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (11,'judy.evans@internalmail','Judy Evans'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (12,'jean.patterson@internalmail','Jean Patterson'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (13,'michelle.ramirez@internalmail','Michelle Ramirez'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (14,'elizabeth.martinez@internalmail','Elizabeth Martinez'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (15,'walter.rogers@internalmail','Walter Rogers'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (16,'ralph.foster@internalmail','Ralph Foster'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (17,'tina.simmons@internalmail','Tina Simmons'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (18,'peter.jones@internalmail','Peter Jones'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (19,'kathryn.rogers@internalmail','Kathryn Rogers'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (20,'dennis.lopez@internalmail','Dennis Lopez'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (21,'martha.baker@internalmail','Martha Baker'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (22,'raymond.bailey@internalmail','Raymond Bailey'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (23,'christopher.allen@internalmail','Christopher Allen'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (24,'jonathan.coleman@internalmail','Jonathan Coleman'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (25,'walter.turner@internalmail','Walter Turner'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (26,'anna.murphy@internalmail','Anna Murphy'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (27,'carol.alexander@internalmail','Carol Alexander'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (28,'teresa.brown@internalmail','Teresa Brown'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (29,'beverly.rivera@internalmail','Beverly Rivera'); insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (30,'lisa.hughes@internalmail','Lisa Hughes'); COMMIT;
[ { "code": null, "e": 1071, "s": 1062, "text": "Problem:" }, { "code": null, "e": 1110, "s": 1071, "text": "You want to UNPIVOT results in Oracle." }, { "code": null, "e": 1119, "s": 1110, "text": "Solution" }, { "code": null, "e": 1319, "s": 1119, "text": "The UNPIVOT clause is new for Oracle Database 11g and enables you to flip the columns into rows in the output from a query, and, at the same time,allow you to run an aggregation function on the data." }, { "code": null, "e": 1388, "s": 1319, "text": "Consider a table called customer which has below data stored inside." }, { "code": null, "e": 1413, "s": 1388, "text": "SELECT * FROM customers;" }, { "code": null, "e": 1438, "s": 1413, "text": "SELECT * FROM customers;" }, { "code": null, "e": 1663, "s": 1438, "text": "1 tammy.bryant@internalmail Tammy Bryant\n2 roy.white@internalmail Roy White\n3 gary.jenkins@internalmail Gary Jenkins\n4 victor.morris@internalmail Victor Morris\n5 beverly.hughes@internalmail Beverly Hughes" }, { "code": null, "e": 1888, "s": 1663, "text": "1 tammy.bryant@internalmail Tammy Bryant\n2 roy.white@internalmail Roy White\n3 gary.jenkins@internalmail Gary Jenkins\n4 victor.morris@internalmail Victor Morris\n5 beverly.hughes@internalmail Beverly Hughes" }, { "code": null, "e": 2038, "s": 1888, "text": "In the customer table we can see that full name has First name and last name , now lets seperate the First Name and Last Name into different columns." }, { "code": null, "e": 2192, "s": 2038, "text": "SELECT full_name,\n SUBSTR(full_name,1,INSTR(full_name,' ',1,1)-1) first_name,\n SUBSTR(full_name,INSTR(full_name,' ',-1) + 1) last_name\n FROM customers;" }, { "code": null, "e": 2346, "s": 2192, "text": "SELECT full_name,\n SUBSTR(full_name,1,INSTR(full_name,' ',1,1)-1) first_name,\n SUBSTR(full_name,INSTR(full_name,' ',-1) + 1) last_name\n FROM customers;" }, { "code": null, "e": 2524, "s": 2346, "text": "Tammy Bryant Tammy Bryant\nRoy White Roy White\nGary Jenkins Gary Jenkins\nVictor Morris Victor Morris\nBeverly Hughes Beverly Hughes\nEvelyn Torres Evelyn Torres" }, { "code": null, "e": 2702, "s": 2524, "text": "Tammy Bryant Tammy Bryant\nRoy White Roy White\nGary Jenkins Gary Jenkins\nVictor Morris Victor Morris\nBeverly Hughes Beverly Hughes\nEvelyn Torres Evelyn Torres" }, { "code": null, "e": 2837, "s": 2702, "text": "Now if we want these first name and last name columns to be coverted into a one single column , we can use UNPIVOT function of oracle." }, { "code": null, "e": 3099, "s": 2837, "text": "SELECT DISTINCT new_column FROM\n(\nSELECT full_name,\n SUBSTR(full_name,1,INSTR(full_name,' ',1,1)-1) first_name,\n SUBSTR(full_name,INSTR(full_name,' ',-1) + 1) last_name\n FROM customers\n )\nUNPIVOT\n (new_column FOR ref_col2 IN (first_name,last_name));" }, { "code": null, "e": 3361, "s": 3099, "text": "SELECT DISTINCT new_column FROM\n(\nSELECT full_name,\n SUBSTR(full_name,1,INSTR(full_name,' ',1,1)-1) first_name,\n SUBSTR(full_name,INSTR(full_name,' ',-1) + 1) last_name\n FROM customers\n )\nUNPIVOT\n (new_column FOR ref_col2 IN (first_name,last_name));" }, { "code": null, "e": 3443, "s": 3361, "text": "Roy\nBeverly\nCarl\nSanchez\nEvans\nMartinez\nDennis\nBrown\nDeborah\nCarolyn\nBennett\nJack" }, { "code": null, "e": 3525, "s": 3443, "text": "Roy\nBeverly\nCarl\nSanchez\nEvans\nMartinez\nDennis\nBrown\nDeborah\nCarolyn\nBennett\nJack" }, { "code": null, "e": 7320, "s": 3525, "text": "create table customers (\n customer_id integer generated by default on null as identity,\n email_address varchar2(255 char) not null,\n full_name varchar2(255 char) not null)\n ;\n\n\ninsert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (1,'tammy.bryant@internalmail','Tammy Bryant');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (2,'roy.white@internalmail','Roy White');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (3,'gary.jenkins@internalmail','Gary Jenkins');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (4,'victor.morris@internalmail','Victor Morris');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (5,'beverly.hughes@internalmail','Beverly Hughes');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (6,'evelyn.torres@internalmail','Evelyn Torres');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (7,'carl.lee@internalmail','Carl Lee');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (8,'douglas.flores@internalmail','Douglas Flores');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (9,'norma.robinson@internalmail','Norma Robinson');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (10,'gregory.sanchez@internalmail','Gregory Sanchez');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (11,'judy.evans@internalmail','Judy Evans');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (12,'jean.patterson@internalmail','Jean Patterson');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (13,'michelle.ramirez@internalmail','Michelle Ramirez');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (14,'elizabeth.martinez@internalmail','Elizabeth Martinez');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (15,'walter.rogers@internalmail','Walter Rogers');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (16,'ralph.foster@internalmail','Ralph Foster');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (17,'tina.simmons@internalmail','Tina Simmons');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (18,'peter.jones@internalmail','Peter Jones');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (19,'kathryn.rogers@internalmail','Kathryn Rogers');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (20,'dennis.lopez@internalmail','Dennis Lopez');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (21,'martha.baker@internalmail','Martha Baker');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (22,'raymond.bailey@internalmail','Raymond Bailey');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (23,'christopher.allen@internalmail','Christopher Allen');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (24,'jonathan.coleman@internalmail','Jonathan Coleman');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (25,'walter.turner@internalmail','Walter Turner');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (26,'anna.murphy@internalmail','Anna Murphy');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (27,'carol.alexander@internalmail','Carol Alexander');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (28,'teresa.brown@internalmail','Teresa Brown');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (29,'beverly.rivera@internalmail','Beverly Rivera');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (30,'lisa.hughes@internalmail','Lisa Hughes');\n\nCOMMIT;" }, { "code": null, "e": 11115, "s": 7320, "text": "create table customers (\n customer_id integer generated by default on null as identity,\n email_address varchar2(255 char) not null,\n full_name varchar2(255 char) not null)\n ;\n\n\ninsert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (1,'tammy.bryant@internalmail','Tammy Bryant');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (2,'roy.white@internalmail','Roy White');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (3,'gary.jenkins@internalmail','Gary Jenkins');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (4,'victor.morris@internalmail','Victor Morris');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (5,'beverly.hughes@internalmail','Beverly Hughes');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (6,'evelyn.torres@internalmail','Evelyn Torres');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (7,'carl.lee@internalmail','Carl Lee');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (8,'douglas.flores@internalmail','Douglas Flores');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (9,'norma.robinson@internalmail','Norma Robinson');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (10,'gregory.sanchez@internalmail','Gregory Sanchez');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (11,'judy.evans@internalmail','Judy Evans');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (12,'jean.patterson@internalmail','Jean Patterson');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (13,'michelle.ramirez@internalmail','Michelle Ramirez');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (14,'elizabeth.martinez@internalmail','Elizabeth Martinez');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (15,'walter.rogers@internalmail','Walter Rogers');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (16,'ralph.foster@internalmail','Ralph Foster');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (17,'tina.simmons@internalmail','Tina Simmons');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (18,'peter.jones@internalmail','Peter Jones');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (19,'kathryn.rogers@internalmail','Kathryn Rogers');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (20,'dennis.lopez@internalmail','Dennis Lopez');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (21,'martha.baker@internalmail','Martha Baker');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (22,'raymond.bailey@internalmail','Raymond Bailey');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (23,'christopher.allen@internalmail','Christopher Allen');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (24,'jonathan.coleman@internalmail','Jonathan Coleman');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (25,'walter.turner@internalmail','Walter Turner');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (26,'anna.murphy@internalmail','Anna Murphy');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (27,'carol.alexander@internalmail','Carol Alexander');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (28,'teresa.brown@internalmail','Teresa Brown');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (29,'beverly.rivera@internalmail','Beverly Rivera');\n insert into customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (30,'lisa.hughes@internalmail','Lisa Hughes');\n\nCOMMIT;" } ]
React Render HTML
React's goal is in many ways to render HTML in a web page. React renders HTML to the web page by using a function called ReactDOM.render(). The ReactDOM.render() function takes two arguments, HTML code and an HTML element. The purpose of the function is to display the specified HTML code inside the specified HTML element. But render where? There is another folder in the root directory of your React project, named "public". In this folder, there is an index.html file. You'll notice a single <div> in the body of this file. This is where our React application will be rendered. Display a paragraph inside an element with the id of "root": ReactDOM.render(<p>Hello</p>, document.getElementById('root')); The result is displayed in the <div id="root"> element: <body> <div id="root"></div> </body> Run Example » Note that the element id does not have to be called "root", but this is the standard convention. The HTML code in this tutorial uses JSX which allows you to write HTML tags inside the JavaScript code: Do not worry if the syntax is unfamiliar, you will learn more about JSX in the next chapter. Create a variable that contains HTML code and display it in the "root" node: const myelement = ( <table> <tr> <th>Name</th> </tr> <tr> <td>John</td> </tr> <tr> <td>Elsa</td> </tr> </table> ); ReactDOM.render(myelement, document.getElementById('root')); Run Example » The root node is the HTML element where you want to display the result. It is like a container for content managed by React. It does NOT have to be a <div> element and it does NOT have to have the id='root': The root node can be called whatever you like: <body> <header id="sandy"></header> </body> Display the result in the <header id="sandy"> element: ReactDOM.render(<p>Hallo</p>, document.getElementById('sandy')); Run Example » We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 59, "s": 0, "text": "React's goal is in many ways to render HTML in a web page." }, { "code": null, "e": 141, "s": 59, "text": "React renders HTML to the web page by using a function called \nReactDOM.render()." }, { "code": null, "e": 225, "s": 141, "text": "The ReactDOM.render() function takes two \narguments, HTML code and an HTML element." }, { "code": null, "e": 327, "s": 225, "text": "The purpose of the function is to display the specified HTML code inside the \nspecified HTML element." }, { "code": null, "e": 345, "s": 327, "text": "But render where?" }, { "code": null, "e": 475, "s": 345, "text": "There is another folder in the root directory of your React project, named \"public\".\nIn this folder, there is an index.html file." }, { "code": null, "e": 584, "s": 475, "text": "You'll notice a single <div>\nin the body of this file. This is where our React application will be rendered." }, { "code": null, "e": 645, "s": 584, "text": "Display a paragraph inside an element with the id of \"root\":" }, { "code": null, "e": 709, "s": 645, "text": "ReactDOM.render(<p>Hello</p>, document.getElementById('root'));" }, { "code": null, "e": 765, "s": 709, "text": "The result is displayed in the <div id=\"root\"> element:" }, { "code": null, "e": 805, "s": 765, "text": "<body>\n <div id=\"root\"></div>\n</body>\n" }, { "code": null, "e": 822, "s": 805, "text": "\nRun \nExample »\n" }, { "code": null, "e": 919, "s": 822, "text": "Note that the element id does not have to be called \"root\", but this is the standard convention." }, { "code": null, "e": 1024, "s": 919, "text": "The HTML code in this tutorial uses JSX which allows you to write HTML tags \ninside the JavaScript code:" }, { "code": null, "e": 1117, "s": 1024, "text": "Do not worry if the syntax is unfamiliar, you will learn more about JSX in the next chapter." }, { "code": null, "e": 1194, "s": 1117, "text": "Create a variable that contains HTML code and display it in the \"root\" node:" }, { "code": null, "e": 1418, "s": 1194, "text": "const myelement = (\n <table>\n <tr>\n <th>Name</th>\n </tr>\n <tr>\n <td>John</td>\n </tr>\n <tr>\n <td>Elsa</td>\n </tr>\n </table>\n);\n\nReactDOM.render(myelement, document.getElementById('root'));\n" }, { "code": null, "e": 1435, "s": 1418, "text": "\nRun \nExample »\n" }, { "code": null, "e": 1507, "s": 1435, "text": "The root node is the HTML element where you want to display the result." }, { "code": null, "e": 1560, "s": 1507, "text": "It is like a container for content managed by React." }, { "code": null, "e": 1645, "s": 1560, "text": "It does NOT have to be a <div> element and it does \nNOT have to \nhave the id='root':" }, { "code": null, "e": 1692, "s": 1645, "text": "The root node can be called whatever you like:" }, { "code": null, "e": 1741, "s": 1692, "text": "<body>\n\n <header id=\"sandy\"></header>\n\n</body>\n" }, { "code": null, "e": 1796, "s": 1741, "text": "Display the result in the <header id=\"sandy\"> element:" }, { "code": null, "e": 1862, "s": 1796, "text": "ReactDOM.render(<p>Hallo</p>, document.getElementById('sandy'));\n" }, { "code": null, "e": 1879, "s": 1862, "text": "\nRun \nExample »\n" }, { "code": null, "e": 1912, "s": 1879, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1954, "s": 1912, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 2061, "s": 1954, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 2080, "s": 2061, "text": "help@w3schools.com" } ]
Perfect Numbers | Practice | GeeksforGeeks
Given a number N, check if a number is perfect or not. A number is said to be perfect if sum of all its factors excluding the number itself is equal to the number. Example 1: Input: N = 6 Output: 1 Explanation: Factors of 6 are 1, 2, 3 and 6. Excluding 6 their sum is 6 which is equal to N itself. So, it's a Perfect Number. Example 2: Input: N = 10 Output: 0 Explanation: Factors of 10 are 1, 2, 5 and 10. Excluding 10 their sum is 8 which is not equal to N itself. So, it's not a Perfect Number. Your Task: You don't need to read input or print anything. Your task is to complete the function isPerfectNumber() which takes an Integer N as input and returns 1 if N is a Perfect number else returns 0. Expected Time Complexity: O(sqrt(N)) Expected Auxiliary Space: O(1) Constraints: 1 <= N <= 1012 0 mayank180919991 week ago int isPerfectNumber(long long N) { int sum=1; if(N==1){ return 0; } for(int i=2;i<=sqrt(N);i++){ if(N%i==0){ sum+=i; sum+=N/i; } } if(sum==N){ return 1; } return 0; } 0 mohdraza2 weeks ago class Solution { static int isPerfectNumber(Long N) { if(ispf(N)){ return 1; } else { return 0; } } static boolean ispf(Long n){ { if (n == 1) return false; long sum = 1; for (long i = 2; i * i <=n ; i++) { if (n % i == 0) { sum += i + (n / i); } } if (sum == n) return true; return false; }}}; 0 mayank20212 months ago C++ 0.3/1.2int isPerfectNumber(long long N) { if (N==1) return 0; int sum=1; for(int i=2; i<=sqrt(N); i++) { if(N%i==0) sum=sum+i+N/i; } if(sum==N) return 1; return 0; } 0 makkarbharat242 months ago Why am I getting run time error for this code? class Solution { static int isPerfectNumber(Long N){ int sum=1; for(int i=2;i<=N/2;i++) { if(N%i==0) {sum+=i;} } return sum==N?1:0; }} +2 arpitkatiyar091972 months ago CORRECT JAVA SOLUTION class Solution { static int isPerfectNumber(Long n) { // code here long sum = 1; // Find all divisors and add them for (int i = 2; i<=Math.sqrt(n); i++) { if (n%i==0) { if(i*i!=n) sum = sum + i + n/i; else sum=sum+i; } } // If sum of divisors is equal to // n, then n is a perfect number if (sum == n && n != 1) return 1; return 0; }}; -2 satendrapal91112 months ago long long sum = 0,i; for( i=1; i<=N/2; i++) { if(N % i == 0 ) { sum = sum + i; } } if(sum == N) { return 1; } else { return 0; } -5 varshakavi20017 months ago long sum=1; for (long i = 2; i * i <= N; i++) { if (N % i==0) { if(i * i != N) sum = sum + i + N / i; else sum = sum + i; } } // If sum of divisors is equal to number // Then number is a perfect number if (sum == N && N != 1) return 1; return 0; 0 Rachana11 months ago Rachana def perfect(n): a=[] d=0 for i in range(1,n): if(n%i==0): a.append(i) for j in range(len(a)): d+=a[j] if(d==n): return 1 return 0 0 Sawi Sharma1 year ago Sawi Sharma Python3 solusann: def isPerfectNumber(self, N): # code here import math if N==1: return 0 self.total=1 for i in range(2,int(math.sqrt(N))+1): if N%i==0 and N!=i: self.total+=i self.total+=int(N/i) if self.total==N: return 1 else: return 0 +2 Rutvik Rana1 year ago Rutvik Rana Correct Solution As I Guess Should Be:- int isPerfectNumber(long long N) { if(N==1)return 0; long long sum = 1; for(long long i=2;i<=sqrt(N);i++){ if(N/i==i){sum+=i;} else if(N%i==0){sum+=(i+(N/i));} } return sum==N; } 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": 402, "s": 238, "text": "Given a number N, check if a number is perfect or not. A number is said to be perfect if sum of all its factors excluding the number itself is equal to the number." }, { "code": null, "e": 415, "s": 404, "text": "Example 1:" }, { "code": null, "e": 566, "s": 415, "text": "Input:\nN = 6\nOutput:\n1 \nExplanation:\nFactors of 6 are 1, 2, 3 and 6.\nExcluding 6 their sum is 6 which\nis equal to N itself. So, it's a\nPerfect Number." }, { "code": null, "e": 577, "s": 566, "text": "Example 2:" }, { "code": null, "e": 739, "s": 577, "text": "Input:\nN = 10\nOutput:\n0\nExplanation:\nFactors of 10 are 1, 2, 5 and 10.\nExcluding 10 their sum is 8 which\nis not equal to N itself. So, it's\nnot a Perfect Number." }, { "code": null, "e": 945, "s": 741, "text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function isPerfectNumber() which takes an Integer N as input and returns 1 if N is a Perfect number else returns 0." }, { "code": null, "e": 1015, "s": 947, "text": "Expected Time Complexity: O(sqrt(N))\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 1045, "s": 1017, "text": "Constraints:\n1 <= N <= 1012" }, { "code": null, "e": 1047, "s": 1045, "text": "0" }, { "code": null, "e": 1072, "s": 1047, "text": "mayank180919991 week ago" }, { "code": null, "e": 1374, "s": 1072, "text": " int isPerfectNumber(long long N) {\n int sum=1;\n if(N==1){\n return 0;\n }\n for(int i=2;i<=sqrt(N);i++){\n if(N%i==0){\n sum+=i;\n sum+=N/i;\n }\n }\n if(sum==N){\n return 1;\n }\n return 0;\n }" }, { "code": null, "e": 1376, "s": 1374, "text": "0" }, { "code": null, "e": 1396, "s": 1376, "text": "mohdraza2 weeks ago" }, { "code": null, "e": 1916, "s": 1396, "text": "class Solution { static int isPerfectNumber(Long N) { if(ispf(N)){ return 1; } else { return 0; } } static boolean ispf(Long n){ { if (n == 1) return false; long sum = 1; for (long i = 2; i * i <=n ; i++) { if (n % i == 0) { sum += i + (n / i); } } if (sum == n) return true; return false; }}};" }, { "code": null, "e": 1918, "s": 1916, "text": "0" }, { "code": null, "e": 1941, "s": 1918, "text": "mayank20212 months ago" }, { "code": null, "e": 2239, "s": 1941, "text": "C++ 0.3/1.2int isPerfectNumber(long long N) { if (N==1) return 0; int sum=1; for(int i=2; i<=sqrt(N); i++) { if(N%i==0) sum=sum+i+N/i; } if(sum==N) return 1; return 0; }" }, { "code": null, "e": 2241, "s": 2239, "text": "0" }, { "code": null, "e": 2268, "s": 2241, "text": "makkarbharat242 months ago" }, { "code": null, "e": 2315, "s": 2268, "text": "Why am I getting run time error for this code?" }, { "code": null, "e": 2370, "s": 2315, "text": "class Solution { static int isPerfectNumber(Long N){" }, { "code": null, "e": 2509, "s": 2370, "text": " int sum=1; for(int i=2;i<=N/2;i++) { if(N%i==0) {sum+=i;} } return sum==N?1:0; }}" }, { "code": null, "e": 2512, "s": 2509, "text": "+2" }, { "code": null, "e": 2542, "s": 2512, "text": "arpitkatiyar091972 months ago" }, { "code": null, "e": 2565, "s": 2542, "text": "CORRECT JAVA SOLUTION " }, { "code": null, "e": 3010, "s": 2567, "text": "class Solution { static int isPerfectNumber(Long n) { // code here long sum = 1; // Find all divisors and add them for (int i = 2; i<=Math.sqrt(n); i++) { if (n%i==0) { if(i*i!=n) sum = sum + i + n/i; else sum=sum+i; } } // If sum of divisors is equal to // n, then n is a perfect number if (sum == n && n != 1) return 1; return 0; }};" }, { "code": null, "e": 3013, "s": 3010, "text": "-2" }, { "code": null, "e": 3041, "s": 3013, "text": "satendrapal91112 months ago" }, { "code": null, "e": 3329, "s": 3041, "text": " long long sum = 0,i; for( i=1; i<=N/2; i++) { if(N % i == 0 ) { sum = sum + i; } } if(sum == N) { return 1; } else { return 0; }" }, { "code": null, "e": 3332, "s": 3329, "text": "-5" }, { "code": null, "e": 3359, "s": 3332, "text": "varshakavi20017 months ago" }, { "code": null, "e": 3711, "s": 3359, "text": "long sum=1; for (long i = 2; i * i <= N; i++) { if (N % i==0) { if(i * i != N) sum = sum + i + N / i; else sum = sum + i; } } // If sum of divisors is equal to number // Then number is a perfect number if (sum == N && N != 1) return 1; return 0;" }, { "code": null, "e": 3713, "s": 3711, "text": "0" }, { "code": null, "e": 3734, "s": 3713, "text": "Rachana11 months ago" }, { "code": null, "e": 3742, "s": 3734, "text": "Rachana" }, { "code": null, "e": 3922, "s": 3742, "text": "def perfect(n): a=[] d=0 for i in range(1,n): if(n%i==0): a.append(i) for j in range(len(a)): d+=a[j] if(d==n): return 1 return 0" }, { "code": null, "e": 3924, "s": 3922, "text": "0" }, { "code": null, "e": 3946, "s": 3924, "text": "Sawi Sharma1 year ago" }, { "code": null, "e": 3958, "s": 3946, "text": "Sawi Sharma" }, { "code": null, "e": 3976, "s": 3958, "text": "Python3 solusann:" }, { "code": null, "e": 4081, "s": 3976, "text": "def isPerfectNumber(self, N): # code here import math if N==1: return 0" }, { "code": null, "e": 4207, "s": 4081, "text": " self.total=1 for i in range(2,int(math.sqrt(N))+1): if N%i==0 and N!=i: self.total+=i self.total+=int(N/i)" }, { "code": null, "e": 4286, "s": 4207, "text": " if self.total==N: return 1 else: return 0" }, { "code": null, "e": 4289, "s": 4286, "text": "+2" }, { "code": null, "e": 4311, "s": 4289, "text": "Rutvik Rana1 year ago" }, { "code": null, "e": 4323, "s": 4311, "text": "Rutvik Rana" }, { "code": null, "e": 4363, "s": 4323, "text": "Correct Solution As I Guess Should Be:-" }, { "code": null, "e": 4606, "s": 4363, "text": " int isPerfectNumber(long long N) { if(N==1)return 0; long long sum = 1; for(long long i=2;i<=sqrt(N);i++){ if(N/i==i){sum+=i;} else if(N%i==0){sum+=(i+(N/i));} } return sum==N; }" }, { "code": null, "e": 4752, "s": 4606, "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": 4788, "s": 4752, "text": " Login to access your submissions. " }, { "code": null, "e": 4798, "s": 4788, "text": "\nProblem\n" }, { "code": null, "e": 4808, "s": 4798, "text": "\nContest\n" }, { "code": null, "e": 4871, "s": 4808, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5019, "s": 4871, "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": 5227, "s": 5019, "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": 5333, "s": 5227, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Access Ethereum Data Using Web3.py, Infura, and The Graph | by Posey | Towards Data Science
Note: full code to this article can be found on GitHub. Previously I shared how to access blockchain data for DeFi projects using various centralized APIs like DeFi Llama and decentralized APIs like The Graph. This time around we’re going to query the blockchain directly using the Web3.py Python library. Why? Web3.py is a Python library built for interacting with the Ethereum blockchain. With it we can build all sorts of core functionality for decentralized applications. We can interact with smart contracts directly, gather blockchain data, and send transactions. If you’re not a Python user, there are libraries for other languages, like the popular web3.js libraries. In our terminal let’s get started by installing our Python library. pip install web3 Web3.py functions by connecting to nodes in the Ethereum network to both retrieve data and broadcast data to the network. Nodes store blockchain data so we can query the state of the Ethereum blockchain to gather the data we need. The data retrieval is an effectively free operation for us, as the only real cost is the storage and computation being performed by the nodes saving that data. With this library we can connect to our own node or an existing node on the network to build what we want. We could spin up a local node on our machine, but the costs to do that are pretty steep; a full node as of 4/21 is about ~7TB of data. Instead of operating our own node any time we want to access data, we’ll cop out and go the sensible route by using a service like Infura. Infura is a Consensys product we will use as our node to connect to the Ethereum blockchain. Many of the top projects are Infura users. Later down the road you can explore if operating your own node or using another service is the right option for your use-case. To get started, find your way over to Infura and create a new project. There you will find a project ID. That project ID will go at the end of your endpoint in this snippet of Web3.py code that will define what node you want to connect to. Now that you’ve got your connection to the network ready to go, how about making some basic queries? That was neat but very basic. How about digging deeper? How about trying to mimic the functionality of a product like Zapper that tracks the $ value of our tokens? First, we’ll need to scan for what tokens our address holds. To do this, we’ll be interacting with smart contracts for the individual tokens. These contracts live at addresses that look like our wallet addresses (externally owned accounts), except these are instead contract addresses. At this address lives smart contract code. Tokens will adhere to the ERC-20 standard that makes our lives easier for interacting with these contracts. An ERC-20 contract will by default have the following functions... balanceOf is the function that allows us to see how many of the tokens are held by the wallet address we query for. We start by defining an ABI. The ABI or application binary interface is a format we define to interact with contracts. It’s what we use to define how data should be encoded/decoded in the EVM. Technical details aside, what’s important is to understand it is the format we define for how we will interact with our desired smart contract. Next we take a series of steps to input the address and return the # of tokens held by the wallet address of our choosing. Our sample address was for Synthetix (SNX), you can input any contract address you like. You can imagine that you could set up a master list of ERC-20 contract addresses and iterate through to find what tokens are held by a specific wallet. We use the Web3 function toChecksumAddress() to make sure our address is in checksum format. We use fromWei() to convert our Wei value to ether. 1 ETH is 1E18 Wei. Finally, we’ll use The Graph to grab some price data. Since we want everything to be on-chain for this use-case, we need to get the value of our desired token in DAI, a stablecoin that stays relatively pegged to USD. We do a pair of queries to The Graph to get the DAI (stablecoin soft pegged to USD) value of SNX. We start by getting the fraction of ETH per SNX and multiply by the number of DAI per ETH to get to a final DAI value per SNX. We can then multiply our final DAI value times the number of SNX our wallet holds to find (roughly) the total USD value of the position. If that sounds confusing, try reading the code and it’ll make a lot more sense. We had to do all these extra steps because there isn’t an active pool in Uniswap for directly exchanging DAI for SNX. So we go from SNX to ETH to DAI. Next time we’ll toss our data in a UI and see how we can query blockchain data in real-time to keep up-to-date with on-chain activity. Let’s continue the conversation on Twitter. Access the full code on GitHub. To support my writing and get full access to all articles on Medium, visit https://posey.medium.com/membership
[ { "code": null, "e": 228, "s": 172, "text": "Note: full code to this article can be found on GitHub." }, { "code": null, "e": 478, "s": 228, "text": "Previously I shared how to access blockchain data for DeFi projects using various centralized APIs like DeFi Llama and decentralized APIs like The Graph. This time around we’re going to query the blockchain directly using the Web3.py Python library." }, { "code": null, "e": 483, "s": 478, "text": "Why?" }, { "code": null, "e": 848, "s": 483, "text": "Web3.py is a Python library built for interacting with the Ethereum blockchain. With it we can build all sorts of core functionality for decentralized applications. We can interact with smart contracts directly, gather blockchain data, and send transactions. If you’re not a Python user, there are libraries for other languages, like the popular web3.js libraries." }, { "code": null, "e": 916, "s": 848, "text": "In our terminal let’s get started by installing our Python library." }, { "code": null, "e": 933, "s": 916, "text": "pip install web3" }, { "code": null, "e": 1324, "s": 933, "text": "Web3.py functions by connecting to nodes in the Ethereum network to both retrieve data and broadcast data to the network. Nodes store blockchain data so we can query the state of the Ethereum blockchain to gather the data we need. The data retrieval is an effectively free operation for us, as the only real cost is the storage and computation being performed by the nodes saving that data." }, { "code": null, "e": 1705, "s": 1324, "text": "With this library we can connect to our own node or an existing node on the network to build what we want. We could spin up a local node on our machine, but the costs to do that are pretty steep; a full node as of 4/21 is about ~7TB of data. Instead of operating our own node any time we want to access data, we’ll cop out and go the sensible route by using a service like Infura." }, { "code": null, "e": 1968, "s": 1705, "text": "Infura is a Consensys product we will use as our node to connect to the Ethereum blockchain. Many of the top projects are Infura users. Later down the road you can explore if operating your own node or using another service is the right option for your use-case." }, { "code": null, "e": 2073, "s": 1968, "text": "To get started, find your way over to Infura and create a new project. There you will find a project ID." }, { "code": null, "e": 2208, "s": 2073, "text": "That project ID will go at the end of your endpoint in this snippet of Web3.py code that will define what node you want to connect to." }, { "code": null, "e": 2309, "s": 2208, "text": "Now that you’ve got your connection to the network ready to go, how about making some basic queries?" }, { "code": null, "e": 2473, "s": 2309, "text": "That was neat but very basic. How about digging deeper? How about trying to mimic the functionality of a product like Zapper that tracks the $ value of our tokens?" }, { "code": null, "e": 2910, "s": 2473, "text": "First, we’ll need to scan for what tokens our address holds. To do this, we’ll be interacting with smart contracts for the individual tokens. These contracts live at addresses that look like our wallet addresses (externally owned accounts), except these are instead contract addresses. At this address lives smart contract code. Tokens will adhere to the ERC-20 standard that makes our lives easier for interacting with these contracts." }, { "code": null, "e": 2977, "s": 2910, "text": "An ERC-20 contract will by default have the following functions..." }, { "code": null, "e": 3093, "s": 2977, "text": "balanceOf is the function that allows us to see how many of the tokens are held by the wallet address we query for." }, { "code": null, "e": 3430, "s": 3093, "text": "We start by defining an ABI. The ABI or application binary interface is a format we define to interact with contracts. It’s what we use to define how data should be encoded/decoded in the EVM. Technical details aside, what’s important is to understand it is the format we define for how we will interact with our desired smart contract." }, { "code": null, "e": 3794, "s": 3430, "text": "Next we take a series of steps to input the address and return the # of tokens held by the wallet address of our choosing. Our sample address was for Synthetix (SNX), you can input any contract address you like. You can imagine that you could set up a master list of ERC-20 contract addresses and iterate through to find what tokens are held by a specific wallet." }, { "code": null, "e": 3958, "s": 3794, "text": "We use the Web3 function toChecksumAddress() to make sure our address is in checksum format. We use fromWei() to convert our Wei value to ether. 1 ETH is 1E18 Wei." }, { "code": null, "e": 4175, "s": 3958, "text": "Finally, we’ll use The Graph to grab some price data. Since we want everything to be on-chain for this use-case, we need to get the value of our desired token in DAI, a stablecoin that stays relatively pegged to USD." }, { "code": null, "e": 4273, "s": 4175, "text": "We do a pair of queries to The Graph to get the DAI (stablecoin soft pegged to USD) value of SNX." }, { "code": null, "e": 4400, "s": 4273, "text": "We start by getting the fraction of ETH per SNX and multiply by the number of DAI per ETH to get to a final DAI value per SNX." }, { "code": null, "e": 4768, "s": 4400, "text": "We can then multiply our final DAI value times the number of SNX our wallet holds to find (roughly) the total USD value of the position. If that sounds confusing, try reading the code and it’ll make a lot more sense. We had to do all these extra steps because there isn’t an active pool in Uniswap for directly exchanging DAI for SNX. So we go from SNX to ETH to DAI." }, { "code": null, "e": 4903, "s": 4768, "text": "Next time we’ll toss our data in a UI and see how we can query blockchain data in real-time to keep up-to-date with on-chain activity." }, { "code": null, "e": 4947, "s": 4903, "text": "Let’s continue the conversation on Twitter." }, { "code": null, "e": 4979, "s": 4947, "text": "Access the full code on GitHub." } ]
Currency Converter in JavaScript - GeeksforGeeks
21 May, 2021 In this article, we will implement a currency converter that simply converts the currency into any other country’s currency. Pre-requisites: Basic HTML, CSS, JavaScript. Approach: HTML code is implemented for GUI for user entries of the amount and two currencies. Select the currency, Convert button display the converted amount. The Reset button resets the data. JavaScript functions and custom methods are used for implementing currency conversion like addEventListener(). Currency exchange API is used in the script file. HTML code: The following HTML code implements the GUI for user entries like amount and both the currencies for which the conversion needs to take place. index.html <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Currency Converter</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"> </script> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Amiri&family=Lobster&family=Pacifico&display=swap" rel="stylesheet"> <!-- linking style.css file--> <link rel="stylesheet" href="style.css"></head> <body> <!-- Currency Converter --> <h1 class="heading text-center display-2"> Currency Converter</h1> <hr> <div class="container"> <div class="main"> <div class="form-group"> <label for="oamount"> Amount to Convert : </label> <input type="text" class="form-control searchBox" placeholder="0.00" id="oamount"> </div> <div class="row"> <div class="col-sm-6"> <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text">From</span> </div> <select class="form-control from" id="sel1"> <option value="">Select One ...</option> <option value="USD">USD</option> <option value="AED">AED</option> <option value="ARS">ARS</option> <option value="AUD">AUD</option> <option value="BGN">BGN</option> <option value="BRL">BRL</option> <option value="BSD">BSD</option> <option value="CAD">CAD</option> <option value="CHF">CHF</option> <option value="CLP">CLP</option> <option value="CNY">CNY</option> <option value="COP">COP</option> <option value="CZK">CZK</option> <option value="DKK">DKK</option> <option value="DOP">DOP</option> <option value="EGP">EGP</option> <option value="EUR">EUR</option> <option value="FJD">FJD</option> <option value="GBP">GBP</option> <option value="GTQ">GTQ</option> <option value="HKD">HKD</option> <option value="HRK">HRK</option> <option value="HUF">HUF</option> <option value="IDR">IDR</option> <option value="ILS">ILS</option> <option value="INR">INR</option> <option value="ISK">ISK</option> <option value="JPY">JPY</option> <option value="KRW">KRW</option> <option value="KZT">KZT</option> <option value="MVR">MVR</option> <option value="MXN">MXN</option> <option value="MYR">MYR</option> <option value="NOK">NOK</option> <option value="NZD">NZD</option> <option value="PAB">PAB</option> <option value="PEN">PEN</option> <option value="PHP">PHP</option> <option value="PKR">PKR</option> <option value="PLN">PLN</option> <option value="PYG">PYG</option> <option value="RON">RON</option> <option value="RUB">RUB</option> <option value="SAR">SAR</option> <option value="SEK">SEK</option> <option value="SGD">SGD</option> <option value="THB">THB</option> <option value="TRY">TRY</option> <option value="TWD">TWD</option> <option value="UAH">UAH</option> <option value="UYU">UYU</option> <option value="ZAR">ZAR</option> </select> </div> </div> <div class="col-sm-6"> <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text">To</span> </div> <select class="form-control to" id="sel2"> <option value="">Select One ...</option> <option value="USD">USD</option> <option value="AED">AED</option> <option value="ARS">ARS</option> <option value="AUD">AUD</option> <option value="BGN">BGN</option> <option value="BRL">BRL</option> <option value="BSD">BSD</option> <option value="CAD">CAD</option> <option value="CHF">CHF</option> <option value="CLP">CLP</option> <option value="CNY">CNY</option> <option value="COP">COP</option> <option value="CZK">CZK</option> <option value="DKK">DKK</option> <option value="DOP">DOP</option> <option value="EGP">EGP</option> <option value="EUR">EUR</option> <option value="FJD">FJD</option> <option value="GBP">GBP</option> <option value="GTQ">GTQ</option> <option value="HKD">HKD</option> <option value="HRK">HRK</option> <option value="HUF">HUF</option> <option value="IDR">IDR</option> <option value="ILS">ILS</option> <option value="INR">INR</option> <option value="ISK">ISK</option> <option value="JPY">JPY</option> <option value="KRW">KRW</option> <option value="KZT">KZT</option> <option value="MVR">MVR</option> <option value="MXN">MXN</option> <option value="MYR">MYR</option> <option value="NOK">NOK</option> <option value="NZD">NZD</option> <option value="PAB">PAB</option> <option value="PEN">PEN</option> <option value="PHP">PHP</option> <option value="PKR">PKR</option> <option value="PLN">PLN</option> <option value="PYG">PYG</option> <option value="RON">RON</option> <option value="RUB">RUB</option> <option value="SAR">SAR</option> <option value="SEK">SEK</option> <option value="SGD">SGD</option> <option value="THB">THB</option> <option value="TRY">TRY</option> <option value="TWD">TWD</option> <option value="UAH">UAH</option> <option value="UYU">UYU</option> <option value="ZAR">ZAR</option> </select> </div> </div> </div> <div class="text-center"> <!-- convert button --> <button class="btn btn-primary convert m-2" type="submit"> Convert </button> <!-- reset button --> <button class="btn btn-primary m-2" onclick="clearVal()"> Reset </button> </div> </div> <div id="finalAmount" class="text-center"> <!-- Display the converted amount --> <h2>Converted Amount : <span class="finalValue" style="color:green;"> </span> </h2> </div> </div> <!-- linking script.js file --> <script src="script.js"></script></body> </html> CSS code: The following is the content for the file “style.css” used in the above HTML file. style.css body { background-color: aliceblue; background-position: center; background-size: cover; background-attachment: fixed; background-repeat: no-repeat;} .heading { font-family: 'Pacifico', cursive; margin: 35px auto 20px;} hr { border-top: 2px solid black; width: 40%; margin-bottom: 55px;} .main { width: 50vw; margin: auto; padding: 30px; border-radius: 5px; background-color: rgba(0, 0, 0, 0.5); color: white;} label { font-size: 20px;} .btn { width: 200px;} #finalAmount { font-family: 'Lobster', cursive; display: none; margin: 50px auto;} #finalAmount h2 { font-size: 50px;} .finalValue { font-family: 'Amiri', serif;} @media (max-width: 768px) { hr { width: 60%; } .main { width: 100%; }} @media (max-width: 400px) { .heading { font-size: 60px; } hr { width: 75%; } #finalAmount h2, .finalValue { font-size: 40px; }} JavaScript code: The following is the content for the file “script.js” used in the above HTML code. Javascript // include api for currency changeconst api = "https://api.exchangerate-api.com/v4/latest/USD"; // for selecting different controlsvar search = document.querySelector(".searchBox");var convert = document.querySelector(".convert");var fromCurrecy = document.querySelector(".from");var toCurrecy = document.querySelector(".to");var finalValue = document.querySelector(".finalValue");var finalAmount = document.getElementById("finalAmount");var resultFrom;var resultTo;var searchValue; // Event when currency is changedfromCurrecy.addEventListener('change', (event) => { resultFrom = `${event.target.value}`;}); // Event when currency is changedtoCurrecy.addEventListener('change', (event) => { resultTo = `${event.target.value}`;}); search.addEventListener('input', updateValue); // function for updating valuefunction updateValue(e) { searchValue = e.target.value;} // when user clicks, it calls function getresults convert.addEventListener("click", getResults); // function getresultsfunction getResults() { fetch(`${api}`) .then(currency => { return currency.json(); }).then(displayResults);} // display results after convertionfunction displayResults(currency) { let fromRate = currency.rates[resultFrom]; let toRate = currency.rates[resultTo]; finalValue.innerHTML = ((toRate / fromRate) * searchValue).toFixed(2); finalAmount.style.display = "block";} // when user click on reset buttonfunction clearVal() { window.location.reload(); document.getElementsByClassName("finalValue").innerHTML = "";}; Output: Before click: After click: After conversion Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML5 javascript-math JavaScript-Questions Project-Ideas CSS HTML JavaScript Web Technologies HTML 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? How to create footer to stay at the bottom of a Web page? How to update Node.js and NPM to next version ? Types of CSS (Cascading Style Sheet) Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to set the default value for an HTML <select> element ? How to update Node.js and NPM to next version ? How to set input type date in dd-mm-yyyy format using HTML ?
[ { "code": null, "e": 37581, "s": 37553, "text": "\n21 May, 2021" }, { "code": null, "e": 37706, "s": 37581, "text": "In this article, we will implement a currency converter that simply converts the currency into any other country’s currency." }, { "code": null, "e": 37722, "s": 37706, "text": "Pre-requisites:" }, { "code": null, "e": 37751, "s": 37722, "text": "Basic HTML, CSS, JavaScript." }, { "code": null, "e": 37761, "s": 37751, "text": "Approach:" }, { "code": null, "e": 37845, "s": 37761, "text": "HTML code is implemented for GUI for user entries of the amount and two currencies." }, { "code": null, "e": 37911, "s": 37845, "text": "Select the currency, Convert button display the converted amount." }, { "code": null, "e": 37945, "s": 37911, "text": "The Reset button resets the data." }, { "code": null, "e": 38056, "s": 37945, "text": "JavaScript functions and custom methods are used for implementing currency conversion like addEventListener()." }, { "code": null, "e": 38106, "s": 38056, "text": "Currency exchange API is used in the script file." }, { "code": null, "e": 38259, "s": 38106, "text": "HTML code: The following HTML code implements the GUI for user entries like amount and both the currencies for which the conversion needs to take place." }, { "code": null, "e": 38270, "s": 38259, "text": "index.html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>Currency Converter</title> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js\"> </script> <link rel=\"preconnect\" href=\"https://fonts.gstatic.com\"> <link href=\"https://fonts.googleapis.com/css2?family=Amiri&family=Lobster&family=Pacifico&display=swap\" rel=\"stylesheet\"> <!-- linking style.css file--> <link rel=\"stylesheet\" href=\"style.css\"></head> <body> <!-- Currency Converter --> <h1 class=\"heading text-center display-2\"> Currency Converter</h1> <hr> <div class=\"container\"> <div class=\"main\"> <div class=\"form-group\"> <label for=\"oamount\"> Amount to Convert : </label> <input type=\"text\" class=\"form-control searchBox\" placeholder=\"0.00\" id=\"oamount\"> </div> <div class=\"row\"> <div class=\"col-sm-6\"> <div class=\"input-group mb-3\"> <div class=\"input-group-prepend\"> <span class=\"input-group-text\">From</span> </div> <select class=\"form-control from\" id=\"sel1\"> <option value=\"\">Select One ...</option> <option value=\"USD\">USD</option> <option value=\"AED\">AED</option> <option value=\"ARS\">ARS</option> <option value=\"AUD\">AUD</option> <option value=\"BGN\">BGN</option> <option value=\"BRL\">BRL</option> <option value=\"BSD\">BSD</option> <option value=\"CAD\">CAD</option> <option value=\"CHF\">CHF</option> <option value=\"CLP\">CLP</option> <option value=\"CNY\">CNY</option> <option value=\"COP\">COP</option> <option value=\"CZK\">CZK</option> <option value=\"DKK\">DKK</option> <option value=\"DOP\">DOP</option> <option value=\"EGP\">EGP</option> <option value=\"EUR\">EUR</option> <option value=\"FJD\">FJD</option> <option value=\"GBP\">GBP</option> <option value=\"GTQ\">GTQ</option> <option value=\"HKD\">HKD</option> <option value=\"HRK\">HRK</option> <option value=\"HUF\">HUF</option> <option value=\"IDR\">IDR</option> <option value=\"ILS\">ILS</option> <option value=\"INR\">INR</option> <option value=\"ISK\">ISK</option> <option value=\"JPY\">JPY</option> <option value=\"KRW\">KRW</option> <option value=\"KZT\">KZT</option> <option value=\"MVR\">MVR</option> <option value=\"MXN\">MXN</option> <option value=\"MYR\">MYR</option> <option value=\"NOK\">NOK</option> <option value=\"NZD\">NZD</option> <option value=\"PAB\">PAB</option> <option value=\"PEN\">PEN</option> <option value=\"PHP\">PHP</option> <option value=\"PKR\">PKR</option> <option value=\"PLN\">PLN</option> <option value=\"PYG\">PYG</option> <option value=\"RON\">RON</option> <option value=\"RUB\">RUB</option> <option value=\"SAR\">SAR</option> <option value=\"SEK\">SEK</option> <option value=\"SGD\">SGD</option> <option value=\"THB\">THB</option> <option value=\"TRY\">TRY</option> <option value=\"TWD\">TWD</option> <option value=\"UAH\">UAH</option> <option value=\"UYU\">UYU</option> <option value=\"ZAR\">ZAR</option> </select> </div> </div> <div class=\"col-sm-6\"> <div class=\"input-group mb-3\"> <div class=\"input-group-prepend\"> <span class=\"input-group-text\">To</span> </div> <select class=\"form-control to\" id=\"sel2\"> <option value=\"\">Select One ...</option> <option value=\"USD\">USD</option> <option value=\"AED\">AED</option> <option value=\"ARS\">ARS</option> <option value=\"AUD\">AUD</option> <option value=\"BGN\">BGN</option> <option value=\"BRL\">BRL</option> <option value=\"BSD\">BSD</option> <option value=\"CAD\">CAD</option> <option value=\"CHF\">CHF</option> <option value=\"CLP\">CLP</option> <option value=\"CNY\">CNY</option> <option value=\"COP\">COP</option> <option value=\"CZK\">CZK</option> <option value=\"DKK\">DKK</option> <option value=\"DOP\">DOP</option> <option value=\"EGP\">EGP</option> <option value=\"EUR\">EUR</option> <option value=\"FJD\">FJD</option> <option value=\"GBP\">GBP</option> <option value=\"GTQ\">GTQ</option> <option value=\"HKD\">HKD</option> <option value=\"HRK\">HRK</option> <option value=\"HUF\">HUF</option> <option value=\"IDR\">IDR</option> <option value=\"ILS\">ILS</option> <option value=\"INR\">INR</option> <option value=\"ISK\">ISK</option> <option value=\"JPY\">JPY</option> <option value=\"KRW\">KRW</option> <option value=\"KZT\">KZT</option> <option value=\"MVR\">MVR</option> <option value=\"MXN\">MXN</option> <option value=\"MYR\">MYR</option> <option value=\"NOK\">NOK</option> <option value=\"NZD\">NZD</option> <option value=\"PAB\">PAB</option> <option value=\"PEN\">PEN</option> <option value=\"PHP\">PHP</option> <option value=\"PKR\">PKR</option> <option value=\"PLN\">PLN</option> <option value=\"PYG\">PYG</option> <option value=\"RON\">RON</option> <option value=\"RUB\">RUB</option> <option value=\"SAR\">SAR</option> <option value=\"SEK\">SEK</option> <option value=\"SGD\">SGD</option> <option value=\"THB\">THB</option> <option value=\"TRY\">TRY</option> <option value=\"TWD\">TWD</option> <option value=\"UAH\">UAH</option> <option value=\"UYU\">UYU</option> <option value=\"ZAR\">ZAR</option> </select> </div> </div> </div> <div class=\"text-center\"> <!-- convert button --> <button class=\"btn btn-primary convert m-2\" type=\"submit\"> Convert </button> <!-- reset button --> <button class=\"btn btn-primary m-2\" onclick=\"clearVal()\"> Reset </button> </div> </div> <div id=\"finalAmount\" class=\"text-center\"> <!-- Display the converted amount --> <h2>Converted Amount : <span class=\"finalValue\" style=\"color:green;\"> </span> </h2> </div> </div> <!-- linking script.js file --> <script src=\"script.js\"></script></body> </html>", "e": 47751, "s": 38270, "text": null }, { "code": null, "e": 47844, "s": 47751, "text": "CSS code: The following is the content for the file “style.css” used in the above HTML file." }, { "code": null, "e": 47854, "s": 47844, "text": "style.css" }, { "code": "body { background-color: aliceblue; background-position: center; background-size: cover; background-attachment: fixed; background-repeat: no-repeat;} .heading { font-family: 'Pacifico', cursive; margin: 35px auto 20px;} hr { border-top: 2px solid black; width: 40%; margin-bottom: 55px;} .main { width: 50vw; margin: auto; padding: 30px; border-radius: 5px; background-color: rgba(0, 0, 0, 0.5); color: white;} label { font-size: 20px;} .btn { width: 200px;} #finalAmount { font-family: 'Lobster', cursive; display: none; margin: 50px auto;} #finalAmount h2 { font-size: 50px;} .finalValue { font-family: 'Amiri', serif;} @media (max-width: 768px) { hr { width: 60%; } .main { width: 100%; }} @media (max-width: 400px) { .heading { font-size: 60px; } hr { width: 75%; } #finalAmount h2, .finalValue { font-size: 40px; }}", "e": 48819, "s": 47854, "text": null }, { "code": null, "e": 48919, "s": 48819, "text": "JavaScript code: The following is the content for the file “script.js” used in the above HTML code." }, { "code": null, "e": 48930, "s": 48919, "text": "Javascript" }, { "code": "// include api for currency changeconst api = \"https://api.exchangerate-api.com/v4/latest/USD\"; // for selecting different controlsvar search = document.querySelector(\".searchBox\");var convert = document.querySelector(\".convert\");var fromCurrecy = document.querySelector(\".from\");var toCurrecy = document.querySelector(\".to\");var finalValue = document.querySelector(\".finalValue\");var finalAmount = document.getElementById(\"finalAmount\");var resultFrom;var resultTo;var searchValue; // Event when currency is changedfromCurrecy.addEventListener('change', (event) => { resultFrom = `${event.target.value}`;}); // Event when currency is changedtoCurrecy.addEventListener('change', (event) => { resultTo = `${event.target.value}`;}); search.addEventListener('input', updateValue); // function for updating valuefunction updateValue(e) { searchValue = e.target.value;} // when user clicks, it calls function getresults convert.addEventListener(\"click\", getResults); // function getresultsfunction getResults() { fetch(`${api}`) .then(currency => { return currency.json(); }).then(displayResults);} // display results after convertionfunction displayResults(currency) { let fromRate = currency.rates[resultFrom]; let toRate = currency.rates[resultTo]; finalValue.innerHTML = ((toRate / fromRate) * searchValue).toFixed(2); finalAmount.style.display = \"block\";} // when user click on reset buttonfunction clearVal() { window.location.reload(); document.getElementsByClassName(\"finalValue\").innerHTML = \"\";};", "e": 50503, "s": 48930, "text": null }, { "code": null, "e": 50511, "s": 50503, "text": "Output:" }, { "code": null, "e": 50525, "s": 50511, "text": "Before click:" }, { "code": null, "e": 50538, "s": 50525, "text": "After click:" }, { "code": null, "e": 50555, "s": 50538, "text": "After conversion" }, { "code": null, "e": 50692, "s": 50555, "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": 50698, "s": 50692, "text": "HTML5" }, { "code": null, "e": 50714, "s": 50698, "text": "javascript-math" }, { "code": null, "e": 50735, "s": 50714, "text": "JavaScript-Questions" }, { "code": null, "e": 50749, "s": 50735, "text": "Project-Ideas" }, { "code": null, "e": 50753, "s": 50749, "text": "CSS" }, { "code": null, "e": 50758, "s": 50753, "text": "HTML" }, { "code": null, "e": 50769, "s": 50758, "text": "JavaScript" }, { "code": null, "e": 50786, "s": 50769, "text": "Web Technologies" }, { "code": null, "e": 50791, "s": 50786, "text": "HTML" }, { "code": null, "e": 50889, "s": 50791, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 50898, "s": 50889, "text": "Comments" }, { "code": null, "e": 50911, "s": 50898, "text": "Old Comments" }, { "code": null, "e": 50973, "s": 50911, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 51023, "s": 50973, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 51081, "s": 51023, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 51129, "s": 51081, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 51166, "s": 51129, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 51228, "s": 51166, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 51278, "s": 51228, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 51338, "s": 51278, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 51386, "s": 51338, "text": "How to update Node.js and NPM to next version ?" } ]
Lodash _.orderBy() Method
06 Sep, 2020 Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, collection, strings, objects, numbers, etc. The _.orderBy() method is similar to _.sortBy() method except that it allows the sort orders of the iterates to sort by. If orders are unspecified, then all values are sorted in ascending order otherwise order of corresponding values specifies an order of “desc” for descending or “asc” for ascending sort. Syntax: _.orderBy(collection, iteratees, orders) Parameters: This method accepts three parameters as mentioned above and described below: collection: This parameter holds the collection to iterate over. iteratee: This parameter holds the iteratees to sort by. order: This parameter holds the sort orders of iteratees. Return Value: This method returns the new sorted array. Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library in the file. // Requiring the lodash library const _ = require("lodash"); // Original array var users = [ { 'patron': 'jonny', 'age': 48 }, { 'patron': 'john', 'age': 34 }, { 'patron': 'john', 'age': 40 }, { 'patron': 'jonny', 'age': 36 }]; // Use of _.orderBy() method// Sort by `patron` in ascending order// and by `age` in descending order let gfg = _.orderBy(users, ['patron', 'age'], ['asc', 'desc']); // Printing the output console.log(gfg); Output: [ { 'patron': 'john', 'age': 40 }, { 'patron': 'john', 'age': 34 }, { 'patron': 'jonny', 'age': 48 }, { 'patron': 'jonny', 'age': 36 } ] Example 2: // Requiring the lodash library const _ = require("lodash"); // Original array var users = [ { 'employee': 'hunny', 'salary': 60000 }, { 'employee': 'munny', 'salary': 40000 }, { 'employee': 'hunny', 'salary': 55000 }, { 'employee': 'munny', 'salary': 36000 }]; // Use of _.orderBy() method// Sort by `employee` in ascending order// and by `salary` in descending order let gfg = _.orderBy(users, ['employee', 'salary'], ['asc', 'desc']); // Printing the output console.log(gfg); Output: [ { 'employee': 'hunny', 'salary': 60000 }, { 'employee': 'hunny', 'salary': 55000 }, { 'employee': 'munny', 'salary': 40000 }, { 'employee': 'munny', 'salary': 36000 } ] Note: This code will not work in normal JavaScript because it requires the library lodash to be installed. JavaScript-Lodash JavaScript 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": "\n06 Sep, 2020" }, { "code": null, "e": 487, "s": 28, "text": "Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, collection, strings, objects, numbers, etc. The _.orderBy() method is similar to _.sortBy() method except that it allows the sort orders of the iterates to sort by. If orders are unspecified, then all values are sorted in ascending order otherwise order of corresponding values specifies an order of “desc” for descending or “asc” for ascending sort." }, { "code": null, "e": 495, "s": 487, "text": "Syntax:" }, { "code": null, "e": 536, "s": 495, "text": "_.orderBy(collection, iteratees, orders)" }, { "code": null, "e": 625, "s": 536, "text": "Parameters: This method accepts three parameters as mentioned above and described below:" }, { "code": null, "e": 690, "s": 625, "text": "collection: This parameter holds the collection to iterate over." }, { "code": null, "e": 747, "s": 690, "text": "iteratee: This parameter holds the iteratees to sort by." }, { "code": null, "e": 805, "s": 747, "text": "order: This parameter holds the sort orders of iteratees." }, { "code": null, "e": 861, "s": 805, "text": "Return Value: This method returns the new sorted array." }, { "code": null, "e": 956, "s": 861, "text": "Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library in the file." }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // Original array var users = [ { 'patron': 'jonny', 'age': 48 }, { 'patron': 'john', 'age': 34 }, { 'patron': 'john', 'age': 40 }, { 'patron': 'jonny', 'age': 36 }]; // Use of _.orderBy() method// Sort by `patron` in ascending order// and by `age` in descending order let gfg = _.orderBy(users, ['patron', 'age'], ['asc', 'desc']); // Printing the output console.log(gfg);", "e": 1424, "s": 956, "text": null }, { "code": null, "e": 1432, "s": 1424, "text": "Output:" }, { "code": null, "e": 1582, "s": 1432, "text": "[\n { 'patron': 'john', 'age': 40 },\n { 'patron': 'john', 'age': 34 },\n { 'patron': 'jonny', 'age': 48 },\n { 'patron': 'jonny', 'age': 36 }\n]\n" }, { "code": null, "e": 1593, "s": 1582, "text": "Example 2:" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // Original array var users = [ { 'employee': 'hunny', 'salary': 60000 }, { 'employee': 'munny', 'salary': 40000 }, { 'employee': 'hunny', 'salary': 55000 }, { 'employee': 'munny', 'salary': 36000 }]; // Use of _.orderBy() method// Sort by `employee` in ascending order// and by `salary` in descending order let gfg = _.orderBy(users, ['employee', 'salary'], ['asc', 'desc']); // Printing the output console.log(gfg);", "e": 2103, "s": 1593, "text": null }, { "code": null, "e": 2111, "s": 2103, "text": "Output:" }, { "code": null, "e": 2295, "s": 2111, "text": "[\n { 'employee': 'hunny', 'salary': 60000 },\n { 'employee': 'hunny', 'salary': 55000 },\n { 'employee': 'munny', 'salary': 40000 },\n { 'employee': 'munny', 'salary': 36000 }\n]\n" }, { "code": null, "e": 2402, "s": 2295, "text": "Note: This code will not work in normal JavaScript because it requires the library lodash to be installed." }, { "code": null, "e": 2420, "s": 2402, "text": "JavaScript-Lodash" }, { "code": null, "e": 2431, "s": 2420, "text": "JavaScript" }, { "code": null, "e": 2448, "s": 2431, "text": "Web Technologies" } ]
What is the difference between children and childNodes in JavaScript?
16 Aug, 2019 childNodes:The childNodes property is a property of Node in Javascript and is used to return a Nodelist of child nodes. Nodelist items are objects, not strings and they can be accessed using index numbers. The first childNode starts at index 0.Syntaxelement.childNodes Syntax element.childNodes childrenThe children is a property of element which returns the child elements of an element as objects.Syntaxelement.children Syntax element.children The main difference between children and childNodes property is that children work upon elements and childNodes on nodes including non-element nodes like text and comment nodes. Example 1: This example illustrates the property of childNodes. <!DOCTYPE html><html> <body> <style> p { color: green; } </style><center> <h1 style="color:green">GeeksforGeeks</h1> <h2>childNodes</h2> <button onclick="childNode()"> Try it </button> <p id="geek"></p> <script> function childNode() { //accessing all the child nodes present in our code var childNode = document.body.childNodes; var string = ""; var i; for (i = 0; i < childNode.length; i++) { string = string + childNode[i].nodeName + "<br>"; } //appending the child nodes to paragraph with id "geek" document.getElementById( "geek").innerHTML = string; } </script></center></body> </html> Output:Before:After: Example 2: This example illustrates the property of children. <!DOCTYPE html><html> <body> <style> p { color: green; } </style><center> <h1 style="color:green">GeeksforGeeks</h1> <h2>children</h2> <button onclick="myChildren()"> Try it </button> <p id="geek"></p> <script> function myChildren() { var c = document.body.children; var string = ""; var i; for (i = 0; i < c.length; i++) { string = string + c[i].tagName + "<br>"; } document.getElementById( "geek").innerHTML = string; } </script></center></body> </html> Output:Before:After: Supported Browsers: Google ChromeMozilla FirefoxApple SafariOperaInternet Explorer/Edge Google Chrome Mozilla Firefox Apple Safari Opera Internet Explorer/Edge JavaScript-Misc Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Aug, 2019" }, { "code": null, "e": 297, "s": 28, "text": "childNodes:The childNodes property is a property of Node in Javascript and is used to return a Nodelist of child nodes. Nodelist items are objects, not strings and they can be accessed using index numbers. The first childNode starts at index 0.Syntaxelement.childNodes" }, { "code": null, "e": 304, "s": 297, "text": "Syntax" }, { "code": null, "e": 323, "s": 304, "text": "element.childNodes" }, { "code": null, "e": 450, "s": 323, "text": "childrenThe children is a property of element which returns the child elements of an element as objects.Syntaxelement.children" }, { "code": null, "e": 457, "s": 450, "text": "Syntax" }, { "code": null, "e": 474, "s": 457, "text": "element.children" }, { "code": null, "e": 652, "s": 474, "text": "The main difference between children and childNodes property is that children work upon elements and childNodes on nodes including non-element nodes like text and comment nodes." }, { "code": null, "e": 716, "s": 652, "text": "Example 1: This example illustrates the property of childNodes." }, { "code": "<!DOCTYPE html><html> <body> <style> p { color: green; } </style><center> <h1 style=\"color:green\">GeeksforGeeks</h1> <h2>childNodes</h2> <button onclick=\"childNode()\"> Try it </button> <p id=\"geek\"></p> <script> function childNode() { //accessing all the child nodes present in our code var childNode = document.body.childNodes; var string = \"\"; var i; for (i = 0; i < childNode.length; i++) { string = string + childNode[i].nodeName + \"<br>\"; } //appending the child nodes to paragraph with id \"geek\" document.getElementById( \"geek\").innerHTML = string; } </script></center></body> </html>", "e": 1528, "s": 716, "text": null }, { "code": null, "e": 1549, "s": 1528, "text": "Output:Before:After:" }, { "code": null, "e": 1611, "s": 1549, "text": "Example 2: This example illustrates the property of children." }, { "code": "<!DOCTYPE html><html> <body> <style> p { color: green; } </style><center> <h1 style=\"color:green\">GeeksforGeeks</h1> <h2>children</h2> <button onclick=\"myChildren()\"> Try it </button> <p id=\"geek\"></p> <script> function myChildren() { var c = document.body.children; var string = \"\"; var i; for (i = 0; i < c.length; i++) { string = string + c[i].tagName + \"<br>\"; } document.getElementById( \"geek\").innerHTML = string; } </script></center></body> </html>", "e": 2244, "s": 1611, "text": null }, { "code": null, "e": 2265, "s": 2244, "text": "Output:Before:After:" }, { "code": null, "e": 2285, "s": 2265, "text": "Supported Browsers:" }, { "code": null, "e": 2353, "s": 2285, "text": "Google ChromeMozilla FirefoxApple SafariOperaInternet Explorer/Edge" }, { "code": null, "e": 2367, "s": 2353, "text": "Google Chrome" }, { "code": null, "e": 2383, "s": 2367, "text": "Mozilla Firefox" }, { "code": null, "e": 2396, "s": 2383, "text": "Apple Safari" }, { "code": null, "e": 2402, "s": 2396, "text": "Opera" }, { "code": null, "e": 2425, "s": 2402, "text": "Internet Explorer/Edge" }, { "code": null, "e": 2441, "s": 2425, "text": "JavaScript-Misc" }, { "code": null, "e": 2448, "s": 2441, "text": "Picked" }, { "code": null, "e": 2459, "s": 2448, "text": "JavaScript" }, { "code": null, "e": 2476, "s": 2459, "text": "Web Technologies" }, { "code": null, "e": 2503, "s": 2476, "text": "Web technologies Questions" } ]
SQL | Concatenation Operator
21 Mar, 2018 Prerequisite: Basic Select statement, Insert into clause, SQL Create Clause, SQL Aliases || or concatenation operator is use to link columns or character strings. We can also use a literal. A literal is a character, number or date that is included in the SELECT statement. Let’s demonstrate it through an example: Syntax: SELECT id, first_name, last_name, first_name || last_name, salary, first_name || salary FROM myTable Output (Third and Fifth Columns show values concatenated by operator ||) id first_name last_name first_name||last_name salary first_name||salary 1 Rajat Rawat RajatRawat 10000 Rajat10000 2 Geeks ForGeeks GeeksForGeeks 20000 Geeks20000 3 Shane Watson ShaneWatson 50000 Shane50000 4 Kedar Jadhav KedarJadhav 90000 Kedar90000 Note: Here above we have used || which is known as Concatenation operator which is used to link 2 or as many columns as you want in your select query and it is independent of the datatype of column. Here above we have linked 2 columns i.e, first_name+last_name as well as first_name+salary. We can also use literals in the concatenation operator. Let’s see: Example 1: Using character literalSyntax: SELECT id, first_name, last_name, salary, first_name||' has salary '||salary as "new" FROM myTable Output : (Concatenating three values and giving a name 'new') id first_name last_name salary new 1 Rajat Rawat 10000 Rajat has salary 10000 2 Geeks ForGeeks 20000 Geeks has salary 20000 3 Shane Watson 50000 Shane has salary 50000 4 Kedar Jadhav 90000 Kedar has salary 90000 Note: Here above we have used has salary as a character literal in our select statement. Similarly we can use number literal or date literal according to our requirement. Example 2: Using character as well as number literalSyntax: SELECT id, first_name, last_name, salary, first_name||100||' has id '||id AS "new" FROM myTable Output (Making readable output by concatenating a string with values) id first_name last_name salary new 1 Rajat Rawat 10000 Rajat100 has id 1 2 Geeks ForGeeks 20000 Geeks100 has id 2 3 Shane Watson 50000 Shane100 has id 3 4 Kedar Jadhav 90000 Kedar100 has id 4 Here above we have used has salary as a character literal as well as 100 as number literal in our select statement. References:1) About Concatenation operator: Oracle Docs2) Performing SQL Queries Online: Oracle Live SQL Note: For performing SQL Queries online you must have account on Oracle, if you don’t have then you can make by opening above link. SQL-Clauses-Operators SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n21 Mar, 2018" }, { "code": null, "e": 143, "s": 54, "text": "Prerequisite: Basic Select statement, Insert into clause, SQL Create Clause, SQL Aliases" }, { "code": null, "e": 327, "s": 143, "text": "|| or concatenation operator is use to link columns or character strings. We can also use a literal. A literal is a character, number or date that is included in the SELECT statement." }, { "code": null, "e": 368, "s": 327, "text": "Let’s demonstrate it through an example:" }, { "code": null, "e": 376, "s": 368, "text": "Syntax:" }, { "code": null, "e": 493, "s": 376, "text": "SELECT id, first_name, last_name, first_name || last_name, \n salary, first_name || salary FROM myTable" }, { "code": null, "e": 1078, "s": 493, "text": "Output (Third and Fifth Columns show values concatenated by operator ||)\nid first_name last_name first_name||last_name salary first_name||salary \n1 Rajat Rawat RajatRawat 10000 Rajat10000 \n2 Geeks ForGeeks GeeksForGeeks 20000 Geeks20000 \n3 Shane Watson ShaneWatson 50000 Shane50000 \n4 Kedar Jadhav KedarJadhav 90000 Kedar90000 \n" }, { "code": null, "e": 1369, "s": 1078, "text": "Note: Here above we have used || which is known as Concatenation operator which is used to link 2 or as many columns as you want in your select query and it is independent of the datatype of column. Here above we have linked 2 columns i.e, first_name+last_name as well as first_name+salary." }, { "code": null, "e": 1436, "s": 1369, "text": "We can also use literals in the concatenation operator. Let’s see:" }, { "code": null, "e": 1478, "s": 1436, "text": "Example 1: Using character literalSyntax:" }, { "code": null, "e": 1586, "s": 1478, "text": "SELECT id, first_name, last_name, salary, \n first_name||' has salary '||salary as \"new\" FROM myTable\n" }, { "code": null, "e": 1943, "s": 1586, "text": "Output : (Concatenating three values and giving a name 'new')\nid first_name last_name salary new\n1 Rajat Rawat 10000 Rajat has salary 10000\n2 Geeks ForGeeks 20000 Geeks has salary 20000\n3 Shane Watson 50000 Shane has salary 50000\n4 Kedar Jadhav 90000 Kedar has salary 90000\n\n" }, { "code": null, "e": 2114, "s": 1943, "text": "Note: Here above we have used has salary as a character literal in our select statement. Similarly we can use number literal or date literal according to our requirement." }, { "code": null, "e": 2174, "s": 2114, "text": "Example 2: Using character as well as number literalSyntax:" }, { "code": null, "e": 2298, "s": 2174, "text": "SELECT id, first_name, last_name, salary, first_name||100||' \n has id '||id AS \"new\" FROM myTable\n" }, { "code": null, "e": 2647, "s": 2298, "text": "Output (Making readable output by concatenating a string\nwith values)\n\nid first_name last_name salary new\n1 Rajat Rawat 10000 Rajat100 has id 1\n2 Geeks ForGeeks 20000 Geeks100 has id 2\n3 Shane Watson 50000 Shane100 has id 3\n4 Kedar Jadhav 90000 Kedar100 has id 4" }, { "code": null, "e": 2763, "s": 2647, "text": "Here above we have used has salary as a character literal as well as 100 as number literal in our select statement." }, { "code": null, "e": 2868, "s": 2763, "text": "References:1) About Concatenation operator: Oracle Docs2) Performing SQL Queries Online: Oracle Live SQL" }, { "code": null, "e": 3000, "s": 2868, "text": "Note: For performing SQL Queries online you must have account on Oracle, if you don’t have then you can make by opening above link." }, { "code": null, "e": 3022, "s": 3000, "text": "SQL-Clauses-Operators" }, { "code": null, "e": 3026, "s": 3022, "text": "SQL" }, { "code": null, "e": 3030, "s": 3026, "text": "SQL" } ]
How to create a custom String class in C++ with basic functionalities
01 Feb, 2022 In this article, we will create our custom string class which will have the same functionality as the existing string class.The string class has the following basic functionalities: Constructor with no arguments: This allocates the storage for the string object in the heap and assign the value as a NULL character.Constructor with only one argument : It accepts a pointer to a character or we can say if we pass an array of characters, accepts the pointer to the first character in the array then the constructor of the String class allocates the storage on the heap memory of the same size as of the passed array and copies the contents of the array to that allocated memory in heap. It copies the contents using the strcpy() function declared in cstring library. Before doing the above operation it checks that if the argument passed is a NULL pointer then it behaves as a constructor with no arguments.Copy Constructor: It is called when any object created of the same type from an already created object then it performs a deep copy. It allocates new space on the heap for the object that is to be created and copies the contents of the passed object(that is passed as a reference).Move Constructor: It is typically called when an object is initialized(by direct-initialization or copy-initialization) from rvalue of the same type. It accepts a reference to an rvalue of an object of the type of custom string class. Constructor with no arguments: This allocates the storage for the string object in the heap and assign the value as a NULL character. Constructor with only one argument : It accepts a pointer to a character or we can say if we pass an array of characters, accepts the pointer to the first character in the array then the constructor of the String class allocates the storage on the heap memory of the same size as of the passed array and copies the contents of the array to that allocated memory in heap. It copies the contents using the strcpy() function declared in cstring library. Before doing the above operation it checks that if the argument passed is a NULL pointer then it behaves as a constructor with no arguments. Copy Constructor: It is called when any object created of the same type from an already created object then it performs a deep copy. It allocates new space on the heap for the object that is to be created and copies the contents of the passed object(that is passed as a reference). Move Constructor: It is typically called when an object is initialized(by direct-initialization or copy-initialization) from rvalue of the same type. It accepts a reference to an rvalue of an object of the type of custom string class. Below is the implementation of the above methods using custom string class Mystring: CPP // C++ program to illustrate the// above discussed functionality#include <cstring>#include <iostream>using namespace std; // Custom string classclass Mystring { // Initialise the char array char* str; public: // No arguments Constructor Mystring(); // Constructor with 1 arguments Mystring(char* val); // Copy Constructor Mystring(const Mystring& source); // Move Constructor Mystring(Mystring&& source); // Destructor ~Mystring() { delete str; }}; // Function to illustrate Constructor// with no argumentsMystring::Mystring() : str{ nullptr }{ str = new char[1]; str[0] = '\0';} // Function to illustrate Constructor// with one argumentsMystring::Mystring(char* val){ if (val == nullptr) { str = new char[1]; str[0] = '\0'; } else { str = new char[strlen(val) + 1]; // Copy character of val[] // using strcpy strcpy(str, val); str[strlen(val)] = '\0'; cout << "The string passed is: " << str << endl; }} // Function to illustrate// Copy ConstructorMystring::Mystring(const Mystring& source){ str = new char[strlen(source.str) + 1]; strcpy(str, source.str); str[strlen(source.str)] = '\0';} // Function to illustrate// Move ConstructorMystring::Mystring(Mystring&& source){ str = source.str; source.str = nullptr;} // Driver Codeint main(){ // Constructor with no arguments Mystring a; // Convert string literal to // char array char temp[] = "Hello"; // Constructor with one argument Mystring b{ temp }; // Copy constructor Mystring c{ a }; char temp1[] = "World"; // One arg constructor called, // then the move constructor Mystring d{ Mystring{ temp } }; return 0;} The string passed is: Hello The string passed is: Hello Some more functionalities of string class: pop_back(): Removes the last element from the Mystring object.push_back(char ch): Accepts a character as an argument and adds it to the end of the Mystring object.length(): Returns the length of the mystring.copy(): It copies the mystring object to a character array from a given position(pos) and a specific length(len).swap(): It swaps the two Mystring objects.Concatenate two strings using overloading the ‘+’ operator: Allows us to concatenate two strings. pop_back(): Removes the last element from the Mystring object. push_back(char ch): Accepts a character as an argument and adds it to the end of the Mystring object. length(): Returns the length of the mystring. copy(): It copies the mystring object to a character array from a given position(pos) and a specific length(len). swap(): It swaps the two Mystring objects. Concatenate two strings using overloading the ‘+’ operator: Allows us to concatenate two strings. Below is the program to illustrate the above-discussed functionality: CPP // C++ program to illustrate the// above functionalities#include <cstring>#include <iostream>using namespace std; // Class Mystringclass Mystring { // Prototype for stream insertion friend ostream& operator<<( ostream& os, const Mystring& obj); // Prototype for stream extraction friend istream& operator>>( istream& is, Mystring& obj); // Prototype for '+' // operator overloading friend Mystring operator+( const Mystring& lhs, const Mystring& rhs); char* str; public: // No arguments constructor Mystring(); // pop_back() function void pop_bk(); // push_back() function void push_bk(char a); // To get the length int get_length(); // Function to copy the string // of length len from position pos void copy(char s[], int len, int pos); // Swap strings function void swp(Mystring& rhs); // Constructor with 1 arguments Mystring(char* val); // Copy Constructor Mystring(const Mystring& source); // Move Constructor Mystring(Mystring&& source); // Overloading the assignment // operator Mystring& operator=( const Mystring& rhs); // Destructor ~Mystring() { delete str; }}; // Overloading the assignment operatorMystring& Mystring::operator=( const Mystring& rhs){ if (this == &rhs) return *this; delete[] str; str = new char[strlen(rhs.str) + 1]; strcpy(str, rhs.str); return *this;} // Overloading the plus operatorMystring operator+(const Mystring& lhs, const Mystring& rhs){ int length = strlen(lhs.str) + strlen(rhs.str); char* buff = new char[length + 1]; // Copy the strings to buff[] strcpy(buff, lhs.str); strcat(buff, rhs.str); buff[length] = '\0'; // String temp Mystring temp{ buff }; // delete the buff[] delete[] buff; // Return the concatenated string return temp;}// Overloading the stream// extraction operatoristream& operator>>(istream& is, Mystring& obj){ char* buff = new char[1000]; memset(&buff[0], 0, sizeof(buff)); is >> buff; obj = Mystring{ buff }; delete[] buff; return is;} // Overloading the stream// insertion operatorostream& operator<<(ostream& os, const Mystring& obj){ os << obj.str; return os;} // Function for swapping stringvoid Mystring::swp(Mystring& rhs){ Mystring temp{ rhs }; rhs = *this; *this = temp;} // Function to copy the stringvoid Mystring::copy(char s[], int len, int pos){ for (int i = 0; i < len; i++) { s[i] = str[pos + i]; } s[len] = '\0';} // Function to implement push_bkvoid Mystring::push_bk(char a){ // Find length of string int length = strlen(str); char* buff = new char[length + 2]; // Copy character from str // to buff[] for (int i = 0; i < length; i++) { buff[i] = str[i]; } buff[length] = a; buff[length + 1] = '\0'; // Assign the new string with // char a to string str *this = Mystring{ buff }; // Delete the temp buff[] delete[] buff;} // Function to implement pop_bkvoid Mystring::pop_bk(){ int length = strlen(str); char* buff = new char[length]; // Copy character from str // to buff[] for (int i = 0; i < length - 1; i++) buff[i] = str[i]; buff[length-1] = '\0'; // Assign the new string with // char a to string str *this = Mystring{ buff }; // delete the buff[] delete[] buff;} // Function to implement get_lengthint Mystring::get_length(){ return strlen(str);} // Function to illustrate Constructor// with no argumentsMystring::Mystring() : str{ nullptr }{ str = new char[1]; str[0] = '\0';} // Function to illustrate Constructor// with one argumentsMystring::Mystring(char* val){ if (val == nullptr) { str = new char[1]; str[0] = '\0'; } else { str = new char[strlen(val) + 1]; // Copy character of val[] // using strcpy strcpy(str, val); str[strlen(val)] = '\0'; }} // Function to illustrate// Copy ConstructorMystring::Mystring(const Mystring& source){ str = new char[strlen(source.str) + 1]; strcpy(str, source.str);} // Function to illustrate// Move ConstructorMystring::Mystring(Mystring&& source){ str = source.str; source.str = nullptr;} // Driver Codeint main(){ // Constructor with no arguments Mystring a; // Convert string literal to // char array char temp[] = "Hello"; // Constructor with one argument Mystring b{ temp }; // Copy constructor Mystring c{ a }; char temp1[] = "World"; // One arg constructor called, // then the move constructor Mystring d{ Mystring{ temp } }; // Remove last character from // Mystring b b.pop_bk(); // Print string b cout << "Mystring b: " << b << endl; // Append last character from // Mystring b b.push_bk('o'); // Print string b cout << "Mystring b: " << b << endl; // Print length of string b cout << "Length of Mystring b: " << b << endl; char arr[80]; // Copy string b chars from // length 0 to 3 b.cpy(arr, 3, 0); // Print string arr cout << "arr is: " << arr << endl; // Swap d and b d.swp(b); // Print d and b cout << d << " " << b << endl; // Concatenate b and b with // overloading '+' operator d = b + b; // Print string d cout << "string d: " << d << endl; return 0;} Mystring b: Hell Mystring b: Hello Length of Mystring b: Hello arr is: Hel Hello Hello string d: HelloHello mdsheraj sumitgumber28 C-String-Question cpp-string strings C++ C++ Programs Strings Strings CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n01 Feb, 2022" }, { "code": null, "e": 238, "s": 54, "text": "In this article, we will create our custom string class which will have the same functionality as the existing string class.The string class has the following basic functionalities: " }, { "code": null, "e": 1478, "s": 238, "text": "Constructor with no arguments: This allocates the storage for the string object in the heap and assign the value as a NULL character.Constructor with only one argument : It accepts a pointer to a character or we can say if we pass an array of characters, accepts the pointer to the first character in the array then the constructor of the String class allocates the storage on the heap memory of the same size as of the passed array and copies the contents of the array to that allocated memory in heap. It copies the contents using the strcpy() function declared in cstring library. Before doing the above operation it checks that if the argument passed is a NULL pointer then it behaves as a constructor with no arguments.Copy Constructor: It is called when any object created of the same type from an already created object then it performs a deep copy. It allocates new space on the heap for the object that is to be created and copies the contents of the passed object(that is passed as a reference).Move Constructor: It is typically called when an object is initialized(by direct-initialization or copy-initialization) from rvalue of the same type. It accepts a reference to an rvalue of an object of the type of custom string class." }, { "code": null, "e": 1612, "s": 1478, "text": "Constructor with no arguments: This allocates the storage for the string object in the heap and assign the value as a NULL character." }, { "code": null, "e": 2204, "s": 1612, "text": "Constructor with only one argument : It accepts a pointer to a character or we can say if we pass an array of characters, accepts the pointer to the first character in the array then the constructor of the String class allocates the storage on the heap memory of the same size as of the passed array and copies the contents of the array to that allocated memory in heap. It copies the contents using the strcpy() function declared in cstring library. Before doing the above operation it checks that if the argument passed is a NULL pointer then it behaves as a constructor with no arguments." }, { "code": null, "e": 2486, "s": 2204, "text": "Copy Constructor: It is called when any object created of the same type from an already created object then it performs a deep copy. It allocates new space on the heap for the object that is to be created and copies the contents of the passed object(that is passed as a reference)." }, { "code": null, "e": 2721, "s": 2486, "text": "Move Constructor: It is typically called when an object is initialized(by direct-initialization or copy-initialization) from rvalue of the same type. It accepts a reference to an rvalue of an object of the type of custom string class." }, { "code": null, "e": 2807, "s": 2721, "text": "Below is the implementation of the above methods using custom string class Mystring: " }, { "code": null, "e": 2811, "s": 2807, "text": "CPP" }, { "code": "// C++ program to illustrate the// above discussed functionality#include <cstring>#include <iostream>using namespace std; // Custom string classclass Mystring { // Initialise the char array char* str; public: // No arguments Constructor Mystring(); // Constructor with 1 arguments Mystring(char* val); // Copy Constructor Mystring(const Mystring& source); // Move Constructor Mystring(Mystring&& source); // Destructor ~Mystring() { delete str; }}; // Function to illustrate Constructor// with no argumentsMystring::Mystring() : str{ nullptr }{ str = new char[1]; str[0] = '\\0';} // Function to illustrate Constructor// with one argumentsMystring::Mystring(char* val){ if (val == nullptr) { str = new char[1]; str[0] = '\\0'; } else { str = new char[strlen(val) + 1]; // Copy character of val[] // using strcpy strcpy(str, val); str[strlen(val)] = '\\0'; cout << \"The string passed is: \" << str << endl; }} // Function to illustrate// Copy ConstructorMystring::Mystring(const Mystring& source){ str = new char[strlen(source.str) + 1]; strcpy(str, source.str); str[strlen(source.str)] = '\\0';} // Function to illustrate// Move ConstructorMystring::Mystring(Mystring&& source){ str = source.str; source.str = nullptr;} // Driver Codeint main(){ // Constructor with no arguments Mystring a; // Convert string literal to // char array char temp[] = \"Hello\"; // Constructor with one argument Mystring b{ temp }; // Copy constructor Mystring c{ a }; char temp1[] = \"World\"; // One arg constructor called, // then the move constructor Mystring d{ Mystring{ temp } }; return 0;}", "e": 4576, "s": 2811, "text": null }, { "code": null, "e": 4632, "s": 4576, "text": "The string passed is: Hello\nThe string passed is: Hello" }, { "code": null, "e": 4679, "s": 4634, "text": "Some more functionalities of string class: " }, { "code": null, "e": 5140, "s": 4679, "text": "pop_back(): Removes the last element from the Mystring object.push_back(char ch): Accepts a character as an argument and adds it to the end of the Mystring object.length(): Returns the length of the mystring.copy(): It copies the mystring object to a character array from a given position(pos) and a specific length(len).swap(): It swaps the two Mystring objects.Concatenate two strings using overloading the ‘+’ operator: Allows us to concatenate two strings." }, { "code": null, "e": 5203, "s": 5140, "text": "pop_back(): Removes the last element from the Mystring object." }, { "code": null, "e": 5305, "s": 5203, "text": "push_back(char ch): Accepts a character as an argument and adds it to the end of the Mystring object." }, { "code": null, "e": 5351, "s": 5305, "text": "length(): Returns the length of the mystring." }, { "code": null, "e": 5465, "s": 5351, "text": "copy(): It copies the mystring object to a character array from a given position(pos) and a specific length(len)." }, { "code": null, "e": 5508, "s": 5465, "text": "swap(): It swaps the two Mystring objects." }, { "code": null, "e": 5606, "s": 5508, "text": "Concatenate two strings using overloading the ‘+’ operator: Allows us to concatenate two strings." }, { "code": null, "e": 5677, "s": 5606, "text": "Below is the program to illustrate the above-discussed functionality: " }, { "code": null, "e": 5681, "s": 5677, "text": "CPP" }, { "code": "// C++ program to illustrate the// above functionalities#include <cstring>#include <iostream>using namespace std; // Class Mystringclass Mystring { // Prototype for stream insertion friend ostream& operator<<( ostream& os, const Mystring& obj); // Prototype for stream extraction friend istream& operator>>( istream& is, Mystring& obj); // Prototype for '+' // operator overloading friend Mystring operator+( const Mystring& lhs, const Mystring& rhs); char* str; public: // No arguments constructor Mystring(); // pop_back() function void pop_bk(); // push_back() function void push_bk(char a); // To get the length int get_length(); // Function to copy the string // of length len from position pos void copy(char s[], int len, int pos); // Swap strings function void swp(Mystring& rhs); // Constructor with 1 arguments Mystring(char* val); // Copy Constructor Mystring(const Mystring& source); // Move Constructor Mystring(Mystring&& source); // Overloading the assignment // operator Mystring& operator=( const Mystring& rhs); // Destructor ~Mystring() { delete str; }}; // Overloading the assignment operatorMystring& Mystring::operator=( const Mystring& rhs){ if (this == &rhs) return *this; delete[] str; str = new char[strlen(rhs.str) + 1]; strcpy(str, rhs.str); return *this;} // Overloading the plus operatorMystring operator+(const Mystring& lhs, const Mystring& rhs){ int length = strlen(lhs.str) + strlen(rhs.str); char* buff = new char[length + 1]; // Copy the strings to buff[] strcpy(buff, lhs.str); strcat(buff, rhs.str); buff[length] = '\\0'; // String temp Mystring temp{ buff }; // delete the buff[] delete[] buff; // Return the concatenated string return temp;}// Overloading the stream// extraction operatoristream& operator>>(istream& is, Mystring& obj){ char* buff = new char[1000]; memset(&buff[0], 0, sizeof(buff)); is >> buff; obj = Mystring{ buff }; delete[] buff; return is;} // Overloading the stream// insertion operatorostream& operator<<(ostream& os, const Mystring& obj){ os << obj.str; return os;} // Function for swapping stringvoid Mystring::swp(Mystring& rhs){ Mystring temp{ rhs }; rhs = *this; *this = temp;} // Function to copy the stringvoid Mystring::copy(char s[], int len, int pos){ for (int i = 0; i < len; i++) { s[i] = str[pos + i]; } s[len] = '\\0';} // Function to implement push_bkvoid Mystring::push_bk(char a){ // Find length of string int length = strlen(str); char* buff = new char[length + 2]; // Copy character from str // to buff[] for (int i = 0; i < length; i++) { buff[i] = str[i]; } buff[length] = a; buff[length + 1] = '\\0'; // Assign the new string with // char a to string str *this = Mystring{ buff }; // Delete the temp buff[] delete[] buff;} // Function to implement pop_bkvoid Mystring::pop_bk(){ int length = strlen(str); char* buff = new char[length]; // Copy character from str // to buff[] for (int i = 0; i < length - 1; i++) buff[i] = str[i]; buff[length-1] = '\\0'; // Assign the new string with // char a to string str *this = Mystring{ buff }; // delete the buff[] delete[] buff;} // Function to implement get_lengthint Mystring::get_length(){ return strlen(str);} // Function to illustrate Constructor// with no argumentsMystring::Mystring() : str{ nullptr }{ str = new char[1]; str[0] = '\\0';} // Function to illustrate Constructor// with one argumentsMystring::Mystring(char* val){ if (val == nullptr) { str = new char[1]; str[0] = '\\0'; } else { str = new char[strlen(val) + 1]; // Copy character of val[] // using strcpy strcpy(str, val); str[strlen(val)] = '\\0'; }} // Function to illustrate// Copy ConstructorMystring::Mystring(const Mystring& source){ str = new char[strlen(source.str) + 1]; strcpy(str, source.str);} // Function to illustrate// Move ConstructorMystring::Mystring(Mystring&& source){ str = source.str; source.str = nullptr;} // Driver Codeint main(){ // Constructor with no arguments Mystring a; // Convert string literal to // char array char temp[] = \"Hello\"; // Constructor with one argument Mystring b{ temp }; // Copy constructor Mystring c{ a }; char temp1[] = \"World\"; // One arg constructor called, // then the move constructor Mystring d{ Mystring{ temp } }; // Remove last character from // Mystring b b.pop_bk(); // Print string b cout << \"Mystring b: \" << b << endl; // Append last character from // Mystring b b.push_bk('o'); // Print string b cout << \"Mystring b: \" << b << endl; // Print length of string b cout << \"Length of Mystring b: \" << b << endl; char arr[80]; // Copy string b chars from // length 0 to 3 b.cpy(arr, 3, 0); // Print string arr cout << \"arr is: \" << arr << endl; // Swap d and b d.swp(b); // Print d and b cout << d << \" \" << b << endl; // Concatenate b and b with // overloading '+' operator d = b + b; // Print string d cout << \"string d: \" << d << endl; return 0;}", "e": 11225, "s": 5681, "text": null }, { "code": null, "e": 11333, "s": 11225, "text": "Mystring b: Hell\nMystring b: Hello\nLength of Mystring b: Hello\narr is: Hel\nHello Hello\nstring d: HelloHello" }, { "code": null, "e": 11344, "s": 11335, "text": "mdsheraj" }, { "code": null, "e": 11358, "s": 11344, "text": "sumitgumber28" }, { "code": null, "e": 11376, "s": 11358, "text": "C-String-Question" }, { "code": null, "e": 11387, "s": 11376, "text": "cpp-string" }, { "code": null, "e": 11395, "s": 11387, "text": "strings" }, { "code": null, "e": 11399, "s": 11395, "text": "C++" }, { "code": null, "e": 11412, "s": 11399, "text": "C++ Programs" }, { "code": null, "e": 11420, "s": 11412, "text": "Strings" }, { "code": null, "e": 11428, "s": 11420, "text": "Strings" }, { "code": null, "e": 11432, "s": 11428, "text": "CPP" } ]
Count number of times each Edge appears in all possible paths of a given Tree
07 Sep, 2021 Given an Undirected Connected Graph in the form of a tree consisting of N nodes and (N – 1) edges, the task for each edge is to count the number of times it appears across all possible paths in the Tree. Examples: Input: Output: 3 4 3 Explanation: All possible paths of a given tree are {(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)} Edge 1 occurs in the paths {(1, 2), (1, 3), (1, 4)}. Therefore, the frequency of the edge is 3. Edge 2 occurs in the paths {(1, 3), (1, 4), (2, 3), (2, 4)}. Therefore, the frequency of the edge is 4. Edge 3 occurs in the paths {(1, 4), (2, 4), (3, 4)}. Therefore, the frequency of the edge is 3. Input: Output: 4 6 4 4 Explanation: Edge 1 occurs in the paths {(1, 2), (1, 3), (1, 4), (1, 5)}. Therefore, the frequency of the edge is 4 Edge 2 occurs in the paths {(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5)}. Therefore, the frequency of the edge is 6 Edge 3 occurs in the paths {(1, 4), (2, 4), (3, 4), (4, 5)}. Therefore, the frequency of the edge is 4 Edge 4 occurs in the paths {(1, 5), (2, 5), (3, 5), (4, 5)}. Therefore, the frequency of the edge is 4 Naive Approach: The simplest approach is to generate all possible paths from each node of the given graph and store the count of edges occurring in these paths by a HashMap. Finally, print the frequencies of each edge. Time Complexity: O(N2) Auxiliary Space: O(N) Efficient Approach: To optimize the above approach, the following observation needs to be made: The green-colored edge will appear in all the paths that connect any vertex from the subtree on its left to any vertex from the subtree on its right. Therefore, the number of paths in which the edge occurs = Product of the count of nodes in the two subtrees = 5 * 3 = 15. Follow the steps below in order to solve the problem: Root the tree at any random vertex, say 1. Perform DFS at Root. Using DFS calculate the subtree size connected to the edges. The frequency of each edge connected to subtree is (subtree size) * (N – subtree size). Store the value calculated above for each node in a HashMap. Finally, after complete the traversal of the tree, traverse the HashMap to print the result. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Number of nodesint N; // Structure of a Nodestruct Node { int node; int edgeLabel;}; // Adjacency List to// represent the Treevector<Node> adj[100005]; // Stores the frequencies// of every edgevector<int> freq; // Function to perform DFSint dfs(int u = 1, int p = 1){ // Add the current node to // size of subtree rooted at u int sz = 1; // Iterate over its children for (auto a : adj[u]) { // Check if child is not parent if (a.node != p) { // Get the subtree size // for the child int val = dfs(a.node, u); // Set the frequency // of the current edge freq[a.edgeLabel] = val * (N - val); // Add the subtree size // to itself sz += val; } } // Return the subtree size return sz;} // Function to add edge between nodesvoid addEdge(int u, int v, int label){ adj[u].push_back({ v, label }); adj[v].push_back({ u, label });} // Function to print the frequencies// of each edge in all possible pathsvoid printFrequencies(){ // Stores the frequency // of all the edges freq = vector<int>(N); // Perform DFS dfs(); for (int i = 1; i < N; i++) { cout << freq[i] << " "; }} // Driver Codeint main(){ N = 4; addEdge(1, 2, 1); addEdge(2, 3, 2); addEdge(3, 4, 3); printFrequencies(); return 0;} // Java Program to implement// the above approachimport java.util.*;class GFG{ // Number of nodesstatic int N; // Structure of a Nodestatic class Node{ int node; int edgeLabel; public Node(int node, int edgeLabel) { super(); this.node = node; this.edgeLabel = edgeLabel; }}; // Adjacency List to// represent the Treestatic Vector<Node> []adj = new Vector[100005]; // Stores the frequencies// of every edgestatic int []freq; // Function to perform DFSstatic int dfs(int u , int p){ // Add the current node to // size of subtree rooted at u int sz = 1; // Iterate over its children for (Node a : adj[u]) { // Check if child is not parent if (a.node != p) { // Get the subtree size // for the child int val = dfs(a.node, u); // Set the frequency // of the current edge freq[a.edgeLabel] = val * (N - val); // Add the subtree size // to itself sz += val; } } // Return the subtree size return sz;} // Function to add edge between nodesstatic void addEdge(int u, int v, int label){ adj[u].add(new Node( v, label )); adj[v].add(new Node( u, label));} // Function to print the frequencies// of each edge in all possible pathsstatic void printFrequencies(){ // Stores the frequency // of all the edges freq = new int[N]; // Perform DFS dfs(1, 1); for (int i = 1; i < N; i++) { System.out.print(freq[i] + " "); }} // Driver Codepublic static void main(String[] args){ N = 4; for (int i = 0; i < adj.length; i++) adj[i] = new Vector<Node>(); addEdge(1, 2, 1); addEdge(2, 3, 2); addEdge(3, 4, 3); printFrequencies();}} // This code is contributed by shikhasingrajput # Python3 program to implement# the above approach # Number of nodesN = 4 # Structure of a Nodeclass Node: def __init__(self, v, label): self.node = v self.edgeLabel = label # Adjacency list to# represent the Treeadj = []for i in range(100005): adj.append([]) # Stores the frequencies# of each edgefreq = [0] * N # Function to perform DFSdef dfs(u = 1, p = 1): global N # Add the current node to # size of subtree rooted at u sz = 1 # Iterate over its children for a in adj[u]: # Check if child is not parent if a.node != p: # Get the subtree size # for the child val = dfs(a.node, u) # Set the frequency # of the current edge freq[a.edgeLabel] = val * (N - val) # Add the subtree size # to itself sz += val # Return the subtree size return sz # Function to add edge between nodesdef addEdge(u, v, label): adj[u].append(Node(v, label)) adj[v].append(Node(u, label)) # Function to print the frequencies# of each edge in all possible pathsdef printFrequencies(): # Stores the frequency # of all the edges global N # Perform DFS dfs() for i in range(1, N): print(freq[i], end = " ") # Driver codeN = 4addEdge(1, 2, 1)addEdge(2, 3, 2)addEdge(3, 4, 3) printFrequencies() # This code is contributed by Stuti Pathak // C# Program to implement// the above approachusing System;using System.Collections.Generic;class GFG{ // Number of nodesstatic int N; // Structure of a Nodepublic class Node{ public int node; public int edgeLabel; public Node(int node, int edgeLabel) { this.node = node; this.edgeLabel = edgeLabel; }}; // Adjacency List to// represent the Treestatic List<Node> []adj = new List<Node>[100005]; // Stores the frequencies// of every edgestatic int []freq; // Function to perform DFSstatic int dfs(int u, int p){ // Add the current node to // size of subtree rooted at u int sz = 1; // Iterate over its children foreach (Node a in adj[u]) { // Check if child is not parent if (a.node != p) { // Get the subtree size // for the child int val = dfs(a.node, u); // Set the frequency // of the current edge freq[a.edgeLabel] = val * (N - val); // Add the subtree size // to itself sz += val; } } // Return the subtree size return sz;} // Function to add edge between nodesstatic void addEdge(int u, int v, int label){ adj[u].Add(new Node(v, label)); adj[v].Add(new Node(u, label));} // Function to print the frequencies// of each edge in all possible pathsstatic void printFrequencies(){ // Stores the frequency // of all the edges freq = new int[N]; // Perform DFS dfs(1, 1); for (int i = 1; i < N; i++) { Console.Write(freq[i] + " "); }} // Driver Codepublic static void Main(String[] args){ N = 4; for (int i = 0; i < adj.Length; i++) adj[i] = new List<Node>(); addEdge(1, 2, 1); addEdge(2, 3, 2); addEdge(3, 4, 3); printFrequencies();}} // This code is contributed by gauravrajput1 <script> // Javascript Program to implement the above approach // Number of nodes let N; // Structure of a Node class Node { constructor(node, edgeLabel) { this.node = node; this.edgeLabel = edgeLabel; } } // Adjacency List to // represent the Tree let adj = new Array(100005); // Stores the frequencies // of every edge let freq; // Function to perform DFS function dfs(u, p) { // Add the current node to // size of subtree rooted at u let sz = 1; // Iterate over its children for (let a = 0; a < adj[u].length; a++) { // Check if child is not parent if (adj[u][a].node != p) { // Get the subtree size // for the child let val = dfs(adj[u][a].node, u); // Set the frequency // of the current edge freq[adj[u][a].edgeLabel] = val * (N - val); // Add the subtree size // to itself sz += val; } } // Return the subtree size return sz; } // Function to add edge between nodes function addEdge(u, v, label) { adj[u].push(new Node( v, label )); adj[v].push(new Node( u, label)); } // Function to print the frequencies // of each edge in all possible paths function printFrequencies() { // Stores the frequency // of all the edges freq = new Array(N); // Perform DFS dfs(1, 1); for (let i = 1; i < N; i++) { document.write(freq[i] + " "); } } N = 4; for (let i = 0; i < adj.length; i++) adj[i] = []; addEdge(1, 2, 1); addEdge(2, 3, 2); addEdge(3, 4, 3); printFrequencies(); </script> 3 4 3 Time Complexity: O(N) Auxiliary Space: O(N) stutipathak31jan shikhasingrajput GauravRajput1 divyesh072019 surindertarika1234 DFS frequency-counting Data Structures Graph Hash Tree Data Structures Hash DFS Graph Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Sep, 2021" }, { "code": null, "e": 256, "s": 52, "text": "Given an Undirected Connected Graph in the form of a tree consisting of N nodes and (N – 1) edges, the task for each edge is to count the number of times it appears across all possible paths in the Tree." }, { "code": null, "e": 266, "s": 256, "text": "Examples:" }, { "code": null, "e": 273, "s": 266, "text": "Input:" }, { "code": null, "e": 685, "s": 273, "text": "Output: 3 4 3 Explanation: All possible paths of a given tree are {(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)} Edge 1 occurs in the paths {(1, 2), (1, 3), (1, 4)}. Therefore, the frequency of the edge is 3. Edge 2 occurs in the paths {(1, 3), (1, 4), (2, 3), (2, 4)}. Therefore, the frequency of the edge is 4. Edge 3 occurs in the paths {(1, 4), (2, 4), (3, 4)}. Therefore, the frequency of the edge is 3. " }, { "code": null, "e": 692, "s": 685, "text": "Input:" }, { "code": null, "e": 1151, "s": 692, "text": "Output: 4 6 4 4 Explanation: Edge 1 occurs in the paths {(1, 2), (1, 3), (1, 4), (1, 5)}. Therefore, the frequency of the edge is 4 Edge 2 occurs in the paths {(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5)}. Therefore, the frequency of the edge is 6 Edge 3 occurs in the paths {(1, 4), (2, 4), (3, 4), (4, 5)}. Therefore, the frequency of the edge is 4 Edge 4 occurs in the paths {(1, 5), (2, 5), (3, 5), (4, 5)}. Therefore, the frequency of the edge is 4 " }, { "code": null, "e": 1371, "s": 1151, "text": "Naive Approach: The simplest approach is to generate all possible paths from each node of the given graph and store the count of edges occurring in these paths by a HashMap. Finally, print the frequencies of each edge. " }, { "code": null, "e": 1417, "s": 1371, "text": "Time Complexity: O(N2) Auxiliary Space: O(N) " }, { "code": null, "e": 1513, "s": 1417, "text": "Efficient Approach: To optimize the above approach, the following observation needs to be made:" }, { "code": null, "e": 1785, "s": 1513, "text": "The green-colored edge will appear in all the paths that connect any vertex from the subtree on its left to any vertex from the subtree on its right. Therefore, the number of paths in which the edge occurs = Product of the count of nodes in the two subtrees = 5 * 3 = 15." }, { "code": null, "e": 1841, "s": 1785, "text": "Follow the steps below in order to solve the problem: " }, { "code": null, "e": 1884, "s": 1841, "text": "Root the tree at any random vertex, say 1." }, { "code": null, "e": 1966, "s": 1884, "text": "Perform DFS at Root. Using DFS calculate the subtree size connected to the edges." }, { "code": null, "e": 2054, "s": 1966, "text": "The frequency of each edge connected to subtree is (subtree size) * (N – subtree size)." }, { "code": null, "e": 2208, "s": 2054, "text": "Store the value calculated above for each node in a HashMap. Finally, after complete the traversal of the tree, traverse the HashMap to print the result." }, { "code": null, "e": 2259, "s": 2208, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 2263, "s": 2259, "text": "C++" }, { "code": null, "e": 2268, "s": 2263, "text": "Java" }, { "code": null, "e": 2276, "s": 2268, "text": "Python3" }, { "code": null, "e": 2279, "s": 2276, "text": "C#" }, { "code": null, "e": 2290, "s": 2279, "text": "Javascript" }, { "code": "// C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Number of nodesint N; // Structure of a Nodestruct Node { int node; int edgeLabel;}; // Adjacency List to// represent the Treevector<Node> adj[100005]; // Stores the frequencies// of every edgevector<int> freq; // Function to perform DFSint dfs(int u = 1, int p = 1){ // Add the current node to // size of subtree rooted at u int sz = 1; // Iterate over its children for (auto a : adj[u]) { // Check if child is not parent if (a.node != p) { // Get the subtree size // for the child int val = dfs(a.node, u); // Set the frequency // of the current edge freq[a.edgeLabel] = val * (N - val); // Add the subtree size // to itself sz += val; } } // Return the subtree size return sz;} // Function to add edge between nodesvoid addEdge(int u, int v, int label){ adj[u].push_back({ v, label }); adj[v].push_back({ u, label });} // Function to print the frequencies// of each edge in all possible pathsvoid printFrequencies(){ // Stores the frequency // of all the edges freq = vector<int>(N); // Perform DFS dfs(); for (int i = 1; i < N; i++) { cout << freq[i] << \" \"; }} // Driver Codeint main(){ N = 4; addEdge(1, 2, 1); addEdge(2, 3, 2); addEdge(3, 4, 3); printFrequencies(); return 0;}", "e": 3798, "s": 2290, "text": null }, { "code": "// Java Program to implement// the above approachimport java.util.*;class GFG{ // Number of nodesstatic int N; // Structure of a Nodestatic class Node{ int node; int edgeLabel; public Node(int node, int edgeLabel) { super(); this.node = node; this.edgeLabel = edgeLabel; }}; // Adjacency List to// represent the Treestatic Vector<Node> []adj = new Vector[100005]; // Stores the frequencies// of every edgestatic int []freq; // Function to perform DFSstatic int dfs(int u , int p){ // Add the current node to // size of subtree rooted at u int sz = 1; // Iterate over its children for (Node a : adj[u]) { // Check if child is not parent if (a.node != p) { // Get the subtree size // for the child int val = dfs(a.node, u); // Set the frequency // of the current edge freq[a.edgeLabel] = val * (N - val); // Add the subtree size // to itself sz += val; } } // Return the subtree size return sz;} // Function to add edge between nodesstatic void addEdge(int u, int v, int label){ adj[u].add(new Node( v, label )); adj[v].add(new Node( u, label));} // Function to print the frequencies// of each edge in all possible pathsstatic void printFrequencies(){ // Stores the frequency // of all the edges freq = new int[N]; // Perform DFS dfs(1, 1); for (int i = 1; i < N; i++) { System.out.print(freq[i] + \" \"); }} // Driver Codepublic static void main(String[] args){ N = 4; for (int i = 0; i < adj.length; i++) adj[i] = new Vector<Node>(); addEdge(1, 2, 1); addEdge(2, 3, 2); addEdge(3, 4, 3); printFrequencies();}} // This code is contributed by shikhasingrajput", "e": 5617, "s": 3798, "text": null }, { "code": "# Python3 program to implement# the above approach # Number of nodesN = 4 # Structure of a Nodeclass Node: def __init__(self, v, label): self.node = v self.edgeLabel = label # Adjacency list to# represent the Treeadj = []for i in range(100005): adj.append([]) # Stores the frequencies# of each edgefreq = [0] * N # Function to perform DFSdef dfs(u = 1, p = 1): global N # Add the current node to # size of subtree rooted at u sz = 1 # Iterate over its children for a in adj[u]: # Check if child is not parent if a.node != p: # Get the subtree size # for the child val = dfs(a.node, u) # Set the frequency # of the current edge freq[a.edgeLabel] = val * (N - val) # Add the subtree size # to itself sz += val # Return the subtree size return sz # Function to add edge between nodesdef addEdge(u, v, label): adj[u].append(Node(v, label)) adj[v].append(Node(u, label)) # Function to print the frequencies# of each edge in all possible pathsdef printFrequencies(): # Stores the frequency # of all the edges global N # Perform DFS dfs() for i in range(1, N): print(freq[i], end = \" \") # Driver codeN = 4addEdge(1, 2, 1)addEdge(2, 3, 2)addEdge(3, 4, 3) printFrequencies() # This code is contributed by Stuti Pathak", "e": 7144, "s": 5617, "text": null }, { "code": "// C# Program to implement// the above approachusing System;using System.Collections.Generic;class GFG{ // Number of nodesstatic int N; // Structure of a Nodepublic class Node{ public int node; public int edgeLabel; public Node(int node, int edgeLabel) { this.node = node; this.edgeLabel = edgeLabel; }}; // Adjacency List to// represent the Treestatic List<Node> []adj = new List<Node>[100005]; // Stores the frequencies// of every edgestatic int []freq; // Function to perform DFSstatic int dfs(int u, int p){ // Add the current node to // size of subtree rooted at u int sz = 1; // Iterate over its children foreach (Node a in adj[u]) { // Check if child is not parent if (a.node != p) { // Get the subtree size // for the child int val = dfs(a.node, u); // Set the frequency // of the current edge freq[a.edgeLabel] = val * (N - val); // Add the subtree size // to itself sz += val; } } // Return the subtree size return sz;} // Function to add edge between nodesstatic void addEdge(int u, int v, int label){ adj[u].Add(new Node(v, label)); adj[v].Add(new Node(u, label));} // Function to print the frequencies// of each edge in all possible pathsstatic void printFrequencies(){ // Stores the frequency // of all the edges freq = new int[N]; // Perform DFS dfs(1, 1); for (int i = 1; i < N; i++) { Console.Write(freq[i] + \" \"); }} // Driver Codepublic static void Main(String[] args){ N = 4; for (int i = 0; i < adj.Length; i++) adj[i] = new List<Node>(); addEdge(1, 2, 1); addEdge(2, 3, 2); addEdge(3, 4, 3); printFrequencies();}} // This code is contributed by gauravrajput1", "e": 8957, "s": 7144, "text": null }, { "code": "<script> // Javascript Program to implement the above approach // Number of nodes let N; // Structure of a Node class Node { constructor(node, edgeLabel) { this.node = node; this.edgeLabel = edgeLabel; } } // Adjacency List to // represent the Tree let adj = new Array(100005); // Stores the frequencies // of every edge let freq; // Function to perform DFS function dfs(u, p) { // Add the current node to // size of subtree rooted at u let sz = 1; // Iterate over its children for (let a = 0; a < adj[u].length; a++) { // Check if child is not parent if (adj[u][a].node != p) { // Get the subtree size // for the child let val = dfs(adj[u][a].node, u); // Set the frequency // of the current edge freq[adj[u][a].edgeLabel] = val * (N - val); // Add the subtree size // to itself sz += val; } } // Return the subtree size return sz; } // Function to add edge between nodes function addEdge(u, v, label) { adj[u].push(new Node( v, label )); adj[v].push(new Node( u, label)); } // Function to print the frequencies // of each edge in all possible paths function printFrequencies() { // Stores the frequency // of all the edges freq = new Array(N); // Perform DFS dfs(1, 1); for (let i = 1; i < N; i++) { document.write(freq[i] + \" \"); } } N = 4; for (let i = 0; i < adj.length; i++) adj[i] = []; addEdge(1, 2, 1); addEdge(2, 3, 2); addEdge(3, 4, 3); printFrequencies(); </script>", "e": 10816, "s": 8957, "text": null }, { "code": null, "e": 10822, "s": 10816, "text": "3 4 3" }, { "code": null, "e": 10869, "s": 10824, "text": "Time Complexity: O(N) Auxiliary Space: O(N) " }, { "code": null, "e": 10886, "s": 10869, "text": "stutipathak31jan" }, { "code": null, "e": 10903, "s": 10886, "text": "shikhasingrajput" }, { "code": null, "e": 10917, "s": 10903, "text": "GauravRajput1" }, { "code": null, "e": 10931, "s": 10917, "text": "divyesh072019" }, { "code": null, "e": 10950, "s": 10931, "text": "surindertarika1234" }, { "code": null, "e": 10954, "s": 10950, "text": "DFS" }, { "code": null, "e": 10973, "s": 10954, "text": "frequency-counting" }, { "code": null, "e": 10989, "s": 10973, "text": "Data Structures" }, { "code": null, "e": 10995, "s": 10989, "text": "Graph" }, { "code": null, "e": 11000, "s": 10995, "text": "Hash" }, { "code": null, "e": 11005, "s": 11000, "text": "Tree" }, { "code": null, "e": 11021, "s": 11005, "text": "Data Structures" }, { "code": null, "e": 11026, "s": 11021, "text": "Hash" }, { "code": null, "e": 11030, "s": 11026, "text": "DFS" }, { "code": null, "e": 11036, "s": 11030, "text": "Graph" }, { "code": null, "e": 11041, "s": 11036, "text": "Tree" } ]
Check whether XOR of all numbers in a given range is even or odd
23 Jun, 2022 Given a range [ L, R ], the task is to find if value of XOR of all natural numbers in range L to R ( both inclusive ) is even or odd. Print ‘Even’ if XOR of all numbers in the range is even, otherwise print odd.Examples: Input: L = 1, R= 10 Output: Odd Input: L= 5, R=15 Output: Even A Simple Solution is to calculate XOR of all numbers in range [L, R] and then check if resultant XOR value is even or odd. Time Complexity of this approach will be O(n).An Efficient Solution is based on the below fact: odd ^ odd = even odd ^ even = odd even ^ odd = odd even ^ even = even XOR of all even numbers will be even ( irrespective of size of range ) and if count of odd numbers is odd then the final XOR will be odd and if even then final XOR will be even.Now, it can be concluded that, If the count of Odd Numbers is even, XOR of all odd numbers = Even XOR of all even numbers = Even Final XOR = Even ^ Even = Even If the count of Odd Numbers is Odd, XOR of all odd numbers = Odd XOR of all even numbers = Even Final XOR = Odd ^ Even = Odd So, all we have to do is to count odd numbers in range L to R.Approach : Count the odd numbers in the range [ L, R ]. Check if count of odd numbers is even or odd. Print ‘Even’ if count is even otherwise print ‘Odd’ . Below is the implementation of above approach: C++ Java C# Python3 PHP Javascript // C++ program to check if XOR of// all numbers in range [L, R]// is Even or odd #include <bits/stdc++.h>using namespace std; // Function to check if XOR of all numbers// in range [L, R] is Even or Odd string isEvenOrOdd(int L, int R){ // Count odd Numbers in range [L, R] int oddCount = (R - L) / 2; if (R % 2 == 1 || L % 2 == 1) oddCount++; // Check if count of odd Numbers // is even or odd if (oddCount % 2 == 0) return "Even"; else return "Odd";} // Driver Codeint main(){ int L = 5, R = 15; cout << isEvenOrOdd(L, R); return 0;} // Java program to check if XOR of// all numbers in range [L, R]// is Even or odd class GFG { // Function to check if XOR of all numbers // in range [L, R] is Even or Odd static String isEvenOrOdd(int L, int R) { // Count odd Numbers in range [L, R] int oddCount = (R - L) / 2; if (R % 2 == 1 || L % 2 == 1) oddCount++; // Check if count of odd Numbers // is even or odd if (oddCount % 2 == 0) return "Even"; else return "Odd"; } // Driver Code public static void main(String[] args) { int L = 5, R = 15; System.out.println(isEvenOrOdd(L, R)); }} // C# program to check if XOR of// all numbers in range [L, R]// is Even or odd using System;class GFG { // Function to check if XOR of all numbers // in range [L, R] is Even or Odd static string isEvenOrOdd(int L, int R) { // Count odd Numbers in range [L, R] int oddCount = (R - L) / 2; if (R % 2 == 1 || L % 2 == 1) oddCount++; // Check if count of odd Numbers // is even or odd if (oddCount % 2 == 0) return "Even"; else return "Odd"; } // Driver Code public static void Main() { int L = 5, R = 15; Console.WriteLine(isEvenOrOdd(L, R)); }} # Python3 program to check if XOR of# all numbers in range [L, R]# is Even or odd # Function to check if XOR of all numbers# in range [L, R] is Even or Odd def isEvenOrOdd( L, R ): # Count odd Numbers in range [L, R] oddCount = (R - L )/2 if( R % 2 == 1 or L % 2 == 1): oddCount = oddCount + 1 # Check if count of odd Numbers # is even or odd if(oddCount % 2 == 0 ): return "Even" else : return "Odd" # Driver Code L = 5R = 15 print(isEvenOrOdd(L, R)); <?php// PHP program to check if XOR of all// numbers in range [L, R] is Even or odd // Function to check if XOR of all numbers// in range [L, R] is Even or Oddfunction isEvenOrOdd($L, $R){ // Count odd Numbers in range [L, R] $oddCount = floor(($R - $L) / 2); if ($R % 2 == 1 || $L % 2 == 1) $oddCount++; // Check if count of odd Numbers // is even or odd if ($oddCount % 2 == 0) return "Even"; else return "Odd";} // Driver Code$L = 5;$R = 15; echo isEvenOrOdd($L, $R); // This code is contributed by Ryuga?> <script>// JavaScript program to check if XOR of// all numbers in range [L, R]// is Even or odd // Function to check if XOR of all numbers// in range [L, R] is Even or Odd function isEvenOrOdd(L, R){ // Count odd Numbers in range [L, R] let oddCount = Math.floor((R - L) / 2); if (R % 2 == 1 || L % 2 == 1) oddCount++; // Check if count of odd Numbers // is even or odd if (oddCount % 2 == 0) return "Even"; else return "Odd";} // Driver Code let L = 5, R = 15; document.write(isEvenOrOdd(L, R)); // This code is contributed by Surbhi Tyagi. </script> Even Time Complexity : O(1), since there is no loop or recursion.Auxiliary Space : O(1), since no extra space has been taken. ankthon muskan_garg surbhityagi15 vansikasharma1329 Bitwise-XOR Competitive Programming Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Jun, 2022" }, { "code": null, "e": 275, "s": 52, "text": "Given a range [ L, R ], the task is to find if value of XOR of all natural numbers in range L to R ( both inclusive ) is even or odd. Print ‘Even’ if XOR of all numbers in the range is even, otherwise print odd.Examples: " }, { "code": null, "e": 340, "s": 275, "text": "Input: L = 1, R= 10 \nOutput: Odd\n\nInput: L= 5, R=15\nOutput: Even" }, { "code": null, "e": 563, "s": 342, "text": "A Simple Solution is to calculate XOR of all numbers in range [L, R] and then check if resultant XOR value is even or odd. Time Complexity of this approach will be O(n).An Efficient Solution is based on the below fact: " }, { "code": null, "e": 633, "s": 563, "text": "odd ^ odd = even\nodd ^ even = odd\neven ^ odd = odd\neven ^ even = even" }, { "code": null, "e": 843, "s": 633, "text": "XOR of all even numbers will be even ( irrespective of size of range ) and if count of odd numbers is odd then the final XOR will be odd and if even then final XOR will be even.Now, it can be concluded that, " }, { "code": null, "e": 972, "s": 843, "text": "If the count of Odd Numbers is even, XOR of all odd numbers = Even XOR of all even numbers = Even Final XOR = Even ^ Even = Even" }, { "code": null, "e": 1097, "s": 972, "text": "If the count of Odd Numbers is Odd, XOR of all odd numbers = Odd XOR of all even numbers = Even Final XOR = Odd ^ Even = Odd" }, { "code": null, "e": 1172, "s": 1097, "text": "So, all we have to do is to count odd numbers in range L to R.Approach : " }, { "code": null, "e": 1217, "s": 1172, "text": "Count the odd numbers in the range [ L, R ]." }, { "code": null, "e": 1263, "s": 1217, "text": "Check if count of odd numbers is even or odd." }, { "code": null, "e": 1317, "s": 1263, "text": "Print ‘Even’ if count is even otherwise print ‘Odd’ ." }, { "code": null, "e": 1366, "s": 1317, "text": "Below is the implementation of above approach: " }, { "code": null, "e": 1370, "s": 1366, "text": "C++" }, { "code": null, "e": 1375, "s": 1370, "text": "Java" }, { "code": null, "e": 1378, "s": 1375, "text": "C#" }, { "code": null, "e": 1386, "s": 1378, "text": "Python3" }, { "code": null, "e": 1390, "s": 1386, "text": "PHP" }, { "code": null, "e": 1401, "s": 1390, "text": "Javascript" }, { "code": "// C++ program to check if XOR of// all numbers in range [L, R]// is Even or odd #include <bits/stdc++.h>using namespace std; // Function to check if XOR of all numbers// in range [L, R] is Even or Odd string isEvenOrOdd(int L, int R){ // Count odd Numbers in range [L, R] int oddCount = (R - L) / 2; if (R % 2 == 1 || L % 2 == 1) oddCount++; // Check if count of odd Numbers // is even or odd if (oddCount % 2 == 0) return \"Even\"; else return \"Odd\";} // Driver Codeint main(){ int L = 5, R = 15; cout << isEvenOrOdd(L, R); return 0;}", "e": 1993, "s": 1401, "text": null }, { "code": "// Java program to check if XOR of// all numbers in range [L, R]// is Even or odd class GFG { // Function to check if XOR of all numbers // in range [L, R] is Even or Odd static String isEvenOrOdd(int L, int R) { // Count odd Numbers in range [L, R] int oddCount = (R - L) / 2; if (R % 2 == 1 || L % 2 == 1) oddCount++; // Check if count of odd Numbers // is even or odd if (oddCount % 2 == 0) return \"Even\"; else return \"Odd\"; } // Driver Code public static void main(String[] args) { int L = 5, R = 15; System.out.println(isEvenOrOdd(L, R)); }}", "e": 2671, "s": 1993, "text": null }, { "code": "// C# program to check if XOR of// all numbers in range [L, R]// is Even or odd using System;class GFG { // Function to check if XOR of all numbers // in range [L, R] is Even or Odd static string isEvenOrOdd(int L, int R) { // Count odd Numbers in range [L, R] int oddCount = (R - L) / 2; if (R % 2 == 1 || L % 2 == 1) oddCount++; // Check if count of odd Numbers // is even or odd if (oddCount % 2 == 0) return \"Even\"; else return \"Odd\"; } // Driver Code public static void Main() { int L = 5, R = 15; Console.WriteLine(isEvenOrOdd(L, R)); }}", "e": 3346, "s": 2671, "text": null }, { "code": "# Python3 program to check if XOR of# all numbers in range [L, R]# is Even or odd # Function to check if XOR of all numbers# in range [L, R] is Even or Odd def isEvenOrOdd( L, R ): # Count odd Numbers in range [L, R] oddCount = (R - L )/2 if( R % 2 == 1 or L % 2 == 1): oddCount = oddCount + 1 # Check if count of odd Numbers # is even or odd if(oddCount % 2 == 0 ): return \"Even\" else : return \"Odd\" # Driver Code L = 5R = 15 print(isEvenOrOdd(L, R));", "e": 3877, "s": 3346, "text": null }, { "code": "<?php// PHP program to check if XOR of all// numbers in range [L, R] is Even or odd // Function to check if XOR of all numbers// in range [L, R] is Even or Oddfunction isEvenOrOdd($L, $R){ // Count odd Numbers in range [L, R] $oddCount = floor(($R - $L) / 2); if ($R % 2 == 1 || $L % 2 == 1) $oddCount++; // Check if count of odd Numbers // is even or odd if ($oddCount % 2 == 0) return \"Even\"; else return \"Odd\";} // Driver Code$L = 5;$R = 15; echo isEvenOrOdd($L, $R); // This code is contributed by Ryuga?>", "e": 4431, "s": 3877, "text": null }, { "code": "<script>// JavaScript program to check if XOR of// all numbers in range [L, R]// is Even or odd // Function to check if XOR of all numbers// in range [L, R] is Even or Odd function isEvenOrOdd(L, R){ // Count odd Numbers in range [L, R] let oddCount = Math.floor((R - L) / 2); if (R % 2 == 1 || L % 2 == 1) oddCount++; // Check if count of odd Numbers // is even or odd if (oddCount % 2 == 0) return \"Even\"; else return \"Odd\";} // Driver Code let L = 5, R = 15; document.write(isEvenOrOdd(L, R)); // This code is contributed by Surbhi Tyagi. </script>", "e": 5037, "s": 4431, "text": null }, { "code": null, "e": 5042, "s": 5037, "text": "Even" }, { "code": null, "e": 5166, "s": 5044, "text": "Time Complexity : O(1), since there is no loop or recursion.Auxiliary Space : O(1), since no extra space has been taken. " }, { "code": null, "e": 5174, "s": 5166, "text": "ankthon" }, { "code": null, "e": 5186, "s": 5174, "text": "muskan_garg" }, { "code": null, "e": 5200, "s": 5186, "text": "surbhityagi15" }, { "code": null, "e": 5218, "s": 5200, "text": "vansikasharma1329" }, { "code": null, "e": 5230, "s": 5218, "text": "Bitwise-XOR" }, { "code": null, "e": 5254, "s": 5230, "text": "Competitive Programming" }, { "code": null, "e": 5267, "s": 5254, "text": "Mathematical" }, { "code": null, "e": 5280, "s": 5267, "text": "Mathematical" } ]
PHP – Mysql LIKE Operator
07 Apr, 2021 Problem Statement : In this article, we are going to display data using LIKE operator with SQL in Xampp server. Here we are going to consider the student address database as an example. Requirements: Xampp Introduction: PHP stands for hypertext preprocessor. It is used as a server-side scripting language and can be used to connect with MySQL server with xampp tool. MySQL is a query language for managing databases. LIKE OPERATOR The LIKE operator in SQL is used in a WHERE clause to search for a specified pattern in a column. There are two wildcards that can be used in conjunction with the LIKE operator. They are: The percent sign (%) which represents zero, one, or multiple charactersThe underscore sign (_) represents one, single character. The percent sign (%) which represents zero, one, or multiple characters The underscore sign (_) represents one, single character. Syntax: SELECT column1, column2, ...,columnn FROM table_name WHERE columnn LIKE pattern; Description letter% = gives the result starts with the given letter Example: Consider the following table: Query: Address starts with h: SELECT * from student_address WHERE saddress LIKE 'h%' Output: Address starts with h: STUDENT-ID : 3 ----- NAME : ojaswi ----- ADDRESS : hyderabad STUDENT-ID : 4 ----- NAME : rohith ----- ADDRESS : hyderabad STUDENT-ID : 5 ----- NAME : gnanesh ----- ADDRESS : hyderabad Query: Name ends with h: SELECT * from student_address WHERE sname LIKE '%h'; Output: Name ends with h: STUDENT-ID : 4 ----- NAME : rohith ----- ADDRESS : hyderabad STUDENT-ID : 5 ----- NAME : gnanesh ----- ADDRESS : hyderabad Query: Address contains “um” pattern SELECT * from student_address WHERE sname LIKE '%um%'; Output: STUDENT-ID : 1 ----- NAME : sravan kumar ----- ADDRESS : kakumanu Query: Address starts with r and ends with h. SELECT * from student_address WHERE sname LIKE 'r%h'; Output: STUDENT-ID : 4 ----- NAME : rohith ----- ADDRESS : hyderabad. Approach: Create database(named database) and create table named student_address Insert data into the table using PHP Write PHP code to perform like operation Observe the results Steps: Start xampp server. Create database named database and create a table named student_address Write PHP code to insert records into it. (data1.php) PHP <?php//servername$servername = "localhost";//username$username = "root";//empty password$password = "";//database is the database name$dbname = "database"; // Create connection by passing these connection parameters$conn = new mysqli($servername, $username, $password, $dbname);// Check this connectionif ($conn->connect_error) { die("Connection failed: " . $conn->connect_error);}//insert records into table$sql = "INSERT INTO student_address VALUES (1,'sravan kumar','kakumanu');";$sql .= "INSERT INTO student_address VALUES (2,'bobby','kakumanu');";$sql .= "INSERT INTO student_address VALUES (3,'ojaswi','hyderabad');";$sql .= "INSERT INTO student_address VALUES (4,'rohith','hyderabad');";$sql .= "INSERT INTO student_address VALUES (5,'gnanesh','hyderabad');"; if ($conn->multi_query($sql) === TRUE) { echo "data stored successfully";} else { echo "Error: " . $sql . "<br>" . $conn->error;} $conn->close();?> open browser and type “localhost.data1.php” to execute it. Output: data stored successfully PHP code demo for like operator for a letter starts with : form.php PHP <html><body><?php//servername$servername = "localhost";//username$username = "root";//empty password$password = "";//database is the database name$dbname = "database"; // Create connection by passing these connection parameters$conn = new mysqli($servername, $username, $password, $dbname);echo "<h1>"; echo "Like operator demo: "; echo"</h1>";echo "<br>";echo "address starts with h:";echo "<br>";echo "<br>";//sql query$sql = "SELECT * from student_address WHERE saddress LIKE 'h%'";$result = $conn->query($sql);//display data on web pagewhile($row = mysqli_fetch_array($result)){ echo " STUDENT-ID : ". $row['sid'], " ----- NAME : ". $row['sname'] ," ----- ADDRESS : ". $row['saddress'] ; echo "<br>"; } echo "<br>";echo "name starts with s ";echo "<br>";echo "<br>";//sql query $sql1 = "SELECT * from student_address WHERE sname LIKE 's%'";$result1 = $conn->query($sql1);//display data on web pagewhile($row = mysqli_fetch_array($result1)){ echo " STUDENT-ID : ". $row['sid'], " ----- NAME : ". $row['sname'] ," ----- ADDRESS : ". $row['saddress'] ; echo "<br>"; } //close the connection $conn->close();?></body></html> Output: localhost/form.php PHP code demo for a letter ends with : form1.php PHP <html><body><?php//servername$servername = "localhost";//username$username = "root";//empty password$password = "";//database is the database name$dbname = "database"; // Create connection by passing these connection parameters$conn = new mysqli($servername, $username, $password, $dbname);echo "<h1>"; echo "Like operator demo: "; echo"</h1>";echo "<br>";echo "name ends with h:";echo "<br>";echo "<br>";//sql query$sql = "SELECT * from student_address WHERE sname LIKE '%h'";$result = $conn->query($sql);//display data on web pagewhile($row = mysqli_fetch_array($result)){ echo " STUDENT-ID : ". $row['sid'], " ----- NAME : ". $row['sname'] ," ----- ADDRESS : ". $row['saddress'] ; echo "<br>"; } echo "<br>";echo "address ends with u ";echo "<br>";echo "<br>";//sql query $sql1 = "SELECT * from student_address WHERE saddress LIKE '%u'";$result1 = $conn->query($sql1);//display data on web pagewhile($row = mysqli_fetch_array($result1)){ echo " STUDENT-ID : ". $row['sid'], " ----- NAME : ". $row['sname'] ," ----- ADDRESS : ". $row['saddress'] ; echo "<br>"; } //close the connection $conn->close();?></body></html> Output: PHP code demo for a substring match and letter starts with-ends with form2.php PHP <html><body><?php//servername$servername = "localhost";//username$username = "root";//empty password$password = "";//database is the database name$dbname = "database"; // Create connection by passing these connection parameters$conn = new mysqli($servername, $username, $password, $dbname);echo "<h1>"; echo "Like operator demo: "; echo"</h1>";echo "<br>";echo "address contains um:";echo "<br>";echo "<br>";//sql query$sql = "SELECT * from student_address WHERE sname LIKE '%um%'";$result = $conn->query($sql);//display data on web pagewhile($row = mysqli_fetch_array($result)){ echo " STUDENT-ID : ". $row['sid'], " ----- NAME : ". $row['sname'] ," ----- ADDRESS : ". $row['saddress'] ; echo "<br>"; } echo "<br>";echo "name starts with r and ends with h ";echo "<br>";echo "<br>";//sql query $sql1 = "SELECT * from student_address WHERE sname LIKE 'r%h'";$result1 = $conn->query($sql1);//display data on web pagewhile($row = mysqli_fetch_array($result1)){ echo " STUDENT-ID : ". $row['sid'], " ----- NAME : ". $row['sname'] ," ----- ADDRESS : ". $row['saddress'] ; echo "<br>"; } //close the connection $conn->close();?></body></html> Output: HTML PHP SQL SQL HTML PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Apr, 2021" }, { "code": null, "e": 48, "s": 28, "text": "Problem Statement :" }, { "code": null, "e": 140, "s": 48, "text": "In this article, we are going to display data using LIKE operator with SQL in Xampp server." }, { "code": null, "e": 214, "s": 140, "text": "Here we are going to consider the student address database as an example." }, { "code": null, "e": 228, "s": 214, "text": "Requirements:" }, { "code": null, "e": 234, "s": 228, "text": "Xampp" }, { "code": null, "e": 248, "s": 234, "text": "Introduction:" }, { "code": null, "e": 396, "s": 248, "text": "PHP stands for hypertext preprocessor. It is used as a server-side scripting language and can be used to connect with MySQL server with xampp tool." }, { "code": null, "e": 446, "s": 396, "text": "MySQL is a query language for managing databases." }, { "code": null, "e": 460, "s": 446, "text": "LIKE OPERATOR" }, { "code": null, "e": 558, "s": 460, "text": "The LIKE operator in SQL is used in a WHERE clause to search for a specified pattern in a column." }, { "code": null, "e": 648, "s": 558, "text": "There are two wildcards that can be used in conjunction with the LIKE operator. They are:" }, { "code": null, "e": 778, "s": 648, "text": "The percent sign (%) which represents zero, one, or multiple charactersThe underscore sign (_) represents one, single character." }, { "code": null, "e": 851, "s": 778, "text": "The percent sign (%) which represents zero, one, or multiple characters" }, { "code": null, "e": 909, "s": 851, "text": "The underscore sign (_) represents one, single character." }, { "code": null, "e": 917, "s": 909, "text": "Syntax:" }, { "code": null, "e": 998, "s": 917, "text": "SELECT column1, column2, ...,columnn\nFROM table_name\nWHERE columnn LIKE pattern;" }, { "code": null, "e": 1010, "s": 998, "text": "Description" }, { "code": null, "e": 1066, "s": 1010, "text": "letter% = gives the result starts with the given letter" }, { "code": null, "e": 1075, "s": 1066, "text": "Example:" }, { "code": null, "e": 1105, "s": 1075, "text": "Consider the following table:" }, { "code": null, "e": 1112, "s": 1105, "text": "Query:" }, { "code": null, "e": 1135, "s": 1112, "text": "Address starts with h:" }, { "code": null, "e": 1191, "s": 1135, "text": "SELECT * from student_address WHERE saddress LIKE 'h%'" }, { "code": null, "e": 1199, "s": 1191, "text": "Output:" }, { "code": null, "e": 1406, "s": 1199, "text": "Address starts with h:\nSTUDENT-ID : 3 ----- NAME : ojaswi ----- ADDRESS : hyderabad\nSTUDENT-ID : 4 ----- NAME : rohith ----- ADDRESS : hyderabad\nSTUDENT-ID : 5 ----- NAME : gnanesh ----- ADDRESS : hyderabad" }, { "code": null, "e": 1413, "s": 1406, "text": "Query:" }, { "code": null, "e": 1431, "s": 1413, "text": "Name ends with h:" }, { "code": null, "e": 1485, "s": 1431, "text": "SELECT * from student_address WHERE sname LIKE '%h';" }, { "code": null, "e": 1493, "s": 1485, "text": "Output:" }, { "code": null, "e": 1634, "s": 1493, "text": "Name ends with h:\nSTUDENT-ID : 4 ----- NAME : rohith ----- ADDRESS : hyderabad\nSTUDENT-ID : 5 ----- NAME : gnanesh ----- ADDRESS : hyderabad" }, { "code": null, "e": 1641, "s": 1634, "text": "Query:" }, { "code": null, "e": 1671, "s": 1641, "text": "Address contains “um” pattern" }, { "code": null, "e": 1727, "s": 1671, "text": "SELECT * from student_address WHERE sname LIKE '%um%';" }, { "code": null, "e": 1735, "s": 1727, "text": "Output:" }, { "code": null, "e": 1801, "s": 1735, "text": "STUDENT-ID : 1 ----- NAME : sravan kumar ----- ADDRESS : kakumanu" }, { "code": null, "e": 1808, "s": 1801, "text": "Query:" }, { "code": null, "e": 1847, "s": 1808, "text": "Address starts with r and ends with h." }, { "code": null, "e": 1902, "s": 1847, "text": "SELECT * from student_address WHERE sname LIKE 'r%h';" }, { "code": null, "e": 1910, "s": 1902, "text": "Output:" }, { "code": null, "e": 1972, "s": 1910, "text": "STUDENT-ID : 4 ----- NAME : rohith ----- ADDRESS : hyderabad." }, { "code": null, "e": 1982, "s": 1972, "text": "Approach:" }, { "code": null, "e": 2053, "s": 1982, "text": "Create database(named database) and create table named student_address" }, { "code": null, "e": 2090, "s": 2053, "text": "Insert data into the table using PHP" }, { "code": null, "e": 2131, "s": 2090, "text": "Write PHP code to perform like operation" }, { "code": null, "e": 2151, "s": 2131, "text": "Observe the results" }, { "code": null, "e": 2158, "s": 2151, "text": "Steps:" }, { "code": null, "e": 2178, "s": 2158, "text": "Start xampp server." }, { "code": null, "e": 2250, "s": 2178, "text": "Create database named database and create a table named student_address" }, { "code": null, "e": 2304, "s": 2250, "text": "Write PHP code to insert records into it. (data1.php)" }, { "code": null, "e": 2308, "s": 2304, "text": "PHP" }, { "code": "<?php//servername$servername = \"localhost\";//username$username = \"root\";//empty password$password = \"\";//database is the database name$dbname = \"database\"; // Create connection by passing these connection parameters$conn = new mysqli($servername, $username, $password, $dbname);// Check this connectionif ($conn->connect_error) { die(\"Connection failed: \" . $conn->connect_error);}//insert records into table$sql = \"INSERT INTO student_address VALUES (1,'sravan kumar','kakumanu');\";$sql .= \"INSERT INTO student_address VALUES (2,'bobby','kakumanu');\";$sql .= \"INSERT INTO student_address VALUES (3,'ojaswi','hyderabad');\";$sql .= \"INSERT INTO student_address VALUES (4,'rohith','hyderabad');\";$sql .= \"INSERT INTO student_address VALUES (5,'gnanesh','hyderabad');\"; if ($conn->multi_query($sql) === TRUE) { echo \"data stored successfully\";} else { echo \"Error: \" . $sql . \"<br>\" . $conn->error;} $conn->close();?>", "e": 3233, "s": 2308, "text": null }, { "code": null, "e": 3292, "s": 3233, "text": "open browser and type “localhost.data1.php” to execute it." }, { "code": null, "e": 3300, "s": 3292, "text": "Output:" }, { "code": null, "e": 3325, "s": 3300, "text": "data stored successfully" }, { "code": null, "e": 3384, "s": 3325, "text": "PHP code demo for like operator for a letter starts with :" }, { "code": null, "e": 3393, "s": 3384, "text": "form.php" }, { "code": null, "e": 3397, "s": 3393, "text": "PHP" }, { "code": "<html><body><?php//servername$servername = \"localhost\";//username$username = \"root\";//empty password$password = \"\";//database is the database name$dbname = \"database\"; // Create connection by passing these connection parameters$conn = new mysqli($servername, $username, $password, $dbname);echo \"<h1>\"; echo \"Like operator demo: \"; echo\"</h1>\";echo \"<br>\";echo \"address starts with h:\";echo \"<br>\";echo \"<br>\";//sql query$sql = \"SELECT * from student_address WHERE saddress LIKE 'h%'\";$result = $conn->query($sql);//display data on web pagewhile($row = mysqli_fetch_array($result)){ echo \" STUDENT-ID : \". $row['sid'], \" ----- NAME : \". $row['sname'] ,\" ----- ADDRESS : \". $row['saddress'] ; echo \"<br>\"; } echo \"<br>\";echo \"name starts with s \";echo \"<br>\";echo \"<br>\";//sql query $sql1 = \"SELECT * from student_address WHERE sname LIKE 's%'\";$result1 = $conn->query($sql1);//display data on web pagewhile($row = mysqli_fetch_array($result1)){ echo \" STUDENT-ID : \". $row['sid'], \" ----- NAME : \". $row['sname'] ,\" ----- ADDRESS : \". $row['saddress'] ; echo \"<br>\"; } //close the connection $conn->close();?></body></html>", "e": 4551, "s": 3397, "text": null }, { "code": null, "e": 4559, "s": 4551, "text": "Output:" }, { "code": null, "e": 4578, "s": 4559, "text": "localhost/form.php" }, { "code": null, "e": 4618, "s": 4578, "text": "PHP code demo for a letter ends with :" }, { "code": null, "e": 4628, "s": 4618, "text": "form1.php" }, { "code": null, "e": 4632, "s": 4628, "text": "PHP" }, { "code": "<html><body><?php//servername$servername = \"localhost\";//username$username = \"root\";//empty password$password = \"\";//database is the database name$dbname = \"database\"; // Create connection by passing these connection parameters$conn = new mysqli($servername, $username, $password, $dbname);echo \"<h1>\"; echo \"Like operator demo: \"; echo\"</h1>\";echo \"<br>\";echo \"name ends with h:\";echo \"<br>\";echo \"<br>\";//sql query$sql = \"SELECT * from student_address WHERE sname LIKE '%h'\";$result = $conn->query($sql);//display data on web pagewhile($row = mysqli_fetch_array($result)){ echo \" STUDENT-ID : \". $row['sid'], \" ----- NAME : \". $row['sname'] ,\" ----- ADDRESS : \". $row['saddress'] ; echo \"<br>\"; } echo \"<br>\";echo \"address ends with u \";echo \"<br>\";echo \"<br>\";//sql query $sql1 = \"SELECT * from student_address WHERE saddress LIKE '%u'\";$result1 = $conn->query($sql1);//display data on web pagewhile($row = mysqli_fetch_array($result1)){ echo \" STUDENT-ID : \". $row['sid'], \" ----- NAME : \". $row['sname'] ,\" ----- ADDRESS : \". $row['saddress'] ; echo \"<br>\"; } //close the connection $conn->close();?></body></html>", "e": 5783, "s": 4632, "text": null }, { "code": null, "e": 5791, "s": 5783, "text": "Output:" }, { "code": null, "e": 5860, "s": 5791, "text": "PHP code demo for a substring match and letter starts with-ends with" }, { "code": null, "e": 5870, "s": 5860, "text": "form2.php" }, { "code": null, "e": 5874, "s": 5870, "text": "PHP" }, { "code": "<html><body><?php//servername$servername = \"localhost\";//username$username = \"root\";//empty password$password = \"\";//database is the database name$dbname = \"database\"; // Create connection by passing these connection parameters$conn = new mysqli($servername, $username, $password, $dbname);echo \"<h1>\"; echo \"Like operator demo: \"; echo\"</h1>\";echo \"<br>\";echo \"address contains um:\";echo \"<br>\";echo \"<br>\";//sql query$sql = \"SELECT * from student_address WHERE sname LIKE '%um%'\";$result = $conn->query($sql);//display data on web pagewhile($row = mysqli_fetch_array($result)){ echo \" STUDENT-ID : \". $row['sid'], \" ----- NAME : \". $row['sname'] ,\" ----- ADDRESS : \". $row['saddress'] ; echo \"<br>\"; } echo \"<br>\";echo \"name starts with r and ends with h \";echo \"<br>\";echo \"<br>\";//sql query $sql1 = \"SELECT * from student_address WHERE sname LIKE 'r%h'\";$result1 = $conn->query($sql1);//display data on web pagewhile($row = mysqli_fetch_array($result1)){ echo \" STUDENT-ID : \". $row['sid'], \" ----- NAME : \". $row['sname'] ,\" ----- ADDRESS : \". $row['saddress'] ; echo \"<br>\"; } //close the connection $conn->close();?></body></html>", "e": 7042, "s": 5874, "text": null }, { "code": null, "e": 7050, "s": 7042, "text": "Output:" }, { "code": null, "e": 7055, "s": 7050, "text": "HTML" }, { "code": null, "e": 7059, "s": 7055, "text": "PHP" }, { "code": null, "e": 7063, "s": 7059, "text": "SQL" }, { "code": null, "e": 7067, "s": 7063, "text": "SQL" }, { "code": null, "e": 7072, "s": 7067, "text": "HTML" }, { "code": null, "e": 7076, "s": 7072, "text": "PHP" } ]
Session Cookies in Node.js
07 Oct, 2021 HTTP protocol: It is the backbone of the internet every single request from the client for particular contains several HTTP headers and that contains all the information of the request. This protocol is the foundation of the data exchange over the internet but the HTTP protocol is the stateless protocol means this protocol cannot be able to maintain the past requests of the particular client to the server. It means we have to give again and again authorized requests in order to move forward to the next page of the particular page of a web application then how to overcome this problem. The answer is cookies and sessions. Cookies and sessions make the HTTP protocol stateful protocol. Session cookies: Session cookies are the temporary cookies that mainly generated on the server-side.The main use of these cookies to track all the request information that has been made by the client overall particular session. The session is stored for a temporary time when the user closes the browser session automatically destroys it. In this article, we will be using external file storage in order to store session cookies. Example of session cookies the most common example of session cookies are an e-commerce website. All e-commerce website initializes a session when a new user starts the particular e-commerce website. When a session is created after successful authorization a unique session id is created on the client-side in the form of a cookie. So that after the first request this generated cookie on the client-side will help for authentication of the user with the session on the client-side and session track all the new request’s information and response the past tracked information to the client. Installing Modules: express.js: Express.js framework used for handling multiple requests. npm install express cookie-parser: The cookie-parser module used to parse the incoming cookies. npm install cookie-parser express-session: This express-session module used for session management in NodeJS. npm install express-session session-file-store: This module helps to create a new file-store for the new session. npm session-file-store Project Structure: Our project structure will look like this: Filename: index.js Javascript // Importing express moduleconst express = require("express") // Importing express-session moduleconst session = require("express-session") // Importing file-store moduleconst filestore = require("session-file-store")(session) const path = require("path") // Setting up the servervar app = express() // Creating session app.use(session({ name: "session-id", secret: "GFGEnter", // Secret key, saveUninitialized: false, resave: false, store: new filestore()})) // Asking for the authorizationfunction auth(req, res, next) { // Checking for the session console.log(req.session) // Checking for the authorization if (!req.session.user) { var authHeader = req.headers.authorization; console.log(authHeader); var err = new Error("You are not authenticated") res.setHeader("WWW-Authenticate", "Basic") err.status = 401 next(err) var auth = new Buffer.from(authHeader.split(' ')[1], "base64").toString().split(":") // Reading username and password var username = auth[0] var password = auth[1] if (username == "admin2" && password == "password") { req.session.user = "admin2" next() } else { // Retry incase of incorrect credentials var err = new Error('You are not authenticated!'); res.setHeader("WWW-Authenticate", "Basic") err.status = 401; return next(err); } } else { if (req.session.user === "admin2") { next() } else { var err = new Error('You are not authenticated!'); res.setHeader("WWW-Authenticate", "Basic") err.status = 401; return next(err); } }} // Middlewaresapp.use(auth)app.use(express.static(path.join(__dirname, 'public'))); // Server setupapp.listen(3000, () => { console.log("Server is Starting")}) Run index.js file using below command: node index.js Open any browser with http://localhost:3000 location in a private window(in order to avoid a saved password and username). A pop will occur near the address bar. Fill in the username and password that are mention in the code as shown below: If the entered username and password match the mention location index.html will render on the browser. Explanation: When we type Run index.js file using node index.js command we will find a response that is given below for new user: After filling in the matched password and username a new session is generated in the directory which keeps track of all the successful requests made by the client. This session file contains all the session records i.e information of the particular client when the client made the first request and many more as shown below: {"cookie":{"originalMaxAge":null, "expires":null,"httpOnly":true,"path":"/"}, "user":"admin","__lastAccess":1610430510130} The server response to the client to set a cookie for this particular session. So when a client makes another request to the server. The request header contains a cookie that contains session-id that has already created on the server-side. The request.headers will look like the following: After successfully matching both cookie session-id and file store session-id server returns skip the authorization in the above code and Render index.html file to the user. Successfully matching session’s id is shown below: Technical Scripter 2020 Node.js Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Oct, 2021" }, { "code": null, "e": 746, "s": 54, "text": "HTTP protocol: It is the backbone of the internet every single request from the client for particular contains several HTTP headers and that contains all the information of the request. This protocol is the foundation of the data exchange over the internet but the HTTP protocol is the stateless protocol means this protocol cannot be able to maintain the past requests of the particular client to the server. It means we have to give again and again authorized requests in order to move forward to the next page of the particular page of a web application then how to overcome this problem. The answer is cookies and sessions. Cookies and sessions make the HTTP protocol stateful protocol. " }, { "code": null, "e": 1767, "s": 746, "text": "Session cookies: Session cookies are the temporary cookies that mainly generated on the server-side.The main use of these cookies to track all the request information that has been made by the client overall particular session. The session is stored for a temporary time when the user closes the browser session automatically destroys it. In this article, we will be using external file storage in order to store session cookies. Example of session cookies the most common example of session cookies are an e-commerce website. All e-commerce website initializes a session when a new user starts the particular e-commerce website. When a session is created after successful authorization a unique session id is created on the client-side in the form of a cookie. So that after the first request this generated cookie on the client-side will help for authentication of the user with the session on the client-side and session track all the new request’s information and response the past tracked information to the client." }, { "code": null, "e": 1787, "s": 1767, "text": "Installing Modules:" }, { "code": null, "e": 1857, "s": 1787, "text": "express.js: Express.js framework used for handling multiple requests." }, { "code": null, "e": 1877, "s": 1857, "text": "npm install express" }, { "code": null, "e": 1953, "s": 1877, "text": "cookie-parser: The cookie-parser module used to parse the incoming cookies." }, { "code": null, "e": 1979, "s": 1953, "text": "npm install cookie-parser" }, { "code": null, "e": 2063, "s": 1979, "text": "express-session: This express-session module used for session management in NodeJS." }, { "code": null, "e": 2091, "s": 2063, "text": "npm install express-session" }, { "code": null, "e": 2177, "s": 2091, "text": "session-file-store: This module helps to create a new file-store for the new session." }, { "code": null, "e": 2200, "s": 2177, "text": "npm session-file-store" }, { "code": null, "e": 2262, "s": 2200, "text": "Project Structure: Our project structure will look like this:" }, { "code": null, "e": 2281, "s": 2262, "text": "Filename: index.js" }, { "code": null, "e": 2292, "s": 2281, "text": "Javascript" }, { "code": "// Importing express moduleconst express = require(\"express\") // Importing express-session moduleconst session = require(\"express-session\") // Importing file-store moduleconst filestore = require(\"session-file-store\")(session) const path = require(\"path\") // Setting up the servervar app = express() // Creating session app.use(session({ name: \"session-id\", secret: \"GFGEnter\", // Secret key, saveUninitialized: false, resave: false, store: new filestore()})) // Asking for the authorizationfunction auth(req, res, next) { // Checking for the session console.log(req.session) // Checking for the authorization if (!req.session.user) { var authHeader = req.headers.authorization; console.log(authHeader); var err = new Error(\"You are not authenticated\") res.setHeader(\"WWW-Authenticate\", \"Basic\") err.status = 401 next(err) var auth = new Buffer.from(authHeader.split(' ')[1], \"base64\").toString().split(\":\") // Reading username and password var username = auth[0] var password = auth[1] if (username == \"admin2\" && password == \"password\") { req.session.user = \"admin2\" next() } else { // Retry incase of incorrect credentials var err = new Error('You are not authenticated!'); res.setHeader(\"WWW-Authenticate\", \"Basic\") err.status = 401; return next(err); } } else { if (req.session.user === \"admin2\") { next() } else { var err = new Error('You are not authenticated!'); res.setHeader(\"WWW-Authenticate\", \"Basic\") err.status = 401; return next(err); } }} // Middlewaresapp.use(auth)app.use(express.static(path.join(__dirname, 'public'))); // Server setupapp.listen(3000, () => { console.log(\"Server is Starting\")})", "e": 4229, "s": 2292, "text": null }, { "code": null, "e": 4268, "s": 4229, "text": "Run index.js file using below command:" }, { "code": null, "e": 4282, "s": 4268, "text": "node index.js" }, { "code": null, "e": 4523, "s": 4282, "text": "Open any browser with http://localhost:3000 location in a private window(in order to avoid a saved password and username). A pop will occur near the address bar. Fill in the username and password that are mention in the code as shown below:" }, { "code": null, "e": 4626, "s": 4523, "text": "If the entered username and password match the mention location index.html will render on the browser." }, { "code": null, "e": 4639, "s": 4626, "text": "Explanation:" }, { "code": null, "e": 4756, "s": 4639, "text": "When we type Run index.js file using node index.js command we will find a response that is given below for new user:" }, { "code": null, "e": 4920, "s": 4756, "text": "After filling in the matched password and username a new session is generated in the directory which keeps track of all the successful requests made by the client." }, { "code": null, "e": 5081, "s": 4920, "text": "This session file contains all the session records i.e information of the particular client when the client made the first request and many more as shown below:" }, { "code": null, "e": 5206, "s": 5081, "text": "{\"cookie\":{\"originalMaxAge\":null,\n \"expires\":null,\"httpOnly\":true,\"path\":\"/\"},\n\"user\":\"admin\",\"__lastAccess\":1610430510130}" }, { "code": null, "e": 5496, "s": 5206, "text": "The server response to the client to set a cookie for this particular session. So when a client makes another request to the server. The request header contains a cookie that contains session-id that has already created on the server-side. The request.headers will look like the following:" }, { "code": null, "e": 5720, "s": 5496, "text": "After successfully matching both cookie session-id and file store session-id server returns skip the authorization in the above code and Render index.html file to the user. Successfully matching session’s id is shown below:" }, { "code": null, "e": 5744, "s": 5720, "text": "Technical Scripter 2020" }, { "code": null, "e": 5752, "s": 5744, "text": "Node.js" }, { "code": null, "e": 5771, "s": 5752, "text": "Technical Scripter" }, { "code": null, "e": 5788, "s": 5771, "text": "Web Technologies" } ]
Flask – Environment
Python 2.6 or higher is usually required for installation of Flask. Although Flask and its dependencies work well with Python 3 (Python 3.3 onwards), many Flask extensions do not support it properly. Hence, it is recommended that Flask should be installed on Python 2.7. virtualenv is a virtual Python environment builder. It helps a user to create multiple Python environments side-by-side. Thereby, it can avoid compatibility issues between the different versions of the libraries. The following command installs virtualenv pip install virtualenv This command needs administrator privileges. Add sudo before pip on Linux/Mac OS. If you are on Windows, log in as Administrator. On Ubuntu virtualenv may be installed using its package manager. Sudo apt-get install virtualenv Once installed, new virtual environment is created in a folder. mkdir newproj cd newproj virtualenv venv To activate corresponding environment, on Linux/OS X, use the following − venv/bin/activate On Windows, following can be used venv\scripts\activate We are now ready to install Flask in this environment. pip install Flask The above command can be run directly, without virtual environment for system-wide installation. 22 Lectures 6 hours Malhar Lathkar 21 Lectures 1.5 hours Jack Chan 16 Lectures 4 hours Malhar Lathkar 54 Lectures 6 hours Srikanth Guskra 88 Lectures 3.5 hours Jorge Escobar 80 Lectures 12 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2304, "s": 2033, "text": "Python 2.6 or higher is usually required for installation of Flask. Although Flask and its dependencies work well with Python 3 (Python 3.3 onwards), many Flask extensions do not support it properly. Hence, it is recommended that Flask should be installed on Python 2.7." }, { "code": null, "e": 2517, "s": 2304, "text": "virtualenv is a virtual Python environment builder. It helps a user to create multiple Python environments side-by-side. Thereby, it can avoid compatibility issues between the different versions of the libraries." }, { "code": null, "e": 2559, "s": 2517, "text": "The following command installs virtualenv" }, { "code": null, "e": 2583, "s": 2559, "text": "pip install virtualenv\n" }, { "code": null, "e": 2778, "s": 2583, "text": "This command needs administrator privileges. Add sudo before pip on Linux/Mac OS. If you are on Windows, log in as Administrator. On Ubuntu virtualenv may be installed using its package manager." }, { "code": null, "e": 2811, "s": 2778, "text": "Sudo apt-get install virtualenv\n" }, { "code": null, "e": 2875, "s": 2811, "text": "Once installed, new virtual environment is created in a folder." }, { "code": null, "e": 2917, "s": 2875, "text": "mkdir newproj\ncd newproj\nvirtualenv venv\n" }, { "code": null, "e": 2991, "s": 2917, "text": "To activate corresponding environment, on Linux/OS X, use the following −" }, { "code": null, "e": 3010, "s": 2991, "text": "venv/bin/activate\n" }, { "code": null, "e": 3044, "s": 3010, "text": "On Windows, following can be used" }, { "code": null, "e": 3067, "s": 3044, "text": "venv\\scripts\\activate\n" }, { "code": null, "e": 3122, "s": 3067, "text": "We are now ready to install Flask in this environment." }, { "code": null, "e": 3141, "s": 3122, "text": "pip install Flask\n" }, { "code": null, "e": 3238, "s": 3141, "text": "The above command can be run directly, without virtual environment for system-wide installation." }, { "code": null, "e": 3271, "s": 3238, "text": "\n 22 Lectures \n 6 hours \n" }, { "code": null, "e": 3287, "s": 3271, "text": " Malhar Lathkar" }, { "code": null, "e": 3322, "s": 3287, "text": "\n 21 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3333, "s": 3322, "text": " Jack Chan" }, { "code": null, "e": 3366, "s": 3333, "text": "\n 16 Lectures \n 4 hours \n" }, { "code": null, "e": 3382, "s": 3366, "text": " Malhar Lathkar" }, { "code": null, "e": 3415, "s": 3382, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 3432, "s": 3415, "text": " Srikanth Guskra" }, { "code": null, "e": 3467, "s": 3432, "text": "\n 88 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3482, "s": 3467, "text": " Jorge Escobar" }, { "code": null, "e": 3516, "s": 3482, "text": "\n 80 Lectures \n 12 hours \n" }, { "code": null, "e": 3539, "s": 3516, "text": " Stone River ELearning" }, { "code": null, "e": 3546, "s": 3539, "text": " Print" }, { "code": null, "e": 3557, "s": 3546, "text": " Add Notes" } ]
Matplotlib.axes.Axes.draw() in Python - GeeksforGeeks
30 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute. The Axes.draw() function in axes module of matplotlib library is used to draw everything. Syntax: Axes.draw(self, renderer=None, inframe=False) Parameters: This method accepts the following parameters. renderer: This parameter is the first parameter and its default value is None. inframe: This parameter contains the boolean value and its default value is false. Returns: This method does not return any value. Below examples illustrate the matplotlib.axes.Axes.draw() function in matplotlib.axes: Example 1: # Implementation of matplotlib function from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt fig, ax = plt.subplots() def tellme(s): ax.set_title(s, fontsize = 16) fig.canvas.draw() renderer = fig.canvas.renderer ax.draw(renderer) tellme('matplotlib.axes.Axes.draw() function Example') plt.show() Output: Example 2: # Implementation of matplotlib function from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111, projection ='3d') X, Y, Z = axes3d.get_test_data(0.1) ax.plot_wireframe(X, Y, Z, rstride = 5, cstride = 5) for angle in range(0, 90): ax.view_init(30, angle) fig.canvas.draw() renderer = fig.canvas.renderer ax.draw(renderer) plt.pause(.001) ax.set_title('matplotlib.axes.Axes.draw()\ function Example', fontweight ="bold") Output: Matplotlib axes-class Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary How to Install PIP on Windows ? Read a file line by line in Python Enumerate() in Python Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Create a Pandas DataFrame from Lists Python String | replace() Reading and Writing to text files in Python
[ { "code": null, "e": 24566, "s": 24538, "text": "\n30 Apr, 2020" }, { "code": null, "e": 24866, "s": 24566, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute." }, { "code": null, "e": 24956, "s": 24866, "text": "The Axes.draw() function in axes module of matplotlib library is used to draw everything." }, { "code": null, "e": 25010, "s": 24956, "text": "Syntax: Axes.draw(self, renderer=None, inframe=False)" }, { "code": null, "e": 25068, "s": 25010, "text": "Parameters: This method accepts the following parameters." }, { "code": null, "e": 25147, "s": 25068, "text": "renderer: This parameter is the first parameter and its default value is None." }, { "code": null, "e": 25230, "s": 25147, "text": "inframe: This parameter contains the boolean value and its default value is false." }, { "code": null, "e": 25278, "s": 25230, "text": "Returns: This method does not return any value." }, { "code": null, "e": 25365, "s": 25278, "text": "Below examples illustrate the matplotlib.axes.Axes.draw() function in matplotlib.axes:" }, { "code": null, "e": 25376, "s": 25365, "text": "Example 1:" }, { "code": "# Implementation of matplotlib function from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt fig, ax = plt.subplots() def tellme(s): ax.set_title(s, fontsize = 16) fig.canvas.draw() renderer = fig.canvas.renderer ax.draw(renderer) tellme('matplotlib.axes.Axes.draw() function Example') plt.show() ", "e": 25718, "s": 25376, "text": null }, { "code": null, "e": 25726, "s": 25718, "text": "Output:" }, { "code": null, "e": 25737, "s": 25726, "text": "Example 2:" }, { "code": "# Implementation of matplotlib function from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111, projection ='3d') X, Y, Z = axes3d.get_test_data(0.1) ax.plot_wireframe(X, Y, Z, rstride = 5, cstride = 5) for angle in range(0, 90): ax.view_init(30, angle) fig.canvas.draw() renderer = fig.canvas.renderer ax.draw(renderer) plt.pause(.001) ax.set_title('matplotlib.axes.Axes.draw()\\ function Example', fontweight =\"bold\") ", "e": 26275, "s": 25737, "text": null }, { "code": null, "e": 26283, "s": 26275, "text": "Output:" }, { "code": null, "e": 26305, "s": 26283, "text": "Matplotlib axes-class" }, { "code": null, "e": 26323, "s": 26305, "text": "Python-matplotlib" }, { "code": null, "e": 26330, "s": 26323, "text": "Python" }, { "code": null, "e": 26428, "s": 26330, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26437, "s": 26428, "text": "Comments" }, { "code": null, "e": 26450, "s": 26437, "text": "Old Comments" }, { "code": null, "e": 26468, "s": 26450, "text": "Python Dictionary" }, { "code": null, "e": 26500, "s": 26468, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26535, "s": 26500, "text": "Read a file line by line in Python" }, { "code": null, "e": 26557, "s": 26535, "text": "Enumerate() in Python" }, { "code": null, "e": 26587, "s": 26557, "text": "Iterate over a list in Python" }, { "code": null, "e": 26629, "s": 26587, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26672, "s": 26629, "text": "Python program to convert a list to string" }, { "code": null, "e": 26709, "s": 26672, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 26735, "s": 26709, "text": "Python String | replace()" } ]
Calculate Maximum Likelihood Estimator with Newton-Raphson Method using R | by Raden Aurelius Andhika Viadinugroho | Towards Data Science
Motivation In statistical modeling, we have to calculate the estimator to determine the equation of your model. The problem is, the estimator itself is difficult to calculate, especially when it involves some distributions like Beta, Gamma, or even Gompertz distribution. Maximum Likelihood Estimator (MLE) is one of many methods to calculate the estimator for those distributions. In this article, I will give you some examples to calculate MLE with the Newton-Raphson method using R. The Concept: MLE First, we consider as independent and identically distributed (iid) random variables with Probability Distribution Function (PDF) where parameter θ is unknown. The basis of this method is the likelihood function given by The log of this function — namely, the log-likelihood function — is denoted by To determine the MLE, we determine the critical value of the log-likelihood function; that is, the MLE solves the equation The Concept: Newton-Raphson Method Newton-Raphson method is an iterative procedure to calculate the roots of function f. In this method, we want to approximate the roots of the function by calculating where x_{n+1} are the (n+1)-th iteration. The goal of this method is to make the approximated result as close as possible with the exact result (that is, the roots of the function). Putting it Together: Newton-Raphson Method for Calculating MLE The Newton-Raphson method can be applied to generate a sequence that converges to the MLE. If we assume θ as a k×1 vector, we can iterate where l’(θ) is the gradient vector of the log-likelihood function, and l’’(θ) is the Hessian of the log-likelihood function. Implementation in R For the implementation, suppose that we have and we want to estimate μ by using MLE. We know that the PDF of the Poisson distribution is The likelihood function can be written as follows. From the likelihood function above, we can express the log-likelihood function as follows. In R, we can simply write the log-likelihood function by taking the logarithm of the PDF as follows. #MLE Poisson#PDF : f(x|mu) = (exp(-mu)*(mu^(x))/factorial(x))#mu=tloglik=expression(log((exp(-t)*(t^(x))/factorial(x))))dbt=D(loglik,"t")dbtt=D(dbt,"t") Then, we calculate the first and second partial derivative of the log-likelihood function with respect to μ (then μ for the second one) by running dbt=D(loglik,"t") and dbtt=D(dbt,"t") , respectively. The results are as follows. dbt=(exp(-t) * (t^((x) - 1) * (x)) - exp(-t) * (t^(x)))/factorial(x)/(exp(-t) * (t^(x))/factorial(x))dbtt=(exp(-t) * (t^(((x) - 1) - 1) * ((x) - 1) * (x)) - exp(-t) * (t^((x) - 1) * (x)) - (exp(-t) * (t^((x) - 1) * (x)) - exp(-t) * (t^(x))))/factorial(x)/(exp(-t) * (t^(x))/factorial(x)) - (exp(-t) * (t^((x) - 1) * (x)) - exp(-t) * (t^(x)))/factorial(x) * ((exp(-t) * (t^((x) - 1) * (x)) - exp(-t) * (t^(x)))/factorial(x))/(exp(-t) * (t^(x))/factorial(x))^2 Then, we can start to create the Newton-Raphson method function in R. First, we generate the random number that Poisson distributed as the data we used to calculate the MLE. For this function, we need these parameters as follows. n for the number of generated data that Poisson distributed, t for the μ value, and iter for the number of iteration for the Newton-Raphson method. Since the MLE of Poisson distribution for the mean is μ, then we can write the first lines of codes for the function as follows. x=rpois(n,t)x.mean=mean(x)par.hat=matrix(0,1,1)estimate=c(rep(NULL,iter+1))difference=c(rep(NULL,iter+1))estimate[1]=tdifference[1]=abs(t-x.mean) Then, we create the loop function to calculate the sum of the partial derivatives (which is why we just need to write the logarithm of the PDF for the log-likelihood function in R), the gradient vector, the Hessian matrix, and the MLE approximated value as follows. for(i in 1:iter) { #First partial derivative of log-likelihood function with respect to mu dbt=(exp(-t) * (t^((x) - 1) * (x)) - exp(-t) * (t^(x)))/factorial(x)/(exp(-t) * (t^(x))/factorial(x)) #Second partial derivative of log-likelihood function with respect to mu, then mu dbtt=(exp(-t) * (t^(((x) - 1) - 1) * ((x) - 1) * (x)) - exp(-t) * (t^((x) - 1) * (x)) - (exp(-t) * (t^((x) - 1) * (x)) - exp(-t) * (t^(x))))/factorial(x)/(exp(-t) * (t^(x))/factorial(x)) - (exp(-t) * (t^((x) - 1) * (x)) - exp(-t) * (t^(x)))/factorial(x) * ((exp(-t) * (t^((x) - 1) * (x)) - exp(-t) * (t^(x)))/factorial(x))/(exp(-t) * (t^(x))/factorial(x))^2 sdbt=sum(dbt) sdbtt=sum(dbtt) #hessian matrix h=matrix(sdbtt,1,1) #gradient vector g=matrix(sdbt,1,1) #parameter par=matrix(t,1,1) par.hat=par-solve(h)%*%g t=par.hat[1,] estimate[i+1]=t difference[i+1]=t-x.mean } When the iteration reaches the limit, we need to calculate the difference of the actual and approximated value of MLE in each iteration to evaluate the Newton-Raphson method performance for calculating the MLE. The rule is simple: smaller difference, better performance. We can write it as the last lines of codes in our function as follows. tabel=data.frame(estimate,difference)rownames(tabel)=(c("Initiation",1:iter))print(x)print(tabel)cat("The real MLE value for mu is :",x.mean,"\n")cat("The approximated MLE value for mu is",t,"\n") The complete function would be written as follows. nr.poi=function(n,t,iter=100){ x=rpois(n,t) x.mean=mean(x) par.hat=matrix(0,1,1) estimate=c(rep(NULL,iter+1)) difference=c(rep(NULL,iter+1)) estimate[1]=t difference[1]=abs(t-x.mean) for(i in 1:iter) { #First partial derivative of log-likelihood function with respect to mu dbt=(exp(-t) * (t^((x) - 1) * (x)) - exp(-t) * (t^(x)))/factorial(x)/(exp(-t) * (t^(x))/factorial(x)) #Second partial derivative of log-likelihood function with respect to mu, then mu dbtt=(exp(-t) * (t^(((x) - 1) - 1) * ((x) - 1) * (x)) - exp(-t) * (t^((x) - 1) * (x)) - (exp(-t) * (t^((x) - 1) * (x)) - exp(-t) * (t^(x))))/factorial(x)/(exp(-t) * (t^(x))/factorial(x)) - (exp(-t) * (t^((x) - 1) * (x)) - exp(-t) * (t^(x)))/factorial(x) * ((exp(-t) * (t^((x) - 1) * (x)) - exp(-t) * (t^(x)))/factorial(x))/(exp(-t) * (t^(x))/factorial(x))^2 sdbt=sum(dbt) sdbtt=sum(dbtt) #hessian matrix h=matrix(sdbtt,1,1) #gradient vector g=matrix(sdbt,1,1) #parameter par=matrix(t,1,1) par.hat=par-solve(h)%*%g t=par.hat[1,] estimate[i+1]=t difference[i+1]=t-x.mean } tabel=data.frame(estimate,difference) rownames(tabel)=(c("Initiation",1:iter)) print(x) print(tabel) cat("The real MLE value for mu is :",x.mean,"\n") cat("The approximated MLE value for mu is",t,"\n")} For the example of this function implementation, suppose that we want to calculate the MLE of 100 Poisson-distributed data with the mean of 5. By using the Newton-Raphson method function that has been written above with the number of the iteration is 5, the result as follows. > nr.poi(100,5,5)[1] 5 4 6 9 7 8 7 2 9 4 5 6 10 1 4 8 5 7 4 3 6 3 4 4 4 7 6 6 3 6 5 5 6 4 5 5 9 5[39] 5 3 5 6 5 8 5 3 3 12 6 5 3 4 8 5 4 5 7 8 8 5 7 2 8 3 6 4 2 3 7 5 3 4 6 5 2 6[77] 3 3 5 4 8 2 4 7 6 5 4 3 4 7 3 4 6 6 4 7 4 4 14 4 estimate differenceInitiation 5.000000 2.400000e-011 5.229008 -1.099237e-022 5.239977 -2.305956e-053 5.240000 -1.014779e-104 5.240000 0.000000e+005 5.240000 0.000000e+00The real MLE value for mu is : 5.24 The approximated MLE value for mu is 5.24 From the result above, we can see that the Newton-Raphson method MLE produces the same result as the real MLE value. Please note that this method is using the generated data, so the result might be different in every run. Conclusion The MLE can help us to calculate the estimator based on their log-likelihood function. We can numerically approach the estimator result from MLE by using the Newton-Raphson method. And here we are, you now can calculate the MLE with the Newton-Raphson method by using R! For more discussions about this topic, feel free to contact me via LinkedIn here. References: [1] Robert V. Hogg, Joseph W. McKean, and Allen T. Craig, Introduction to Mathematical Statistics, Seventh Edition (2013), Pearson Education. [2] Adi Ben-Israel, A Newton-Raphson method for the solution of systems of equations (1966), Journal of Mathematical Analysis and Applications.
[ { "code": null, "e": 183, "s": 172, "text": "Motivation" }, { "code": null, "e": 444, "s": 183, "text": "In statistical modeling, we have to calculate the estimator to determine the equation of your model. The problem is, the estimator itself is difficult to calculate, especially when it involves some distributions like Beta, Gamma, or even Gompertz distribution." }, { "code": null, "e": 658, "s": 444, "text": "Maximum Likelihood Estimator (MLE) is one of many methods to calculate the estimator for those distributions. In this article, I will give you some examples to calculate MLE with the Newton-Raphson method using R." }, { "code": null, "e": 675, "s": 658, "text": "The Concept: MLE" }, { "code": null, "e": 694, "s": 675, "text": "First, we consider" }, { "code": null, "e": 805, "s": 694, "text": "as independent and identically distributed (iid) random variables with Probability Distribution Function (PDF)" }, { "code": null, "e": 896, "s": 805, "text": "where parameter θ is unknown. The basis of this method is the likelihood function given by" }, { "code": null, "e": 975, "s": 896, "text": "The log of this function — namely, the log-likelihood function — is denoted by" }, { "code": null, "e": 1098, "s": 975, "text": "To determine the MLE, we determine the critical value of the log-likelihood function; that is, the MLE solves the equation" }, { "code": null, "e": 1133, "s": 1098, "text": "The Concept: Newton-Raphson Method" }, { "code": null, "e": 1299, "s": 1133, "text": "Newton-Raphson method is an iterative procedure to calculate the roots of function f. In this method, we want to approximate the roots of the function by calculating" }, { "code": null, "e": 1481, "s": 1299, "text": "where x_{n+1} are the (n+1)-th iteration. The goal of this method is to make the approximated result as close as possible with the exact result (that is, the roots of the function)." }, { "code": null, "e": 1544, "s": 1481, "text": "Putting it Together: Newton-Raphson Method for Calculating MLE" }, { "code": null, "e": 1682, "s": 1544, "text": "The Newton-Raphson method can be applied to generate a sequence that converges to the MLE. If we assume θ as a k×1 vector, we can iterate" }, { "code": null, "e": 1807, "s": 1682, "text": "where l’(θ) is the gradient vector of the log-likelihood function, and l’’(θ) is the Hessian of the log-likelihood function." }, { "code": null, "e": 1827, "s": 1807, "text": "Implementation in R" }, { "code": null, "e": 1872, "s": 1827, "text": "For the implementation, suppose that we have" }, { "code": null, "e": 1964, "s": 1872, "text": "and we want to estimate μ by using MLE. We know that the PDF of the Poisson distribution is" }, { "code": null, "e": 2015, "s": 1964, "text": "The likelihood function can be written as follows." }, { "code": null, "e": 2106, "s": 2015, "text": "From the likelihood function above, we can express the log-likelihood function as follows." }, { "code": null, "e": 2207, "s": 2106, "text": "In R, we can simply write the log-likelihood function by taking the logarithm of the PDF as follows." }, { "code": null, "e": 2360, "s": 2207, "text": "#MLE Poisson#PDF : f(x|mu) = (exp(-mu)*(mu^(x))/factorial(x))#mu=tloglik=expression(log((exp(-t)*(t^(x))/factorial(x))))dbt=D(loglik,\"t\")dbtt=D(dbt,\"t\")" }, { "code": null, "e": 2589, "s": 2360, "text": "Then, we calculate the first and second partial derivative of the log-likelihood function with respect to μ (then μ for the second one) by running dbt=D(loglik,\"t\") and dbtt=D(dbt,\"t\") , respectively. The results are as follows." }, { "code": null, "e": 3080, "s": 2589, "text": "dbt=(exp(-t) * (t^((x) - 1) * (x)) - exp(-t) * (t^(x)))/factorial(x)/(exp(-t) * (t^(x))/factorial(x))dbtt=(exp(-t) * (t^(((x) - 1) - 1) * ((x) - 1) * (x)) - exp(-t) * (t^((x) - 1) * (x)) - (exp(-t) * (t^((x) - 1) * (x)) - exp(-t) * (t^(x))))/factorial(x)/(exp(-t) * (t^(x))/factorial(x)) - (exp(-t) * (t^((x) - 1) * (x)) - exp(-t) * (t^(x)))/factorial(x) * ((exp(-t) * (t^((x) - 1) * (x)) - exp(-t) * (t^(x)))/factorial(x))/(exp(-t) * (t^(x))/factorial(x))^2" }, { "code": null, "e": 3310, "s": 3080, "text": "Then, we can start to create the Newton-Raphson method function in R. First, we generate the random number that Poisson distributed as the data we used to calculate the MLE. For this function, we need these parameters as follows." }, { "code": null, "e": 3371, "s": 3310, "text": "n for the number of generated data that Poisson distributed," }, { "code": null, "e": 3394, "s": 3371, "text": "t for the μ value, and" }, { "code": null, "e": 3458, "s": 3394, "text": "iter for the number of iteration for the Newton-Raphson method." }, { "code": null, "e": 3587, "s": 3458, "text": "Since the MLE of Poisson distribution for the mean is μ, then we can write the first lines of codes for the function as follows." }, { "code": null, "e": 3733, "s": 3587, "text": "x=rpois(n,t)x.mean=mean(x)par.hat=matrix(0,1,1)estimate=c(rep(NULL,iter+1))difference=c(rep(NULL,iter+1))estimate[1]=tdifference[1]=abs(t-x.mean)" }, { "code": null, "e": 3999, "s": 3733, "text": "Then, we create the loop function to calculate the sum of the partial derivatives (which is why we just need to write the logarithm of the PDF for the log-likelihood function in R), the gradient vector, the Hessian matrix, and the MLE approximated value as follows." }, { "code": null, "e": 4947, "s": 3999, "text": "for(i in 1:iter) { #First partial derivative of log-likelihood function with respect to mu dbt=(exp(-t) * (t^((x) - 1) * (x)) - exp(-t) * (t^(x)))/factorial(x)/(exp(-t) * (t^(x))/factorial(x)) #Second partial derivative of log-likelihood function with respect to mu, then mu dbtt=(exp(-t) * (t^(((x) - 1) - 1) * ((x) - 1) * (x)) - exp(-t) * (t^((x) - 1) * (x)) - (exp(-t) * (t^((x) - 1) * (x)) - exp(-t) * (t^(x))))/factorial(x)/(exp(-t) * (t^(x))/factorial(x)) - (exp(-t) * (t^((x) - 1) * (x)) - exp(-t) * (t^(x)))/factorial(x) * ((exp(-t) * (t^((x) - 1) * (x)) - exp(-t) * (t^(x)))/factorial(x))/(exp(-t) * (t^(x))/factorial(x))^2 sdbt=sum(dbt) sdbtt=sum(dbtt) #hessian matrix h=matrix(sdbtt,1,1) #gradient vector g=matrix(sdbt,1,1) #parameter par=matrix(t,1,1) par.hat=par-solve(h)%*%g t=par.hat[1,] estimate[i+1]=t difference[i+1]=t-x.mean }" }, { "code": null, "e": 5289, "s": 4947, "text": "When the iteration reaches the limit, we need to calculate the difference of the actual and approximated value of MLE in each iteration to evaluate the Newton-Raphson method performance for calculating the MLE. The rule is simple: smaller difference, better performance. We can write it as the last lines of codes in our function as follows." }, { "code": null, "e": 5486, "s": 5289, "text": "tabel=data.frame(estimate,difference)rownames(tabel)=(c(\"Initiation\",1:iter))print(x)print(tabel)cat(\"The real MLE value for mu is :\",x.mean,\"\\n\")cat(\"The approximated MLE value for mu is\",t,\"\\n\")" }, { "code": null, "e": 5537, "s": 5486, "text": "The complete function would be written as follows." }, { "code": null, "e": 6885, "s": 5537, "text": "nr.poi=function(n,t,iter=100){ x=rpois(n,t) x.mean=mean(x) par.hat=matrix(0,1,1) estimate=c(rep(NULL,iter+1)) difference=c(rep(NULL,iter+1)) estimate[1]=t difference[1]=abs(t-x.mean) for(i in 1:iter) { #First partial derivative of log-likelihood function with respect to mu dbt=(exp(-t) * (t^((x) - 1) * (x)) - exp(-t) * (t^(x)))/factorial(x)/(exp(-t) * (t^(x))/factorial(x)) #Second partial derivative of log-likelihood function with respect to mu, then mu dbtt=(exp(-t) * (t^(((x) - 1) - 1) * ((x) - 1) * (x)) - exp(-t) * (t^((x) - 1) * (x)) - (exp(-t) * (t^((x) - 1) * (x)) - exp(-t) * (t^(x))))/factorial(x)/(exp(-t) * (t^(x))/factorial(x)) - (exp(-t) * (t^((x) - 1) * (x)) - exp(-t) * (t^(x)))/factorial(x) * ((exp(-t) * (t^((x) - 1) * (x)) - exp(-t) * (t^(x)))/factorial(x))/(exp(-t) * (t^(x))/factorial(x))^2 sdbt=sum(dbt) sdbtt=sum(dbtt) #hessian matrix h=matrix(sdbtt,1,1) #gradient vector g=matrix(sdbt,1,1) #parameter par=matrix(t,1,1) par.hat=par-solve(h)%*%g t=par.hat[1,] estimate[i+1]=t difference[i+1]=t-x.mean } tabel=data.frame(estimate,difference) rownames(tabel)=(c(\"Initiation\",1:iter)) print(x) print(tabel) cat(\"The real MLE value for mu is :\",x.mean,\"\\n\") cat(\"The approximated MLE value for mu is\",t,\"\\n\")}" }, { "code": null, "e": 7162, "s": 6885, "text": "For the example of this function implementation, suppose that we want to calculate the MLE of 100 Poisson-distributed data with the mean of 5. By using the Newton-Raphson method function that has been written above with the number of the iteration is 5, the result as follows." }, { "code": null, "e": 7799, "s": 7162, "text": "> nr.poi(100,5,5)[1] 5 4 6 9 7 8 7 2 9 4 5 6 10 1 4 8 5 7 4 3 6 3 4 4 4 7 6 6 3 6 5 5 6 4 5 5 9 5[39] 5 3 5 6 5 8 5 3 3 12 6 5 3 4 8 5 4 5 7 8 8 5 7 2 8 3 6 4 2 3 7 5 3 4 6 5 2 6[77] 3 3 5 4 8 2 4 7 6 5 4 3 4 7 3 4 6 6 4 7 4 4 14 4 estimate differenceInitiation 5.000000 2.400000e-011 5.229008 -1.099237e-022 5.239977 -2.305956e-053 5.240000 -1.014779e-104 5.240000 0.000000e+005 5.240000 0.000000e+00The real MLE value for mu is : 5.24 The approximated MLE value for mu is 5.24" }, { "code": null, "e": 8021, "s": 7799, "text": "From the result above, we can see that the Newton-Raphson method MLE produces the same result as the real MLE value. Please note that this method is using the generated data, so the result might be different in every run." }, { "code": null, "e": 8032, "s": 8021, "text": "Conclusion" }, { "code": null, "e": 8213, "s": 8032, "text": "The MLE can help us to calculate the estimator based on their log-likelihood function. We can numerically approach the estimator result from MLE by using the Newton-Raphson method." }, { "code": null, "e": 8385, "s": 8213, "text": "And here we are, you now can calculate the MLE with the Newton-Raphson method by using R! For more discussions about this topic, feel free to contact me via LinkedIn here." }, { "code": null, "e": 8397, "s": 8385, "text": "References:" }, { "code": null, "e": 8539, "s": 8397, "text": "[1] Robert V. Hogg, Joseph W. McKean, and Allen T. Craig, Introduction to Mathematical Statistics, Seventh Edition (2013), Pearson Education." } ]
Using GraphSAGE embeddings for downstream classification model | by Tomaz Bratanic | Towards Data Science
The use of knowledge graphs and graph analytics pipeline is getting more and more popular. If you keep an eye on the graph analytics field, you already know that graph neural networks are trending. Unfortunately, there aren’t many tutorials out there on how to use them in a practical application. For this reason, I have decided to write this blog post, where you will learn how to train a convolutional graph neural network and integrate it into your machine learning workflow to improve downstream classification model accuracy. In this example, you will reproduce the protein role classification task from the original GraphSAGE article. The task is to classify protein roles in terms of their cellular function across various protein-protein interaction graphs (PPI). The dataset contains 22 PPI graphs, with each graph corresponding to a different human tissue. The average PPI graph contains 2373 nodes, with an average degree of 28.8. There are available predefined positional gene sets, motif gene sets, and immunological signatures for each protein in the network. Based on those features and their connections, you will predict the roles of proteins in the network. You will train both the classification and GraphSAGE model on 20 graphs and then average prediction F1 scores on two test graphs. As mentioned, we are dealing with a protein-protein interaction network. This is a monopartite network, where nodes represent proteins and relationships represent their interactions. Additionally, the protein nodes have the predefined features stored as a property. The embeddings_all property contains all 50 features stored as a list of floats. I have also prepared the decoupled properties, where the embedding_x property holds a single feature and x ranges from 0 to 49. You will see later in the blog post why the decoupled properties are required. The protein nodes also contain a secondary label that could be either Train or Test. With the help of the secondary label, you can easily perform the train-test data split. To set up the Neo4j environment, you will first need to download and install the Neo4j Desktop application. You don’t need to create a database instance just yet. To avoid bugging you with the import process, I have prepared a database dump file, which you can go ahead and load a database instance from it. In this example, I used the Neo4j 4.2.0 version. If you aren’t familiar with how to load a Neo4j database instance from a dump file, you can take a look at my blog post for more detailed instructions. Next, you will need to install both the APOC and the Graph Data Science libraries. Using the Neo4j Desktop application, you can install both libraries with a single click as shown below. Now that you have loaded the database instance and installed both libraries, you can go ahead and start the database. Run the following query in the Neo4j Browser interface to make sure the graph is loaded correctly. MATCH p=(:Protein)-[:INTERACTS]->(:Protein)RETURN p LIMIT 25 Results You should see a similar visualization in your Neo4j Browser. The green nodes represent the proteins and the relationships represent the interactions between the proteins. You can also notice that a protein can interact with itself. That is represented with self-loops, where the relationship starts and points to the same node. To get a baseline f1 score, you will first train the classification model using only the predefined features available for proteins. The code is identical to the code found in the official GraphSAGE repository, where they used the Stochastic Gradient Descent classifier model to train and predict protein roles. The only difference is that here you will be fetching the data from a Neo4j database instance. The baseline f1 score, where you used only the predefined features of proteins, is 0.422. Let’s now try to improve the classification model accuracy using the GraphSAGE algorithm GraphSAGE is a convolutional graph neural network algorithm. The key idea behind the algorithm is that we learn a function that generates node embeddings by sampling and aggregating feature information from a node’s local neighborhood. As the GraphSAGE algorithm learns a function that can induce the embedding of a node, it can also be used to induce embeddings of a new node that wasn’t observed during the training phase. This is called inductive learning. If you want to learn more about the training process and the math behind the GraphSAGE algorithm, I suggest you take a look at the An Intuitive Explanation of GraphSAGE blog post by Rıza Özçelik or the official GraphSAGE site. Neo4j Graph Data Science library operates entirely on heap memory to enable fast caching for the graph’s topology, containing only relevant nodes, relationships, and weights. Graph algorithms are executed on an in-memory projected graph model, which is separate from Neo4j’s stored graph model. Before you can execute any graph algorithms, you have to project the in-memory graph via the Graph Loader component. You can use either native projection or cypher projection to load the in-memory graph. In this example, you will use the native projection feature to load the in-memory graph. To start, you will project the training data and store it as a named graph in the Graph Catalog. The current implementation of the GraphSAGE algorithm supports only node features that are of type Float. For this reason, you will include the decoupled node properties ranging from embedding_0 to embedding_49 in the graph projection instead of a single property embeddings_all, which holds all the node features in the form of a list of Floats. Additionally, you will treat the projected graph as undirected. UNWIND range(0,49) as iWITH collect('embedding_' + toString(i)) as embeddingsCALL gds.graph.create('train','Train', {INTERACTS:{orientation:'UNDIRECTED'}}, {nodeProperties:embeddings}) YIELD graphName, nodeCount, relationshipCountRETURN graphName, nodeCount, relationshipCount Next, you will train the GraphSAGE model. The model’s hyper-parameter settings were mostly copied from the original paper. I have noticed that the lower learning-rate setting had the most impact on the downstream classification accuracy. Another import hyper-parameter is the samplingSizes parameter, where the size of the list determines the number of layers (defined as K parameter in the paper), and the values determine how many nodes will be sampled by the layers. Find more information about the available hyper-parameters in the documentation. UNWIND range(0,49) as iWITH collect('embedding_' + toString(i)) as embeddingsCALL gds.beta.graphSage.train('train',{ modelName:'proteinModel', aggregator:'pool', batchSize:512, activationFunction:'relu', epochs:10, sampleSizes:[25,10], learningRate:0.0000001, embeddingDimension:256, featureProperties:embeddings})YIELD modelInfoRETURN modelInfo The training process took around 20 minutes on my laptop. After the training process finishes, the GraphSAGE model will be stored in the model catalog. You can now use this model to induce node embeddings on any projected graph with the same node properties used during the training. Before testing the downstream classification accuracy, you have to load the test data as an in-memory graph in the Graph Catalog. UNWIND range(0,49) as iWITH collect('embedding_' + toString(i)) as embeddingsCALL gds.graph.create('test','Test', {INTERACTS:{orientation:'UNDIRECTED'}}, {nodeProperties:embeddings}) YIELD graphName, nodeCount, relationshipCountRETURN graphName, nodeCount, relationshipCount With the GraphSAGE model trained and both the training and test data projected as an in-memory graph, you can go ahead and calculate the f1 score using the GraphSAGE embeddings in a downstream classification model. Remember, the GraphSAGE model has not observed the test data during the training phase. Using the GraphSAGE embeddings as feature input to the classification model, you have improved the f1 score to 0.462. You can also try to follow the other examples in the original GraphSAGE paper to hone your graph data science skills. Connections within your data can help you increase the accuracy of your ML models GraphSAGE algorithm can induce embeddings of new unseen nodes, without the need for re-training process As always, the code is available on GitHub. [1] Hamilton, Will, Zhitao Ying, and Jure Leskovec. “Inductive representation learning on large graphs.” Advances in Neural Information Processing Systems. 2017.
[ { "code": null, "e": 704, "s": 172, "text": "The use of knowledge graphs and graph analytics pipeline is getting more and more popular. If you keep an eye on the graph analytics field, you already know that graph neural networks are trending. Unfortunately, there aren’t many tutorials out there on how to use them in a practical application. For this reason, I have decided to write this blog post, where you will learn how to train a convolutional graph neural network and integrate it into your machine learning workflow to improve downstream classification model accuracy." }, { "code": null, "e": 1479, "s": 704, "text": "In this example, you will reproduce the protein role classification task from the original GraphSAGE article. The task is to classify protein roles in terms of their cellular function across various protein-protein interaction graphs (PPI). The dataset contains 22 PPI graphs, with each graph corresponding to a different human tissue. The average PPI graph contains 2373 nodes, with an average degree of 28.8. There are available predefined positional gene sets, motif gene sets, and immunological signatures for each protein in the network. Based on those features and their connections, you will predict the roles of proteins in the network. You will train both the classification and GraphSAGE model on 20 graphs and then average prediction F1 scores on two test graphs." }, { "code": null, "e": 1662, "s": 1479, "text": "As mentioned, we are dealing with a protein-protein interaction network. This is a monopartite network, where nodes represent proteins and relationships represent their interactions." }, { "code": null, "e": 2206, "s": 1662, "text": "Additionally, the protein nodes have the predefined features stored as a property. The embeddings_all property contains all 50 features stored as a list of floats. I have also prepared the decoupled properties, where the embedding_x property holds a single feature and x ranges from 0 to 49. You will see later in the blog post why the decoupled properties are required. The protein nodes also contain a secondary label that could be either Train or Test. With the help of the secondary label, you can easily perform the train-test data split." }, { "code": null, "e": 2902, "s": 2206, "text": "To set up the Neo4j environment, you will first need to download and install the Neo4j Desktop application. You don’t need to create a database instance just yet. To avoid bugging you with the import process, I have prepared a database dump file, which you can go ahead and load a database instance from it. In this example, I used the Neo4j 4.2.0 version. If you aren’t familiar with how to load a Neo4j database instance from a dump file, you can take a look at my blog post for more detailed instructions. Next, you will need to install both the APOC and the Graph Data Science libraries. Using the Neo4j Desktop application, you can install both libraries with a single click as shown below." }, { "code": null, "e": 3119, "s": 2902, "text": "Now that you have loaded the database instance and installed both libraries, you can go ahead and start the database. Run the following query in the Neo4j Browser interface to make sure the graph is loaded correctly." }, { "code": null, "e": 3180, "s": 3119, "text": "MATCH p=(:Protein)-[:INTERACTS]->(:Protein)RETURN p LIMIT 25" }, { "code": null, "e": 3188, "s": 3180, "text": "Results" }, { "code": null, "e": 3517, "s": 3188, "text": "You should see a similar visualization in your Neo4j Browser. The green nodes represent the proteins and the relationships represent the interactions between the proteins. You can also notice that a protein can interact with itself. That is represented with self-loops, where the relationship starts and points to the same node." }, { "code": null, "e": 3924, "s": 3517, "text": "To get a baseline f1 score, you will first train the classification model using only the predefined features available for proteins. The code is identical to the code found in the official GraphSAGE repository, where they used the Stochastic Gradient Descent classifier model to train and predict protein roles. The only difference is that here you will be fetching the data from a Neo4j database instance." }, { "code": null, "e": 4103, "s": 3924, "text": "The baseline f1 score, where you used only the predefined features of proteins, is 0.422. Let’s now try to improve the classification model accuracy using the GraphSAGE algorithm" }, { "code": null, "e": 4563, "s": 4103, "text": "GraphSAGE is a convolutional graph neural network algorithm. The key idea behind the algorithm is that we learn a function that generates node embeddings by sampling and aggregating feature information from a node’s local neighborhood. As the GraphSAGE algorithm learns a function that can induce the embedding of a node, it can also be used to induce embeddings of a new node that wasn’t observed during the training phase. This is called inductive learning." }, { "code": null, "e": 4792, "s": 4563, "text": "If you want to learn more about the training process and the math behind the GraphSAGE algorithm, I suggest you take a look at the An Intuitive Explanation of GraphSAGE blog post by Rıza Özçelik or the official GraphSAGE site." }, { "code": null, "e": 5087, "s": 4792, "text": "Neo4j Graph Data Science library operates entirely on heap memory to enable fast caching for the graph’s topology, containing only relevant nodes, relationships, and weights. Graph algorithms are executed on an in-memory projected graph model, which is separate from Neo4j’s stored graph model." }, { "code": null, "e": 5291, "s": 5087, "text": "Before you can execute any graph algorithms, you have to project the in-memory graph via the Graph Loader component. You can use either native projection or cypher projection to load the in-memory graph." }, { "code": null, "e": 5888, "s": 5291, "text": "In this example, you will use the native projection feature to load the in-memory graph. To start, you will project the training data and store it as a named graph in the Graph Catalog. The current implementation of the GraphSAGE algorithm supports only node features that are of type Float. For this reason, you will include the decoupled node properties ranging from embedding_0 to embedding_49 in the graph projection instead of a single property embeddings_all, which holds all the node features in the form of a list of Floats. Additionally, you will treat the projected graph as undirected." }, { "code": null, "e": 6172, "s": 5888, "text": "UNWIND range(0,49) as iWITH collect('embedding_' + toString(i)) as embeddingsCALL gds.graph.create('train','Train', {INTERACTS:{orientation:'UNDIRECTED'}}, {nodeProperties:embeddings}) YIELD graphName, nodeCount, relationshipCountRETURN graphName, nodeCount, relationshipCount" }, { "code": null, "e": 6723, "s": 6172, "text": "Next, you will train the GraphSAGE model. The model’s hyper-parameter settings were mostly copied from the original paper. I have noticed that the lower learning-rate setting had the most impact on the downstream classification accuracy. Another import hyper-parameter is the samplingSizes parameter, where the size of the list determines the number of layers (defined as K parameter in the paper), and the values determine how many nodes will be sampled by the layers. Find more information about the available hyper-parameters in the documentation." }, { "code": null, "e": 7078, "s": 6723, "text": "UNWIND range(0,49) as iWITH collect('embedding_' + toString(i)) as embeddingsCALL gds.beta.graphSage.train('train',{ modelName:'proteinModel', aggregator:'pool', batchSize:512, activationFunction:'relu', epochs:10, sampleSizes:[25,10], learningRate:0.0000001, embeddingDimension:256, featureProperties:embeddings})YIELD modelInfoRETURN modelInfo" }, { "code": null, "e": 7492, "s": 7078, "text": "The training process took around 20 minutes on my laptop. After the training process finishes, the GraphSAGE model will be stored in the model catalog. You can now use this model to induce node embeddings on any projected graph with the same node properties used during the training. Before testing the downstream classification accuracy, you have to load the test data as an in-memory graph in the Graph Catalog." }, { "code": null, "e": 7769, "s": 7492, "text": "UNWIND range(0,49) as iWITH collect('embedding_' + toString(i)) as embeddingsCALL gds.graph.create('test','Test', {INTERACTS:{orientation:'UNDIRECTED'}}, {nodeProperties:embeddings}) YIELD graphName, nodeCount, relationshipCountRETURN graphName, nodeCount, relationshipCount" }, { "code": null, "e": 8072, "s": 7769, "text": "With the GraphSAGE model trained and both the training and test data projected as an in-memory graph, you can go ahead and calculate the f1 score using the GraphSAGE embeddings in a downstream classification model. Remember, the GraphSAGE model has not observed the test data during the training phase." }, { "code": null, "e": 8308, "s": 8072, "text": "Using the GraphSAGE embeddings as feature input to the classification model, you have improved the f1 score to 0.462. You can also try to follow the other examples in the original GraphSAGE paper to hone your graph data science skills." }, { "code": null, "e": 8390, "s": 8308, "text": "Connections within your data can help you increase the accuracy of your ML models" }, { "code": null, "e": 8494, "s": 8390, "text": "GraphSAGE algorithm can induce embeddings of new unseen nodes, without the need for re-training process" }, { "code": null, "e": 8538, "s": 8494, "text": "As always, the code is available on GitHub." } ]
How to select elements by attribute in jQuery ? - GeeksforGeeks
20 Sep, 2019 jQuery is a lightweight JavaScript library. In the vanilla JavaScript language, the getElementById method is used to select an element. However, jQuery provides a much lighter alternative for the same purpose. The ‘jQuery Selector’ allows the user to manipulate HTML elements and the data inside it(DOM manipulation). Syntax $("[attribute=value]") Here, attribute and value are mandatory. Some of the most commonly used jQuery selectors #id Selector: The #id selector specifies an id for an element to be selected. It should not begin with a number and the id attribute must be unique within a document which means it can be used only one time. Syntax: $("#example") The id selector must be used only when the user wants to find a unique element. Example: <!DOCTYPE html><html> <head> <title> How to select elements from attribute in jQuery ? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script> $(document).ready(function() { $("button").click(function() { $("#para").hide(); }); }); </script></head> <body> <h2>GeeksforGeeks</h2> <p>This is a constant paragraph.</p> <p id="para"> This paragraph will get hidden once the button is clicked. </p> <button>Click me</button></body> </html> Output: Before Click on the Button: After Click on the Button: .class selector: The .class selector specifies the class for an element to be selected. It should not begin with a number. It gives styling to several HTML elements. $(".example") Example: <!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script> $(document).ready(function() { $("button").click(function() { $(".test").hide(); }); }); </script></head> <body> <h2 class="heading">GeeksForGeeks</h2> <p class="test">This is a paragraph.</p> <p class="test">This is another paragraph.</p> <button>Click me</button></body> </html> Output: Before Click on the Button: After Click on the Button: :first Selector: It is a jQuery Selector that is used to select the first element of the specified type. Syntax: $(":first") Example: <!DOCTYPE html> <html> <head> <title>jQuery :first selector</title> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script> $(document).ready(function() { $("p:first").css( "background-color", "green"); }); </script> </head> <body> <h1>GeeksforGeeks</h1> <p>jQuery</p> <p>JavaScript</p> <p>PHP</p> </body> </html> Output: Picked JQuery Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments jQuery | ajax() Method How to prevent Body from scrolling when a modal is opened using jQuery ? How to get a DOM Element from a jQuery Selector ? How to get the value in an input text box using jQuery ? How to generate a simple popup using jQuery ? 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": 25364, "s": 25336, "text": "\n20 Sep, 2019" }, { "code": null, "e": 25682, "s": 25364, "text": "jQuery is a lightweight JavaScript library. In the vanilla JavaScript language, the getElementById method is used to select an element. However, jQuery provides a much lighter alternative for the same purpose. The ‘jQuery Selector’ allows the user to manipulate HTML elements and the data inside it(DOM manipulation)." }, { "code": null, "e": 25689, "s": 25682, "text": "Syntax" }, { "code": null, "e": 25712, "s": 25689, "text": "$(\"[attribute=value]\")" }, { "code": null, "e": 25753, "s": 25712, "text": "Here, attribute and value are mandatory." }, { "code": null, "e": 25801, "s": 25753, "text": "Some of the most commonly used jQuery selectors" }, { "code": null, "e": 26009, "s": 25801, "text": "#id Selector: The #id selector specifies an id for an element to be selected. It should not begin with a number and the id attribute must be unique within a document which means it can be used only one time." }, { "code": null, "e": 26017, "s": 26009, "text": "Syntax:" }, { "code": null, "e": 26031, "s": 26017, "text": "$(\"#example\")" }, { "code": null, "e": 26111, "s": 26031, "text": "The id selector must be used only when the user wants to find a unique element." }, { "code": null, "e": 26120, "s": 26111, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> How to select elements from attribute in jQuery ? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script> $(document).ready(function() { $(\"button\").click(function() { $(\"#para\").hide(); }); }); </script></head> <body> <h2>GeeksforGeeks</h2> <p>This is a constant paragraph.</p> <p id=\"para\"> This paragraph will get hidden once the button is clicked. </p> <button>Click me</button></body> </html>", "e": 26754, "s": 26120, "text": null }, { "code": null, "e": 26762, "s": 26754, "text": "Output:" }, { "code": null, "e": 26790, "s": 26762, "text": "Before Click on the Button:" }, { "code": null, "e": 26817, "s": 26790, "text": "After Click on the Button:" }, { "code": null, "e": 26983, "s": 26817, "text": ".class selector: The .class selector specifies the class for an element to be selected. It should not begin with a number. It gives styling to several HTML elements." }, { "code": null, "e": 26997, "s": 26983, "text": "$(\".example\")" }, { "code": null, "e": 27006, "s": 26997, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script> $(document).ready(function() { $(\"button\").click(function() { $(\".test\").hide(); }); }); </script></head> <body> <h2 class=\"heading\">GeeksForGeeks</h2> <p class=\"test\">This is a paragraph.</p> <p class=\"test\">This is another paragraph.</p> <button>Click me</button></body> </html>", "e": 27505, "s": 27006, "text": null }, { "code": null, "e": 27513, "s": 27505, "text": "Output:" }, { "code": null, "e": 27541, "s": 27513, "text": "Before Click on the Button:" }, { "code": null, "e": 27568, "s": 27541, "text": "After Click on the Button:" }, { "code": null, "e": 27673, "s": 27568, "text": ":first Selector: It is a jQuery Selector that is used to select the first element of the specified type." }, { "code": null, "e": 27681, "s": 27673, "text": "Syntax:" }, { "code": null, "e": 27693, "s": 27681, "text": "$(\":first\")" }, { "code": null, "e": 27702, "s": 27693, "text": "Example:" }, { "code": "<!DOCTYPE html> <html> <head> <title>jQuery :first selector</title> <script src= \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script> $(document).ready(function() { $(\"p:first\").css( \"background-color\", \"green\"); }); </script> </head> <body> <h1>GeeksforGeeks</h1> <p>jQuery</p> <p>JavaScript</p> <p>PHP</p> </body> </html> ", "e": 28153, "s": 27702, "text": null }, { "code": null, "e": 28161, "s": 28153, "text": "Output:" }, { "code": null, "e": 28168, "s": 28161, "text": "Picked" }, { "code": null, "e": 28175, "s": 28168, "text": "JQuery" }, { "code": null, "e": 28192, "s": 28175, "text": "Web Technologies" }, { "code": null, "e": 28219, "s": 28192, "text": "Web technologies Questions" }, { "code": null, "e": 28317, "s": 28219, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28326, "s": 28317, "text": "Comments" }, { "code": null, "e": 28339, "s": 28326, "text": "Old Comments" }, { "code": null, "e": 28362, "s": 28339, "text": "jQuery | ajax() Method" }, { "code": null, "e": 28435, "s": 28362, "text": "How to prevent Body from scrolling when a modal is opened using jQuery ?" }, { "code": null, "e": 28485, "s": 28435, "text": "How to get a DOM Element from a jQuery Selector ?" }, { "code": null, "e": 28542, "s": 28485, "text": "How to get the value in an input text box using jQuery ?" }, { "code": null, "e": 28588, "s": 28542, "text": "How to generate a simple popup using jQuery ?" }, { "code": null, "e": 28625, "s": 28588, "text": "Express.js express.Router() Function" }, { "code": null, "e": 28658, "s": 28625, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28720, "s": 28658, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28763, "s": 28720, "text": "How to fetch data from an API in ReactJS ?" } ]
<complex.h> header file in C with Examples
07 Apr, 2020 Most of the C Programs deals with complex number operations and manipulations by using complex.h header file. This header file was added in C99 Standard. C++ standard library has a header, which implements complex numbers as a template class, complex<T>, which is different from <complex.h> in C. Macros associated with <complex.h>Some of the macros of <complex.h> are shown below. The values in the left side describe the Macros in complex.h and the right side describes the expansion of those macros with the keywords (_Imaginary, _Complex) added in C99 standard. Below program helps to create complex numbers. Example 1: // C program to show the working// of complex.h library #include <complex.h>#include <stdio.h> int main(void){ double real = 1.3, imag = 4.9; double complex z = CMPLX(real, imag); printf( "z = %.1f% + .1fi\n", creal(z), cimag(z));} z = 1.3+4.9i Explanation: cmplx() function creates complex number objects by taking real part and imaginary parts as parameters. This function returns the object of complex numbers. creal() function returns the real part of a complex number cimag() function returns the imaginary part of a complex number If our real and imaginary parts are of type float we use cmplxf() function to generate complex numbers and to get real and imaginary parts we use crealf(), cimagf() functions. If our real and imaginary parts are of type long double we use cmplxl() function to generate complex numbers and to get real and imaginary parts we use creall(), cimagl() functions. Example 2: We can also create complex number objects using macro I. // C program to create a complex// number using macro I #include <complex.h>#include <stdio.h> int main(void){ double complex z = 3.2 + 4.1 * I; // Creates complex number // with 3.2 and 4.1 as // real and imaginary parts printf( "z = %.1f% + .1fi\n", creal(z), cimag(z));} z = 3.2+4.1i Functions associated with <complex.h>The <complex.h> header file also provides some inbuilt functions to work with the complex number. Here the word “arg” stands for complex number object. Examples 3: Program to find Conjugate of a complex number. #include <complex.h>#include <stdio.h> int main(void){ double real = 1.3, imag = 4.9; double complex z = CMPLX(real, imag); double complex conj_f = conjf(z); printf("z = %.1f% + .1fi\n", creal(conj_f), cimag(conj_f));} z = 1.3-4.9i Examples 4: Program to find the absolute value of a complex number. #include <complex.h>#include <stdio.h> int main(void){ double real = 1.3, imag = 4.9; double complex z = CMPLX(real, imag); printf("Absolute value = %.1f", cabsf(z));} Absolute value = 5.1 Examples 4: Program to find the phase angle of a complex number. #include <complex.h>#include <stdio.h> int main(void){ double real = 1.3, imag = 4.9; double complex z = CMPLX(real, imag); printf( "Phase Angle = %.1f radians\n", cargf(z));} Phase Angle = 1.3 radians C-Library C Language C Programs Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Functions that cannot be overloaded in C++ Exception Handling in C++ Switch Statement in C/C++ Storage Classes in C Operators in C / C++ Strings in C size of char datatype and char array in C UDP Server-Client implementation in C Arrow operator -> in C/C++ with Examples C Program to read contents of Whole File
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Apr, 2020" }, { "code": null, "e": 208, "s": 54, "text": "Most of the C Programs deals with complex number operations and manipulations by using complex.h header file. This header file was added in C99 Standard." }, { "code": null, "e": 351, "s": 208, "text": "C++ standard library has a header, which implements complex numbers as a template class, complex<T>, which is different from <complex.h> in C." }, { "code": null, "e": 620, "s": 351, "text": "Macros associated with <complex.h>Some of the macros of <complex.h> are shown below. The values in the left side describe the Macros in complex.h and the right side describes the expansion of those macros with the keywords (_Imaginary, _Complex) added in C99 standard." }, { "code": null, "e": 667, "s": 620, "text": "Below program helps to create complex numbers." }, { "code": null, "e": 678, "s": 667, "text": "Example 1:" }, { "code": "// C program to show the working// of complex.h library #include <complex.h>#include <stdio.h> int main(void){ double real = 1.3, imag = 4.9; double complex z = CMPLX(real, imag); printf( \"z = %.1f% + .1fi\\n\", creal(z), cimag(z));}", "e": 952, "s": 678, "text": null }, { "code": null, "e": 966, "s": 952, "text": "z = 1.3+4.9i\n" }, { "code": null, "e": 979, "s": 966, "text": "Explanation:" }, { "code": null, "e": 1135, "s": 979, "text": "cmplx() function creates complex number objects by taking real part and imaginary parts as parameters. This function returns the object of complex numbers." }, { "code": null, "e": 1194, "s": 1135, "text": "creal() function returns the real part of a complex number" }, { "code": null, "e": 1258, "s": 1194, "text": "cimag() function returns the imaginary part of a complex number" }, { "code": null, "e": 1434, "s": 1258, "text": "If our real and imaginary parts are of type float we use cmplxf() function to generate complex numbers and to get real and imaginary parts we use crealf(), cimagf() functions." }, { "code": null, "e": 1616, "s": 1434, "text": "If our real and imaginary parts are of type long double we use cmplxl() function to generate complex numbers and to get real and imaginary parts we use creall(), cimagl() functions." }, { "code": null, "e": 1684, "s": 1616, "text": "Example 2: We can also create complex number objects using macro I." }, { "code": "// C program to create a complex// number using macro I #include <complex.h>#include <stdio.h> int main(void){ double complex z = 3.2 + 4.1 * I; // Creates complex number // with 3.2 and 4.1 as // real and imaginary parts printf( \"z = %.1f% + .1fi\\n\", creal(z), cimag(z));}", "e": 2005, "s": 1684, "text": null }, { "code": null, "e": 2019, "s": 2005, "text": "z = 3.2+4.1i\n" }, { "code": null, "e": 2208, "s": 2019, "text": "Functions associated with <complex.h>The <complex.h> header file also provides some inbuilt functions to work with the complex number. Here the word “arg” stands for complex number object." }, { "code": null, "e": 2267, "s": 2208, "text": "Examples 3: Program to find Conjugate of a complex number." }, { "code": "#include <complex.h>#include <stdio.h> int main(void){ double real = 1.3, imag = 4.9; double complex z = CMPLX(real, imag); double complex conj_f = conjf(z); printf(\"z = %.1f% + .1fi\\n\", creal(conj_f), cimag(conj_f));}", "e": 2550, "s": 2267, "text": null }, { "code": null, "e": 2564, "s": 2550, "text": "z = 1.3-4.9i\n" }, { "code": null, "e": 2632, "s": 2564, "text": "Examples 4: Program to find the absolute value of a complex number." }, { "code": "#include <complex.h>#include <stdio.h> int main(void){ double real = 1.3, imag = 4.9; double complex z = CMPLX(real, imag); printf(\"Absolute value = %.1f\", cabsf(z));}", "e": 2837, "s": 2632, "text": null }, { "code": null, "e": 2859, "s": 2837, "text": "Absolute value = 5.1\n" }, { "code": null, "e": 2924, "s": 2859, "text": "Examples 4: Program to find the phase angle of a complex number." }, { "code": "#include <complex.h>#include <stdio.h> int main(void){ double real = 1.3, imag = 4.9; double complex z = CMPLX(real, imag); printf( \"Phase Angle = %.1f radians\\n\", cargf(z));}", "e": 3141, "s": 2924, "text": null }, { "code": null, "e": 3168, "s": 3141, "text": "Phase Angle = 1.3 radians\n" }, { "code": null, "e": 3178, "s": 3168, "text": "C-Library" }, { "code": null, "e": 3189, "s": 3178, "text": "C Language" }, { "code": null, "e": 3200, "s": 3189, "text": "C Programs" }, { "code": null, "e": 3213, "s": 3200, "text": "Mathematical" }, { "code": null, "e": 3226, "s": 3213, "text": "Mathematical" }, { "code": null, "e": 3324, "s": 3226, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3367, "s": 3324, "text": "Functions that cannot be overloaded in C++" }, { "code": null, "e": 3393, "s": 3367, "text": "Exception Handling in C++" }, { "code": null, "e": 3419, "s": 3393, "text": "Switch Statement in C/C++" }, { "code": null, "e": 3440, "s": 3419, "text": "Storage Classes in C" }, { "code": null, "e": 3461, "s": 3440, "text": "Operators in C / C++" }, { "code": null, "e": 3474, "s": 3461, "text": "Strings in C" }, { "code": null, "e": 3516, "s": 3474, "text": "size of char datatype and char array in C" }, { "code": null, "e": 3554, "s": 3516, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 3595, "s": 3554, "text": "Arrow operator -> in C/C++ with Examples" } ]
Python | Check if element is present in tuple of tuples
26 Jan, 2019 Sometimes the data that we use is in the form of tuples and often we need to look into the nested tuples as well. The common problem that this can solve is looking for a missing data or N.A values in data preprocessing. Let’s discuss certain ways in which this can be performed. Method #1 : Using any()any function is used to perform this task. It just tests one by one if the element is present as the tuple element. If the element is present, true is returned else false is returned. # Python3 code to demonstrate # test for values in tuple of tuple# using any() # initializing tuple of tuple test_tuple = (("geeksforgeeks", "gfg"), ("CS_Portal", "best")) # printing tupleprint ("The original tuple is " + str(test_tuple)) # using any()# to test for value in tuple of tupleif (any('geeksforgeeks' in i for i in test_tuple)) : print("geeksforgeeks is present")else : print("geeksforgeeks is not present") Output : The original tuple is (('geeksforgeeks', 'gfg'), ('CS_Portal', 'best')) geeksforgeeks is present Method #2 : Using itertools.chain()The chain function tests for all the intermediate tuples for the desired values and then returns true if the required value is present in any of the tuples searched. # Python3 code to demonstrate # test for values in tuple of tuple# using itertools.chain()import itertools # initializing tuple of tuple test_tuple = (("geeksforgeeks", "gfg"), ("CS_Portal", "best")) # printing tupleprint ("The original tuple is " + str(test_tuple)) # using itertools.chain()# to test for value in tuple of tupleif ('geeksforgeeks' in itertools.chain(*test_tuple)) : print("geeksforgeeks is present")else : print("geeksforgeeks is not present") Output : The original tuple is (('geeksforgeeks', 'gfg'), ('CS_Portal', 'best')) geeksforgeeks is present Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Jan, 2019" }, { "code": null, "e": 307, "s": 28, "text": "Sometimes the data that we use is in the form of tuples and often we need to look into the nested tuples as well. The common problem that this can solve is looking for a missing data or N.A values in data preprocessing. Let’s discuss certain ways in which this can be performed." }, { "code": null, "e": 514, "s": 307, "text": "Method #1 : Using any()any function is used to perform this task. It just tests one by one if the element is present as the tuple element. If the element is present, true is returned else false is returned." }, { "code": "# Python3 code to demonstrate # test for values in tuple of tuple# using any() # initializing tuple of tuple test_tuple = ((\"geeksforgeeks\", \"gfg\"), (\"CS_Portal\", \"best\")) # printing tupleprint (\"The original tuple is \" + str(test_tuple)) # using any()# to test for value in tuple of tupleif (any('geeksforgeeks' in i for i in test_tuple)) : print(\"geeksforgeeks is present\")else : print(\"geeksforgeeks is not present\")", "e": 943, "s": 514, "text": null }, { "code": null, "e": 952, "s": 943, "text": "Output :" }, { "code": null, "e": 1050, "s": 952, "text": "The original tuple is (('geeksforgeeks', 'gfg'), ('CS_Portal', 'best'))\ngeeksforgeeks is present\n" }, { "code": null, "e": 1253, "s": 1052, "text": "Method #2 : Using itertools.chain()The chain function tests for all the intermediate tuples for the desired values and then returns true if the required value is present in any of the tuples searched." }, { "code": "# Python3 code to demonstrate # test for values in tuple of tuple# using itertools.chain()import itertools # initializing tuple of tuple test_tuple = ((\"geeksforgeeks\", \"gfg\"), (\"CS_Portal\", \"best\")) # printing tupleprint (\"The original tuple is \" + str(test_tuple)) # using itertools.chain()# to test for value in tuple of tupleif ('geeksforgeeks' in itertools.chain(*test_tuple)) : print(\"geeksforgeeks is present\")else : print(\"geeksforgeeks is not present\")", "e": 1724, "s": 1253, "text": null }, { "code": null, "e": 1733, "s": 1724, "text": "Output :" }, { "code": null, "e": 1831, "s": 1733, "text": "The original tuple is (('geeksforgeeks', 'gfg'), ('CS_Portal', 'best'))\ngeeksforgeeks is present\n" }, { "code": null, "e": 1852, "s": 1831, "text": "Python list-programs" }, { "code": null, "e": 1859, "s": 1852, "text": "Python" }, { "code": null, "e": 1875, "s": 1859, "text": "Python Programs" }, { "code": null, "e": 1973, "s": 1875, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1991, "s": 1973, "text": "Python Dictionary" }, { "code": null, "e": 2033, "s": 1991, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2055, "s": 2033, "text": "Enumerate() in Python" }, { "code": null, "e": 2090, "s": 2055, "text": "Read a file line by line in Python" }, { "code": null, "e": 2116, "s": 2090, "text": "Python String | replace()" }, { "code": null, "e": 2159, "s": 2116, "text": "Python program to convert a list to string" }, { "code": null, "e": 2181, "s": 2159, "text": "Defaultdict in Python" }, { "code": null, "e": 2220, "s": 2181, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2258, "s": 2220, "text": "Python | Convert a list to dictionary" } ]
High-Level Data Link Control (HDLC) Encapsulation
13 Aug, 2020 High-Level Data Link Control (HDLC) basically provides reliable delivery of data frames over a network or communication link. HDLC provides various operations such as framing, data transparency, error detection, and correction, and even flow control. Primary stations simply transmit commands that contain address of secondary stations. The secondary station then simply transmits responses that contain its own address. HDLC Encapsulation Protocol :We know that each of frames of HDLC includes at least six to seven fields like start/end flag field, control field, information field, FCS (Frame Check Sequence) field. Standard HDLC Protocol contains six fields. Whereas on the other hand, Cisco HDLC (cHDLC) contains one extra protocol field. The standard protocol uses to support only one protocol whereas cHDLC protocol use to support multi-protocol environments. Supporting multiple protocols is possible due to protocol field in header, that helps in identifying different protocols. cHDLC was basically created by Cisco systems. Address field –This field is used to identify and specify type of packet that is present in cHDLC frame. It can be 0*0F for Unicast and 0*8F for Broadcast packets. Control field –This field is always set to zero i.e. 0*00. Protocol field –This field is especially required to specify and identify type of protocol that is being encapsulated withing cHDLC frame. It can be 0x0800 for Internet Protocol. Verify HDLC Encapsulation :We know that HDLC is generally default encapsulation method for serial interfaces on Cisco router. Therefore, it will not be listed in any of running configurations. This simply means that to verify HDLC encapsulation, we cannot even use show running-config command. So, we must use show interfaces (Interface) command identify and view type of encapsulation in interface. Router#show interfaces serial 0/0/0 Serial0/0/0 is administratively down, line protocol is down (disabled) Hardware is HD64570 MTU 1500 bytes, BW 1544 Kbit, DLY 20000 usec, reliability 255/255, txload 1/255, rxload 1/255 Encapsulation HDLC, loopback not set, keepalive set (10 sec) Last input never, output never, output hang never Last clearing of "show interface" counters never The output will indicate type of encapsulation in HDLC. Troubleshoot HDLC Encapsulation :To view and know present status of serial interface, we can use two types of commands as given below: show ip interface brief show interfaces [interface] Show controllers command is an essential and important diagnostic tool that helps in troubleshooting serial lines. This command output also indicates state of interface channels and whether a cable is attached to interface or not. There are some reasons that are responsible for some issues arising during HDLC implementation due to which protocol status will be down. These reasons are given below: Presence of Non-Cisco router at remote side. Usage of others protocols such as PPP by remote side router. Inability to providing clock rate to DTE (Data Terminal Equipment) Device by DCE (Data Circuit-Terminating Equipment) Device. Problem or issue with internal wiring of card. Unknown electrical interfaces. Some of the serial interface issues are given below: Serial x is up, Line Protocol is up –This command indicates that line is up and functioning properly. There is no requirement of any action.Serial x is down, Line Protocol is down (DTE mode) –This command indicates that there is an issue. This issue can arise due to different reasons. Some of them are given below:Fault in cable –This issue can be resolved by swapping all of fault cables.Failure of hardware –This issue can be resolved by changing serial line to another port.Serial x is up, Line Protocol is down (DTE mode) –This command also indicates that there is an issue. This issue can arise due to reason that a local or remote is misconfigured. This problem can be resolved by putting modem, CSU (Channel Service Unit) or DSU (Data Service Unit) in local loopback mode, and then using show interface serial command. This command indicates whether line protocol has come up or not. Serial x is up, Line Protocol is up –This command indicates that line is up and functioning properly. There is no requirement of any action. Serial x is down, Line Protocol is down (DTE mode) –This command indicates that there is an issue. This issue can arise due to different reasons. Some of them are given below:Fault in cable –This issue can be resolved by swapping all of fault cables.Failure of hardware –This issue can be resolved by changing serial line to another port. Fault in cable –This issue can be resolved by swapping all of fault cables. Failure of hardware –This issue can be resolved by changing serial line to another port. Serial x is up, Line Protocol is down (DTE mode) –This command also indicates that there is an issue. This issue can arise due to reason that a local or remote is misconfigured. This problem can be resolved by putting modem, CSU (Channel Service Unit) or DSU (Data Service Unit) in local loopback mode, and then using show interface serial command. This command indicates whether line protocol has come up or not. Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Aug, 2020" }, { "code": null, "e": 473, "s": 52, "text": "High-Level Data Link Control (HDLC) basically provides reliable delivery of data frames over a network or communication link. HDLC provides various operations such as framing, data transparency, error detection, and correction, and even flow control. Primary stations simply transmit commands that contain address of secondary stations. The secondary station then simply transmits responses that contain its own address." }, { "code": null, "e": 1087, "s": 473, "text": "HDLC Encapsulation Protocol :We know that each of frames of HDLC includes at least six to seven fields like start/end flag field, control field, information field, FCS (Frame Check Sequence) field. Standard HDLC Protocol contains six fields. Whereas on the other hand, Cisco HDLC (cHDLC) contains one extra protocol field. The standard protocol uses to support only one protocol whereas cHDLC protocol use to support multi-protocol environments. Supporting multiple protocols is possible due to protocol field in header, that helps in identifying different protocols. cHDLC was basically created by Cisco systems." }, { "code": null, "e": 1251, "s": 1087, "text": "Address field –This field is used to identify and specify type of packet that is present in cHDLC frame. It can be 0*0F for Unicast and 0*8F for Broadcast packets." }, { "code": null, "e": 1310, "s": 1251, "text": "Control field –This field is always set to zero i.e. 0*00." }, { "code": null, "e": 1489, "s": 1310, "text": "Protocol field –This field is especially required to specify and identify type of protocol that is being encapsulated withing cHDLC frame. It can be 0x0800 for Internet Protocol." }, { "code": null, "e": 1889, "s": 1489, "text": "Verify HDLC Encapsulation :We know that HDLC is generally default encapsulation method for serial interfaces on Cisco router. Therefore, it will not be listed in any of running configurations. This simply means that to verify HDLC encapsulation, we cannot even use show running-config command. So, we must use show interfaces (Interface) command identify and view type of encapsulation in interface." }, { "code": null, "e": 2283, "s": 1889, "text": "Router#show interfaces serial 0/0/0\nSerial0/0/0 is administratively down, line protocol is down (disabled)\n Hardware is HD64570\n MTU 1500 bytes, BW 1544 Kbit, DLY 20000 usec,\n reliability 255/255, txload 1/255, rxload 1/255\n Encapsulation HDLC, loopback not set, keepalive set (10 sec)\n Last input never, output never, output hang never\n Last clearing of \"show interface\" counters never " }, { "code": null, "e": 2339, "s": 2283, "text": "The output will indicate type of encapsulation in HDLC." }, { "code": null, "e": 2474, "s": 2339, "text": "Troubleshoot HDLC Encapsulation :To view and know present status of serial interface, we can use two types of commands as given below:" }, { "code": null, "e": 2498, "s": 2474, "text": "show ip interface brief" }, { "code": null, "e": 2526, "s": 2498, "text": "show interfaces [interface]" }, { "code": null, "e": 2895, "s": 2526, "text": "Show controllers command is an essential and important diagnostic tool that helps in troubleshooting serial lines. This command output also indicates state of interface channels and whether a cable is attached to interface or not. There are some reasons that are responsible for some issues arising during HDLC implementation due to which protocol status will be down." }, { "code": null, "e": 2926, "s": 2895, "text": "These reasons are given below:" }, { "code": null, "e": 2971, "s": 2926, "text": "Presence of Non-Cisco router at remote side." }, { "code": null, "e": 3032, "s": 2971, "text": "Usage of others protocols such as PPP by remote side router." }, { "code": null, "e": 3158, "s": 3032, "text": "Inability to providing clock rate to DTE (Data Terminal Equipment) Device by DCE (Data Circuit-Terminating Equipment) Device." }, { "code": null, "e": 3205, "s": 3158, "text": "Problem or issue with internal wiring of card." }, { "code": null, "e": 3236, "s": 3205, "text": "Unknown electrical interfaces." }, { "code": null, "e": 3289, "s": 3236, "text": "Some of the serial interface issues are given below:" }, { "code": null, "e": 4181, "s": 3289, "text": "Serial x is up, Line Protocol is up –This command indicates that line is up and functioning properly. There is no requirement of any action.Serial x is down, Line Protocol is down (DTE mode) –This command indicates that there is an issue. This issue can arise due to different reasons. Some of them are given below:Fault in cable –This issue can be resolved by swapping all of fault cables.Failure of hardware –This issue can be resolved by changing serial line to another port.Serial x is up, Line Protocol is down (DTE mode) –This command also indicates that there is an issue. This issue can arise due to reason that a local or remote is misconfigured. This problem can be resolved by putting modem, CSU (Channel Service Unit) or DSU (Data Service Unit) in local loopback mode, and then using show interface serial command. This command indicates whether line protocol has come up or not." }, { "code": null, "e": 4322, "s": 4181, "text": "Serial x is up, Line Protocol is up –This command indicates that line is up and functioning properly. There is no requirement of any action." }, { "code": null, "e": 4661, "s": 4322, "text": "Serial x is down, Line Protocol is down (DTE mode) –This command indicates that there is an issue. This issue can arise due to different reasons. Some of them are given below:Fault in cable –This issue can be resolved by swapping all of fault cables.Failure of hardware –This issue can be resolved by changing serial line to another port." }, { "code": null, "e": 4737, "s": 4661, "text": "Fault in cable –This issue can be resolved by swapping all of fault cables." }, { "code": null, "e": 4826, "s": 4737, "text": "Failure of hardware –This issue can be resolved by changing serial line to another port." }, { "code": null, "e": 5240, "s": 4826, "text": "Serial x is up, Line Protocol is down (DTE mode) –This command also indicates that there is an issue. This issue can arise due to reason that a local or remote is misconfigured. This problem can be resolved by putting modem, CSU (Channel Service Unit) or DSU (Data Service Unit) in local loopback mode, and then using show interface serial command. This command indicates whether line protocol has come up or not." }, { "code": null, "e": 5258, "s": 5240, "text": "Computer Networks" }, { "code": null, "e": 5276, "s": 5258, "text": "Computer Networks" } ]
list::front() and list::back() in C++ STL
23 Jun, 2022 Lists are containers used in C++ to store data in a non-contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists. list::front() This function is used to reference the first element of the list container. This function can be used to fetch the first element of a list. Syntax : listname.front() Parameters : No value is needed to pass as the parameter. Returns : Direct reference to the first element of the list container. Examples: Input : list list{1, 2, 3, 4, 5}; list.front(); Output : 1 Input : list list{0, 1, 2, 3, 4, 5}; list.front(); Output : 0 Errors and Exceptions If the list container is empty, it causes undefined behaviorIt has a no exception throw guarantee if the list is not empty If the list container is empty, it causes undefined behavior It has a no exception throw guarantee if the list is not empty C++ // CPP program to illustrate// Implementation of front() function#include <iostream>#include <list>using namespace std; int main(){ list<int> mylist{ 1, 2, 3, 4, 5 }; cout << mylist.front(); return 0;} Output: 1 This function is used to reference the last element of the list container. This function can be used to fetch the first element from the end of a list. Syntax : listname.back() Parameters : No value is needed to pass as the parameter. Returns : Direct reference to the last element of the list container. Examples: Input : list list{1, 2, 3, 4, 5}; list.back(); Output : 5 Input : list list{1, 2, 3, 4, 5, 6}; list.back(); Output : 6 Errors and Exceptions If the list container is empty, it causes undefined behaviorIt has a no exception throw guarantee if the list is not empty If the list container is empty, it causes undefined behavior It has a no exception throw guarantee if the list is not empty C++ // CPP program to illustrate// Implementation of back() function#include <iostream>#include <list>using namespace std; int main(){ list<int> mylist{ 1, 2, 3, 4, 5 }; cout << mylist.back(); return 0;} Output: 5 Application Given an empty list of integers, add numbers to the list, then print the difference between the first and the last element. Input: 1, 2, 3, 4, 5, 6, 7, 8 Output:7 Explanation: Last element = 8, First element = 1, Difference = 7 Algorithm 1. Add numbers to the list using push_front() or push_back() function 2. Compare the first and the last element. 3. If first element is larger, subtract last element from it and print it. 4. Else subtract first element from the last element and print it. C++ // CPP program to illustrate// application Of front() and back() function#include <iostream>#include <list>using namespace std; int main(){ list<int> mylist{}; mylist.push_front(8); mylist.push_front(7); mylist.push_front(6); mylist.push_front(5); mylist.push_front(4); mylist.push_front(3); mylist.push_front(2); mylist.push_front(1); // list becomes 1, 2, 3, 4, 5, 6, 7, 8 if (mylist.front() > mylist.back()) { cout << mylist.front() - mylist.back(); } else if (mylist.front() < mylist.back()) { cout << mylist.back() - mylist.front(); } else cout << "0";} Output: 7 Let us see the differences in a tabular form -: Its syntax is -: reference back(); chhabradhanvi mayank007rawa CPP-Library STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bitwise Operators in C/C++ Priority Queue in C++ Standard Template Library (STL) Set in C++ Standard Template Library (STL) vector erase() and clear() in C++ unordered_map in C++ STL Substring in C++ Object Oriented Programming in C++ The C++ Standard Template Library (STL) Inheritance in C++ C++ Classes and Objects
[ { "code": null, "e": 53, "s": 25, "text": "\n23 Jun, 2022" }, { "code": null, "e": 305, "s": 53, "text": "Lists are containers used in C++ to store data in a non-contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists. " }, { "code": null, "e": 319, "s": 305, "text": "list::front()" }, { "code": null, "e": 459, "s": 319, "text": "This function is used to reference the first element of the list container. This function can be used to fetch the first element of a list." }, { "code": null, "e": 470, "s": 459, "text": "Syntax : " }, { "code": null, "e": 616, "s": 470, "text": "listname.front()\nParameters :\nNo value is needed to pass as the parameter.\nReturns :\nDirect reference to the first element of the list container." }, { "code": null, "e": 627, "s": 616, "text": "Examples: " }, { "code": null, "e": 769, "s": 627, "text": "Input : list list{1, 2, 3, 4, 5};\n list.front();\nOutput : 1\n\nInput : list list{0, 1, 2, 3, 4, 5};\n list.front();\nOutput : 0" }, { "code": null, "e": 792, "s": 769, "text": "Errors and Exceptions " }, { "code": null, "e": 915, "s": 792, "text": "If the list container is empty, it causes undefined behaviorIt has a no exception throw guarantee if the list is not empty" }, { "code": null, "e": 976, "s": 915, "text": "If the list container is empty, it causes undefined behavior" }, { "code": null, "e": 1039, "s": 976, "text": "It has a no exception throw guarantee if the list is not empty" }, { "code": null, "e": 1043, "s": 1039, "text": "C++" }, { "code": "// CPP program to illustrate// Implementation of front() function#include <iostream>#include <list>using namespace std; int main(){ list<int> mylist{ 1, 2, 3, 4, 5 }; cout << mylist.front(); return 0;}", "e": 1254, "s": 1043, "text": null }, { "code": null, "e": 1263, "s": 1254, "text": "Output: " }, { "code": null, "e": 1265, "s": 1263, "text": "1" }, { "code": null, "e": 1417, "s": 1265, "text": "This function is used to reference the last element of the list container. This function can be used to fetch the first element from the end of a list." }, { "code": null, "e": 1427, "s": 1417, "text": "Syntax : " }, { "code": null, "e": 1571, "s": 1427, "text": "listname.back()\nParameters :\nNo value is needed to pass as the parameter.\nReturns :\nDirect reference to the last element of the list container." }, { "code": null, "e": 1583, "s": 1571, "text": "Examples: " }, { "code": null, "e": 1723, "s": 1583, "text": "Input : list list{1, 2, 3, 4, 5};\n list.back();\nOutput : 5\n\nInput : list list{1, 2, 3, 4, 5, 6};\n list.back();\nOutput : 6" }, { "code": null, "e": 1747, "s": 1723, "text": "Errors and Exceptions " }, { "code": null, "e": 1870, "s": 1747, "text": "If the list container is empty, it causes undefined behaviorIt has a no exception throw guarantee if the list is not empty" }, { "code": null, "e": 1931, "s": 1870, "text": "If the list container is empty, it causes undefined behavior" }, { "code": null, "e": 1994, "s": 1931, "text": "It has a no exception throw guarantee if the list is not empty" }, { "code": null, "e": 1998, "s": 1994, "text": "C++" }, { "code": "// CPP program to illustrate// Implementation of back() function#include <iostream>#include <list>using namespace std; int main(){ list<int> mylist{ 1, 2, 3, 4, 5 }; cout << mylist.back(); return 0;}", "e": 2207, "s": 1998, "text": null }, { "code": null, "e": 2216, "s": 2207, "text": "Output: " }, { "code": null, "e": 2218, "s": 2216, "text": "5" }, { "code": null, "e": 2354, "s": 2218, "text": "Application Given an empty list of integers, add numbers to the list, then print the difference between the first and the last element." }, { "code": null, "e": 2458, "s": 2354, "text": "Input: 1, 2, 3, 4, 5, 6, 7, 8\nOutput:7\nExplanation: Last element = 8, First element = 1, Difference = 7" }, { "code": null, "e": 2723, "s": 2458, "text": "Algorithm 1. Add numbers to the list using push_front() or push_back() function 2. Compare the first and the last element. 3. If first element is larger, subtract last element from it and print it. 4. Else subtract first element from the last element and print it." }, { "code": null, "e": 2727, "s": 2723, "text": "C++" }, { "code": "// CPP program to illustrate// application Of front() and back() function#include <iostream>#include <list>using namespace std; int main(){ list<int> mylist{}; mylist.push_front(8); mylist.push_front(7); mylist.push_front(6); mylist.push_front(5); mylist.push_front(4); mylist.push_front(3); mylist.push_front(2); mylist.push_front(1); // list becomes 1, 2, 3, 4, 5, 6, 7, 8 if (mylist.front() > mylist.back()) { cout << mylist.front() - mylist.back(); } else if (mylist.front() < mylist.back()) { cout << mylist.back() - mylist.front(); } else cout << \"0\";}", "e": 3354, "s": 2727, "text": null }, { "code": null, "e": 3363, "s": 3354, "text": "Output: " }, { "code": null, "e": 3365, "s": 3363, "text": "7" }, { "code": null, "e": 3413, "s": 3365, "text": "Let us see the differences in a tabular form -:" }, { "code": null, "e": 3430, "s": 3413, "text": "Its syntax is -:" }, { "code": null, "e": 3449, "s": 3430, "text": " reference back();" }, { "code": null, "e": 3465, "s": 3451, "text": "chhabradhanvi" }, { "code": null, "e": 3479, "s": 3465, "text": "mayank007rawa" }, { "code": null, "e": 3491, "s": 3479, "text": "CPP-Library" }, { "code": null, "e": 3495, "s": 3491, "text": "STL" }, { "code": null, "e": 3499, "s": 3495, "text": "C++" }, { "code": null, "e": 3503, "s": 3499, "text": "STL" }, { "code": null, "e": 3507, "s": 3503, "text": "CPP" }, { "code": null, "e": 3605, "s": 3507, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3632, "s": 3605, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 3686, "s": 3632, "text": "Priority Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 3729, "s": 3686, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 3763, "s": 3729, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 3788, "s": 3763, "text": "unordered_map in C++ STL" }, { "code": null, "e": 3805, "s": 3788, "text": "Substring in C++" }, { "code": null, "e": 3840, "s": 3805, "text": "Object Oriented Programming in C++" }, { "code": null, "e": 3880, "s": 3840, "text": "The C++ Standard Template Library (STL)" }, { "code": null, "e": 3899, "s": 3880, "text": "Inheritance in C++" } ]
Regular languages and finite automata - GeeksforGeeks
06 Oct, 2021 1. Complement of L(A) is context-free. 2. L(A) = L((11*0+0)(0 + 1)*0*1*) 3. For the language accepted by A, A is the minimal DFA. 4. A accepts all strings over {0, 1} of length at least 2. 1) abaabaaabaa 2) aaaabaaaa 3) baaaaabaaaab 4) baaaaabaa 1) abaabaaabaa 2) aaaabaaaa 3) baaaaabaaaab 4) baaaaabaa L={| k>0, and n is a positive integer constant} Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ... Must Do Coding Questions for Product Based Companies 50 Common Ports You Should Know GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge? Spring Boot - Thymeleaf with Example Naming Convention in C++ Floyd’s Cycle Finding Algorithm How to use arrays to swap variables in JavaScript ? Samsung R&D Interview Experience How to add horizontal line in HTML ?
[ { "code": null, "e": 31777, "s": 31749, "text": "\n06 Oct, 2021" }, { "code": null, "e": 31967, "s": 31777, "text": "1. Complement of L(A) is context-free.\n2. L(A) = L((11*0+0)(0 + 1)*0*1*)\n3. For the language accepted by A, A is the minimal DFA.\n4. A accepts all strings over {0, 1} of length at least 2. " }, { "code": null, "e": 32025, "s": 31967, "text": "1) abaabaaabaa\n2) aaaabaaaa\n3) baaaaabaaaab\n4) baaaaabaa " }, { "code": null, "e": 32083, "s": 32025, "text": "1) abaabaaabaa\n2) aaaabaaaa\n3) baaaaabaaaab\n4) baaaaabaa " }, { "code": null, "e": 32144, "s": 32083, "text": " L={| k>0, and n is a positive integer constant}" }, { "code": null, "e": 32242, "s": 32144, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 32316, "s": 32242, "text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..." }, { "code": null, "e": 32369, "s": 32316, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 32401, "s": 32369, "text": "50 Common Ports You Should Know" }, { "code": null, "e": 32467, "s": 32401, "text": "GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?" }, { "code": null, "e": 32504, "s": 32467, "text": "Spring Boot - Thymeleaf with Example" }, { "code": null, "e": 32529, "s": 32504, "text": "Naming Convention in C++" }, { "code": null, "e": 32561, "s": 32529, "text": "Floyd’s Cycle Finding Algorithm" }, { "code": null, "e": 32613, "s": 32561, "text": "How to use arrays to swap variables in JavaScript ?" }, { "code": null, "e": 32646, "s": 32613, "text": "Samsung R&D Interview Experience" } ]
Esquisse Package in R Programming
08 Dec, 2021 Packages in the R programming are a collection of R functions, compiled code, and sample data. They are stored under a directory called “library” in the R environment. By default, R installs a set of packages during installation. One of the most important packages in R is the Esquisse package. Esquisse package helps to explore and visualize your data interactively. It is a Shiny gadget to create ggplot charts interactively with drag-and-drop to map your variables. One can quickly visualize the data accordingly to their type, export to ‘PNG’ or ‘PowerPoint’, and retrieve the code to reproduce the chart. To use a package in R programming one must have to install the package first. This task can be done using the command install.packages(“packagename”). source("https://install-github.me/dreamRs/esquisse") install.packages("esquisse") To install the development version from GitHub type this: # or with devtools: devtools::install_github("dreamRs/esquisse") chooseData-Module: It is a module for choosing data.frame from the user environment and select variable to use. It gives the user an option to choose from a given list of available datasets to work on within a shiny app. Syntax: chooseDataUI(id) chooseDataServer(input, output, session, data = NULL, name = NULL, selectVars = TRUE, launchOnStart = TRUE, defaultData = NULL) Parameter Description A character vector of data.frames to choose along if there is no data.frames in Global environment. By default, data.frames from ggplot2 are used. Example: R # Import shiny and# esquisse packageslibrary(shiny)library(esquisse) ui <- fluidPage( tags$h2("Choose data module"), fluidRow( column( width = 4, tags$h4("Default"), # Using chooseDataUI chooseDataUI(id = "choose1"), verbatimTextOutput(outputId = "res1")))) server <- function(input, output, session){ res_dat1 <- callModule( chooseDataServer, id = "choose1", launchOnStart = FALSE) output$res1 <- renderPrint({ str(reactiveValuesToList(res_dat1))})} shinyApp(ui,server) Output: dragulaInput: It creates a Drag And Drop Input Widget. One can select different labels(data) from a variety of labels provided by the developer to the app user to twerk with a simple drag and drop layouts. Syntax: dragulaInput(inputId, sourceLabel, targetsLabels, targetsIds = NULL, choices = NULL, choiceNames = NULL, choiceValues = NULL, status = “primary”, replace = FALSE, badge = TRUE, width = NULL, height = “200px”) Parameter Description List of values to select from. If this argument is provided, then choiceNames and choiceValues must not be provided, and vice-versa. List of names and values, respectively, that are displayed to the user in the app and correspond to the each choice (for this reason, choiceNames and choiceValues must have the same length). List of names and values, respectively, that are displayed to the user in the app and correspond to the each choice (for this reason, choiceNames and choiceValues must have the same length). If choices are displayed into a Bootstrap label, you can use Bootstrap status to color them, or NULL. When a choice is dragged in a target container already containing a choice, does the later be replaced by the new one ?#’ Example: R # Import shiny and# esquisse packageslibrary("shiny")library("esquisse") ui <- fluidPage( tags$h2("dragulaInput demo for geeksforgeeks"), tags$br(), # using dragulaInput() # to create a drag and # drop widget dragulaInput( inputId = "data_di", sourceLabel = "Source", targetsLabels = c("Drop Here", "Drop Here 2"), choices = names(rock), width = "400px"), verbatimTextOutput(outputId = "result")) server <- function(input, output, session){ output$result <- renderPrint(str(input$data_di))} shinyApp(ui = ui, server = server) Output: esquisser: It is an add-in to easily create plots with ggplot2. ggplot2 is a system for declaratively creating graphics. Just provide the data, tell ggplot2 how to map variables to aesthetics, what graphical primitives to use, and it takes handles rest all on its own. Syntax: esquisser(data = NULL) Parameter Description Example: R # Import shiny and# esquisse packageslibrary("shiny")library("esquisse") esquisser(rock) Output: updateDragulaInput: Update Dragula Input. It updates the drag and drop widgets as soon as the call is passed to the function. For instance, if a label is dragged and dropped from the input, the function updates the set of provided input values in the output. Syntax: updateDragulaInput(session, inputId, choices = NULL, choiceNames = NULL, choiceValues = NULL, badge = TRUE, status = “primary”) Parameter Description List of values to select from. If this argument is provided, then choiceNames and choiceValues must not be provided, and vice-versa choiceNames choiceValues List of names and values, respectively, that are displayed to the user in the app and correspond to the each choice (for this reason, choiceNames and choiceValues must have the same length). If either of these arguments is provided, then the other must be provided and choices must not be provided. Example: R # Import shiny and# esquisse packageslibrary("shiny")library("esquisse") ui <- fluidPage( tags$h2("GfG demo for Update dragulaInput"), radioButtons( inputId = "update", label = "Dataset", choices = c("iris", "rock")), tags$br(), dragulaInput( inputId = "data", sourceLabel = "Variables", targetsLabels = c("X", "Y", "fill", "color", "size"), choices = names(iris), replace = TRUE, width = "400px", status = "success"), verbatimTextOutput(outputId = "result")) server <- function(input, output, session){ output$result <- renderPrint(str(input$data)) observeEvent(input$update, { if (input$update == "iris") { updateDragulaInput( session = session, inputId = "data", choices = names(iris), status = "success") } else { updateDragulaInput( session = session, inputId = "data", choices = names(rock)) } }, ignoreInit = TRUE) } shinyApp(ui, server) Output: ggplot_to_plot: Utility To Export ggplot Objects To PowerPoint. This utility function provides an easy way to save graphs and models layed using ggplot to a .ppt file or simply a PowerPoint presentation. Syntax: ggplot_to_ppt(gg = NULL) Parameter Description Example: R # import ggplot2 librarylibrary(ggplot2)p <- ggplot(iris) + geom_point(aes(Sepal.Length, Sepal.Width)) # use ggplot_to_plot# to display plot# in a ppt formatggplot_to_ppt("p") Output: The code displays the output in a ppt format. Output to the above piece of code can be seen via this link. simmytarika5 R Data-science R Machine-Learning R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column? R - if statement Logistic Regression in R Programming Replace Specific Characters in String in R How to import an Excel File into R ? Joining of Dataframes in R Programming
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Dec, 2021" }, { "code": null, "e": 638, "s": 28, "text": "Packages in the R programming are a collection of R functions, compiled code, and sample data. They are stored under a directory called “library” in the R environment. By default, R installs a set of packages during installation. One of the most important packages in R is the Esquisse package. Esquisse package helps to explore and visualize your data interactively. It is a Shiny gadget to create ggplot charts interactively with drag-and-drop to map your variables. One can quickly visualize the data accordingly to their type, export to ‘PNG’ or ‘PowerPoint’, and retrieve the code to reproduce the chart." }, { "code": null, "e": 789, "s": 638, "text": "To use a package in R programming one must have to install the package first. This task can be done using the command install.packages(“packagename”)." }, { "code": null, "e": 871, "s": 789, "text": "source(\"https://install-github.me/dreamRs/esquisse\")\ninstall.packages(\"esquisse\")" }, { "code": null, "e": 929, "s": 871, "text": "To install the development version from GitHub type this:" }, { "code": null, "e": 994, "s": 929, "text": "# or with devtools:\ndevtools::install_github(\"dreamRs/esquisse\")" }, { "code": null, "e": 1215, "s": 994, "text": "chooseData-Module: It is a module for choosing data.frame from the user environment and select variable to use. It gives the user an option to choose from a given list of available datasets to work on within a shiny app." }, { "code": null, "e": 1224, "s": 1215, "text": "Syntax: " }, { "code": null, "e": 1241, "s": 1224, "text": "chooseDataUI(id)" }, { "code": null, "e": 1308, "s": 1241, "text": "chooseDataServer(input, output, session, data = NULL, name = NULL," }, { "code": null, "e": 1397, "s": 1308, "text": " selectVars = TRUE, launchOnStart = TRUE, defaultData = NULL)" }, { "code": null, "e": 1407, "s": 1397, "text": "Parameter" }, { "code": null, "e": 1419, "s": 1407, "text": "Description" }, { "code": null, "e": 1479, "s": 1419, "text": " A character vector of data.frames to choose along if there" }, { "code": null, "e": 1521, "s": 1479, "text": " is no data.frames in Global environment." }, { "code": null, "e": 1569, "s": 1521, "text": " By default, data.frames from ggplot2 are used." }, { "code": null, "e": 1579, "s": 1569, "text": "Example: " }, { "code": null, "e": 1581, "s": 1579, "text": "R" }, { "code": "# Import shiny and# esquisse packageslibrary(shiny)library(esquisse) ui <- fluidPage( tags$h2(\"Choose data module\"), fluidRow( column( width = 4, tags$h4(\"Default\"), # Using chooseDataUI chooseDataUI(id = \"choose1\"), verbatimTextOutput(outputId = \"res1\")))) server <- function(input, output, session){ res_dat1 <- callModule( chooseDataServer, id = \"choose1\", launchOnStart = FALSE) output$res1 <- renderPrint({ str(reactiveValuesToList(res_dat1))})} shinyApp(ui,server)", "e": 2094, "s": 1581, "text": null }, { "code": null, "e": 2102, "s": 2094, "text": "Output:" }, { "code": null, "e": 2308, "s": 2102, "text": "dragulaInput: It creates a Drag And Drop Input Widget. One can select different labels(data) from a variety of labels provided by the developer to the app user to twerk with a simple drag and drop layouts." }, { "code": null, "e": 2385, "s": 2308, "text": "Syntax: dragulaInput(inputId, sourceLabel, targetsLabels, targetsIds = NULL," }, { "code": null, "e": 2476, "s": 2385, "text": " choices = NULL, choiceNames = NULL, choiceValues = NULL," }, { "code": null, "e": 2575, "s": 2476, "text": " status = “primary”, replace = FALSE, badge = TRUE, width = NULL," }, { "code": null, "e": 2626, "s": 2575, "text": " height = “200px”)" }, { "code": null, "e": 2636, "s": 2626, "text": "Parameter" }, { "code": null, "e": 2648, "s": 2636, "text": "Description" }, { "code": null, "e": 2710, "s": 2648, "text": "List of values to select from. If this argument is provided, " }, { "code": null, "e": 2766, "s": 2710, "text": "then choiceNames and choiceValues must not be provided," }, { "code": null, "e": 2783, "s": 2766, "text": " and vice-versa." }, { "code": null, "e": 2843, "s": 2783, "text": "List of names and values, respectively, that are displayed " }, { "code": null, "e": 2881, "s": 2843, "text": "to the user in the app and correspond" }, { "code": null, "e": 2936, "s": 2881, "text": " to the each choice (for this reason, choiceNames and " }, { "code": null, "e": 2977, "s": 2936, "text": "choiceValues must have the same length)." }, { "code": null, "e": 3036, "s": 2977, "text": "List of names and values, respectively, that are displayed" }, { "code": null, "e": 3075, "s": 3036, "text": " to the user in the app and correspond" }, { "code": null, "e": 3126, "s": 3075, "text": " to the each choice (for this reason, choiceNames " }, { "code": null, "e": 3171, "s": 3126, "text": "and choiceValues must have the same length)." }, { "code": null, "e": 3225, "s": 3171, "text": "If choices are displayed into a Bootstrap label, you " }, { "code": null, "e": 3274, "s": 3225, "text": "can use Bootstrap status to color them, or NULL." }, { "code": null, "e": 3330, "s": 3274, "text": "When a choice is dragged in a target container already " }, { "code": null, "e": 3397, "s": 3330, "text": "containing a choice, does the later be replaced by the new one ?#’" }, { "code": null, "e": 3406, "s": 3397, "text": "Example:" }, { "code": null, "e": 3408, "s": 3406, "text": "R" }, { "code": "# Import shiny and# esquisse packageslibrary(\"shiny\")library(\"esquisse\") ui <- fluidPage( tags$h2(\"dragulaInput demo for geeksforgeeks\"), tags$br(), # using dragulaInput() # to create a drag and # drop widget dragulaInput( inputId = \"data_di\", sourceLabel = \"Source\", targetsLabels = c(\"Drop Here\", \"Drop Here 2\"), choices = names(rock), width = \"400px\"), verbatimTextOutput(outputId = \"result\")) server <- function(input, output, session){ output$result <- renderPrint(str(input$data_di))} shinyApp(ui = ui, server = server)", "e": 3953, "s": 3408, "text": null }, { "code": null, "e": 3961, "s": 3953, "text": "Output:" }, { "code": null, "e": 4230, "s": 3961, "text": "esquisser: It is an add-in to easily create plots with ggplot2. ggplot2 is a system for declaratively creating graphics. Just provide the data, tell ggplot2 how to map variables to aesthetics, what graphical primitives to use, and it takes handles rest all on its own." }, { "code": null, "e": 4261, "s": 4230, "text": "Syntax: esquisser(data = NULL)" }, { "code": null, "e": 4271, "s": 4261, "text": "Parameter" }, { "code": null, "e": 4283, "s": 4271, "text": "Description" }, { "code": null, "e": 4292, "s": 4283, "text": "Example:" }, { "code": null, "e": 4294, "s": 4292, "text": "R" }, { "code": "# Import shiny and# esquisse packageslibrary(\"shiny\")library(\"esquisse\") esquisser(rock)", "e": 4385, "s": 4294, "text": null }, { "code": null, "e": 4393, "s": 4385, "text": "Output:" }, { "code": null, "e": 4652, "s": 4393, "text": "updateDragulaInput: Update Dragula Input. It updates the drag and drop widgets as soon as the call is passed to the function. For instance, if a label is dragged and dropped from the input, the function updates the set of provided input values in the output." }, { "code": null, "e": 4733, "s": 4652, "text": "Syntax: updateDragulaInput(session, inputId, choices = NULL, choiceNames = NULL," }, { "code": null, "e": 4834, "s": 4733, "text": " choiceValues = NULL, badge = TRUE, status = “primary”)" }, { "code": null, "e": 4844, "s": 4834, "text": "Parameter" }, { "code": null, "e": 4856, "s": 4844, "text": "Description" }, { "code": null, "e": 4935, "s": 4856, "text": "List of values to select from. If this argument is provided, then choiceNames " }, { "code": null, "e": 4989, "s": 4935, "text": "and choiceValues must not be provided, and vice-versa" }, { "code": null, "e": 5001, "s": 4989, "text": "choiceNames" }, { "code": null, "e": 5014, "s": 5001, "text": "choiceValues" }, { "code": null, "e": 5111, "s": 5014, "text": "List of names and values, respectively, that are displayed to the user in the app and correspond" }, { "code": null, "e": 5206, "s": 5111, "text": "to the each choice (for this reason, choiceNames and choiceValues must have the same length). " }, { "code": null, "e": 5314, "s": 5206, "text": "If either of these arguments is provided, then the other must be provided and choices must not be provided." }, { "code": null, "e": 5323, "s": 5314, "text": "Example:" }, { "code": null, "e": 5325, "s": 5323, "text": "R" }, { "code": "# Import shiny and# esquisse packageslibrary(\"shiny\")library(\"esquisse\") ui <- fluidPage( tags$h2(\"GfG demo for Update dragulaInput\"), radioButtons( inputId = \"update\", label = \"Dataset\", choices = c(\"iris\", \"rock\")), tags$br(), dragulaInput( inputId = \"data\", sourceLabel = \"Variables\", targetsLabels = c(\"X\", \"Y\", \"fill\", \"color\", \"size\"), choices = names(iris), replace = TRUE, width = \"400px\", status = \"success\"), verbatimTextOutput(outputId = \"result\")) server <- function(input, output, session){ output$result <- renderPrint(str(input$data)) observeEvent(input$update, { if (input$update == \"iris\") { updateDragulaInput( session = session, inputId = \"data\", choices = names(iris), status = \"success\") } else { updateDragulaInput( session = session, inputId = \"data\", choices = names(rock)) } }, ignoreInit = TRUE) } shinyApp(ui, server)", "e": 6256, "s": 5325, "text": null }, { "code": null, "e": 6264, "s": 6256, "text": "Output:" }, { "code": null, "e": 6468, "s": 6264, "text": "ggplot_to_plot: Utility To Export ggplot Objects To PowerPoint. This utility function provides an easy way to save graphs and models layed using ggplot to a .ppt file or simply a PowerPoint presentation." }, { "code": null, "e": 6501, "s": 6468, "text": "Syntax: ggplot_to_ppt(gg = NULL)" }, { "code": null, "e": 6511, "s": 6501, "text": "Parameter" }, { "code": null, "e": 6523, "s": 6511, "text": "Description" }, { "code": null, "e": 6532, "s": 6523, "text": "Example:" }, { "code": null, "e": 6534, "s": 6532, "text": "R" }, { "code": "# import ggplot2 librarylibrary(ggplot2)p <- ggplot(iris) + geom_point(aes(Sepal.Length, Sepal.Width)) # use ggplot_to_plot# to display plot# in a ppt formatggplot_to_ppt(\"p\")", "e": 6714, "s": 6534, "text": null }, { "code": null, "e": 6722, "s": 6714, "text": "Output:" }, { "code": null, "e": 6829, "s": 6722, "text": "The code displays the output in a ppt format. Output to the above piece of code can be seen via this link." }, { "code": null, "e": 6844, "s": 6831, "text": "simmytarika5" }, { "code": null, "e": 6859, "s": 6844, "text": "R Data-science" }, { "code": null, "e": 6878, "s": 6859, "text": "R Machine-Learning" }, { "code": null, "e": 6889, "s": 6878, "text": "R Language" }, { "code": null, "e": 6987, "s": 6889, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7039, "s": 6987, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 7097, "s": 7039, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 7132, "s": 7097, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 7170, "s": 7132, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 7219, "s": 7170, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 7236, "s": 7219, "text": "R - if statement" }, { "code": null, "e": 7273, "s": 7236, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 7316, "s": 7273, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 7353, "s": 7316, "text": "How to import an Excel File into R ?" } ]
Turtle Programming in Python
18 Oct, 2021 “Turtle” is a Python feature like a drawing board, which lets us command a turtle to draw all over it! We can use functions like turtle.forward(...) and turtle.right(...) which can move the turtle around. Commonly used turtle methods are : Plotting using Turtle To make use of the turtle methods and functionalities, we need to import turtle.”turtle” comes packed with the standard Python package and need not be installed externally. The roadmap for executing a turtle program follows 4 steps: Import the turtle moduleCreate a turtle to control.Draw around using the turtle methods.Run turtle.done(). Import the turtle module Create a turtle to control. Draw around using the turtle methods. Run turtle.done(). So as stated above, before we can use turtle, we need to import it. We import it as : from turtle import * # or import turtle After importing the turtle library and making all the turtle functionalities available to us, we need to create a new drawing board(window) and a turtle. Let’s call the window as wn and the turtle as skk. So we code as: wn = turtle.Screen() wn.bgcolor("light green") wn.title("Turtle") skk = turtle.Turtle() Now that we have created the window and the turtle, we need to move the turtle. To move forward 100 pixels in the direction skk is facing, we code: skk.forward(100) We have moved skk 100 pixels forward, Awesome! Now we complete the program with the done() function and We’re done! turtle.done() So, we have created a program that draws a line 100 pixels long. We can draw various shapes and fill different colors using turtle methods. There’s plethora of functions and programs to be coded using the turtle library in python. Let’s learn to draw some of the basic shapes. Shape 1: Square Python # Python program to draw square# using Turtle Programmingimport turtleskk = turtle.Turtle() for i in range(4): skk.forward(50) skk.right(90) turtle.done() Output: Shape 2: Star Python3 # Python program to draw star# using Turtle Programmingimport turtlestar = turtle.Turtle() star.right(75)star.forward(100) for i in range(4): star.right(144) star.forward(100) turtle.done() Output: Shape 3: Hexagon Python # Python program to draw hexagon# using Turtle Programmingimport turtlepolygon = turtle.Turtle() num_sides = 6side_length = 70angle = 360.0 / num_sides for i in range(num_sides): polygon.forward(side_length) polygon.right(angle) turtle.done() Output: Visit pythonturtle.org to get a taste of Turtle without having python pre-installed. The shell in PythonTurtle is a full Python shell, and you can do with it almost anything you can with a standard Python shell. You can make loops, define functions, create classes, etc. You can access these codes for wonderful turtle programs here 1. Spiral Square Outside In and Inside Out Python # Python program to draw# Spiral Square Outside In and Inside Out# using Turtle Programmingimport turtle #Outside_Inwn = turtle.Screen()wn.bgcolor("light green")wn.title("Turtle")skk = turtle.Turtle()skk.color("blue") def sqrfunc(size): for i in range(4): skk.fd(size) skk.left(90) size = size-5 sqrfunc(146)sqrfunc(126)sqrfunc(106)sqrfunc(86)sqrfunc(66)sqrfunc(46)sqrfunc(26) Python import turtle #Inside_Outwn = turtle.Screen()wn.bgcolor("light green")skk = turtle.Turtle()skk.color("blue") def sqrfunc(size): for i in range(4): skk.fd(size) skk.left(90) size = size + 5 sqrfunc(6)sqrfunc(26)sqrfunc(46)sqrfunc(66)sqrfunc(86)sqrfunc(106)sqrfunc(126)sqrfunc(146) Output: https://www.youtube.com/watch?v=QPf 2. User Input Pattern Python # Python program to user input pattern# using Turtle Programmingimport turtle #Outside_Inimport turtleimport timeimport random print ("This program draws shapes based on the number you enter in a uniform pattern.")num_str = input("Enter the side number of the shape you want to draw: ")if num_str.isdigit(): squares = int(num_str) angle = 180 - 180*(squares-2)/squares turtle.up x = 0y = 0turtle.setpos(x, y) numshapes = 8for x in range(numshapes): turtle.color(random.random(), random.random(), random.random()) x += 5 y += 5 turtle.forward(x) turtle.left(y) for i in range(squares): turtle.begin_fill() turtle.down() turtle.forward(40) turtle.left(angle) turtle.forward(40) print (turtle.pos()) turtle.up() turtle.end_fill() time.sleep(11)turtle.bye() 3. Spiral Helix Pattern Python # Python program to draw# Spiral Helix Pattern# using Turtle Programming import turtleloadWindow = turtle.Screen()turtle.speed(2) for i in range(100): turtle.circle(5*i) turtle.circle(-5*i) turtle.left(i) turtle.exitonclick() Output: Turtle Programming in Python - YouTubeAmartya R Saikia277 subscribersTurtle Programming in PythonWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:01•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=_FxzEAIWvtE" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> 4. Rainbow Benzene Python # Python program to draw# Rainbow Benzene# using Turtle Programmingimport turtlecolors = ['red', 'purple', 'blue', 'green', 'orange', 'yellow']t = turtle.Pen()turtle.bgcolor('black')for x in range(360): t.pencolor(colors[x%6]) t.width(x//100 + 1) t.forward(x) t.left(59) Output: Trees using Turtle Programming Trees in Python using Turtle - YouTubeAmartya R Saikia277 subscribersTrees in Python using TurtleWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 0:29•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=NA1yaRGAjbY" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> References: Turtle documentation for Python 3 and 2 eecs.wsu.edu [PDF] ! This article is contributed by Amartya Ranjan Saikia. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. anshitaagarwal raaschatterjee11 allanturning94 sumitgumber28 Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 54, "s": 26, "text": "\n18 Oct, 2021" }, { "code": null, "e": 295, "s": 54, "text": "“Turtle” is a Python feature like a drawing board, which lets us command a turtle to draw all over it! We can use functions like turtle.forward(...) and turtle.right(...) which can move the turtle around. Commonly used turtle methods are : " }, { "code": null, "e": 317, "s": 295, "text": "Plotting using Turtle" }, { "code": null, "e": 552, "s": 317, "text": "To make use of the turtle methods and functionalities, we need to import turtle.”turtle” comes packed with the standard Python package and need not be installed externally. The roadmap for executing a turtle program follows 4 steps: " }, { "code": null, "e": 659, "s": 552, "text": "Import the turtle moduleCreate a turtle to control.Draw around using the turtle methods.Run turtle.done()." }, { "code": null, "e": 684, "s": 659, "text": "Import the turtle module" }, { "code": null, "e": 712, "s": 684, "text": "Create a turtle to control." }, { "code": null, "e": 750, "s": 712, "text": "Draw around using the turtle methods." }, { "code": null, "e": 769, "s": 750, "text": "Run turtle.done()." }, { "code": null, "e": 856, "s": 769, "text": "So as stated above, before we can use turtle, we need to import it. We import it as : " }, { "code": null, "e": 896, "s": 856, "text": "from turtle import *\n# or\nimport turtle" }, { "code": null, "e": 1117, "s": 896, "text": "After importing the turtle library and making all the turtle functionalities available to us, we need to create a new drawing board(window) and a turtle. Let’s call the window as wn and the turtle as skk. So we code as: " }, { "code": null, "e": 1205, "s": 1117, "text": "wn = turtle.Screen()\nwn.bgcolor(\"light green\")\nwn.title(\"Turtle\")\nskk = turtle.Turtle()" }, { "code": null, "e": 1354, "s": 1205, "text": "Now that we have created the window and the turtle, we need to move the turtle. To move forward 100 pixels in the direction skk is facing, we code: " }, { "code": null, "e": 1371, "s": 1354, "text": "skk.forward(100)" }, { "code": null, "e": 1488, "s": 1371, "text": "We have moved skk 100 pixels forward, Awesome! Now we complete the program with the done() function and We’re done! " }, { "code": null, "e": 1502, "s": 1488, "text": "turtle.done()" }, { "code": null, "e": 1781, "s": 1502, "text": "So, we have created a program that draws a line 100 pixels long. We can draw various shapes and fill different colors using turtle methods. There’s plethora of functions and programs to be coded using the turtle library in python. Let’s learn to draw some of the basic shapes. " }, { "code": null, "e": 1797, "s": 1781, "text": "Shape 1: Square" }, { "code": null, "e": 1804, "s": 1797, "text": "Python" }, { "code": "# Python program to draw square# using Turtle Programmingimport turtleskk = turtle.Turtle() for i in range(4): skk.forward(50) skk.right(90) turtle.done()", "e": 1969, "s": 1804, "text": null }, { "code": null, "e": 1977, "s": 1969, "text": "Output:" }, { "code": null, "e": 1991, "s": 1977, "text": "Shape 2: Star" }, { "code": null, "e": 1999, "s": 1991, "text": "Python3" }, { "code": "# Python program to draw star# using Turtle Programmingimport turtlestar = turtle.Turtle() star.right(75)star.forward(100) for i in range(4): star.right(144) star.forward(100) turtle.done()", "e": 2199, "s": 1999, "text": null }, { "code": null, "e": 2207, "s": 2199, "text": "Output:" }, { "code": null, "e": 2224, "s": 2207, "text": "Shape 3: Hexagon" }, { "code": null, "e": 2231, "s": 2224, "text": "Python" }, { "code": "# Python program to draw hexagon# using Turtle Programmingimport turtlepolygon = turtle.Turtle() num_sides = 6side_length = 70angle = 360.0 / num_sides for i in range(num_sides): polygon.forward(side_length) polygon.right(angle) turtle.done()", "e": 2484, "s": 2231, "text": null }, { "code": null, "e": 2492, "s": 2484, "text": "Output:" }, { "code": null, "e": 2827, "s": 2492, "text": "Visit pythonturtle.org to get a taste of Turtle without having python pre-installed. The shell in PythonTurtle is a full Python shell, and you can do with it almost anything you can with a standard Python shell. You can make loops, define functions, create classes, etc. You can access these codes for wonderful turtle programs here " }, { "code": null, "e": 2871, "s": 2827, "text": "1. Spiral Square Outside In and Inside Out " }, { "code": null, "e": 2878, "s": 2871, "text": "Python" }, { "code": "# Python program to draw# Spiral Square Outside In and Inside Out# using Turtle Programmingimport turtle #Outside_Inwn = turtle.Screen()wn.bgcolor(\"light green\")wn.title(\"Turtle\")skk = turtle.Turtle()skk.color(\"blue\") def sqrfunc(size): for i in range(4): skk.fd(size) skk.left(90) size = size-5 sqrfunc(146)sqrfunc(126)sqrfunc(106)sqrfunc(86)sqrfunc(66)sqrfunc(46)sqrfunc(26)", "e": 3281, "s": 2878, "text": null }, { "code": null, "e": 3288, "s": 3281, "text": "Python" }, { "code": "import turtle #Inside_Outwn = turtle.Screen()wn.bgcolor(\"light green\")skk = turtle.Turtle()skk.color(\"blue\") def sqrfunc(size): for i in range(4): skk.fd(size) skk.left(90) size = size + 5 sqrfunc(6)sqrfunc(26)sqrfunc(46)sqrfunc(66)sqrfunc(86)sqrfunc(106)sqrfunc(126)sqrfunc(146)", "e": 3593, "s": 3288, "text": null }, { "code": null, "e": 3603, "s": 3593, "text": "Output: " }, { "code": null, "e": 3639, "s": 3603, "text": "https://www.youtube.com/watch?v=QPf" }, { "code": null, "e": 3662, "s": 3639, "text": "2. User Input Pattern " }, { "code": null, "e": 3669, "s": 3662, "text": "Python" }, { "code": "# Python program to user input pattern# using Turtle Programmingimport turtle #Outside_Inimport turtleimport timeimport random print (\"This program draws shapes based on the number you enter in a uniform pattern.\")num_str = input(\"Enter the side number of the shape you want to draw: \")if num_str.isdigit(): squares = int(num_str) angle = 180 - 180*(squares-2)/squares turtle.up x = 0y = 0turtle.setpos(x, y) numshapes = 8for x in range(numshapes): turtle.color(random.random(), random.random(), random.random()) x += 5 y += 5 turtle.forward(x) turtle.left(y) for i in range(squares): turtle.begin_fill() turtle.down() turtle.forward(40) turtle.left(angle) turtle.forward(40) print (turtle.pos()) turtle.up() turtle.end_fill() time.sleep(11)turtle.bye()", "e": 4503, "s": 3669, "text": null }, { "code": null, "e": 4528, "s": 4503, "text": "3. Spiral Helix Pattern " }, { "code": null, "e": 4535, "s": 4528, "text": "Python" }, { "code": "# Python program to draw# Spiral Helix Pattern# using Turtle Programming import turtleloadWindow = turtle.Screen()turtle.speed(2) for i in range(100): turtle.circle(5*i) turtle.circle(-5*i) turtle.left(i) turtle.exitonclick()", "e": 4771, "s": 4535, "text": null }, { "code": null, "e": 4780, "s": 4771, "text": "Output: " }, { "code": null, "e": 5624, "s": 4780, "text": "Turtle Programming in Python - YouTubeAmartya R Saikia277 subscribersTurtle Programming in PythonWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:01•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=_FxzEAIWvtE\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 5644, "s": 5624, "text": "4. Rainbow Benzene " }, { "code": null, "e": 5651, "s": 5644, "text": "Python" }, { "code": "# Python program to draw# Rainbow Benzene# using Turtle Programmingimport turtlecolors = ['red', 'purple', 'blue', 'green', 'orange', 'yellow']t = turtle.Pen()turtle.bgcolor('black')for x in range(360): t.pencolor(colors[x%6]) t.width(x//100 + 1) t.forward(x) t.left(59)", "e": 5934, "s": 5651, "text": null }, { "code": null, "e": 5943, "s": 5934, "text": "Output: " }, { "code": null, "e": 5976, "s": 5945, "text": "Trees using Turtle Programming" }, { "code": null, "e": 6820, "s": 5976, "text": "Trees in Python using Turtle - YouTubeAmartya R Saikia277 subscribersTrees in Python using TurtleWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 0:29•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=NA1yaRGAjbY\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 6834, "s": 6820, "text": " References: " }, { "code": null, "e": 6874, "s": 6834, "text": "Turtle documentation for Python 3 and 2" }, { "code": null, "e": 6895, "s": 6874, "text": "eecs.wsu.edu [PDF] !" }, { "code": null, "e": 7328, "s": 6895, "text": "This article is contributed by Amartya Ranjan Saikia. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 7343, "s": 7328, "text": "anshitaagarwal" }, { "code": null, "e": 7360, "s": 7343, "text": "raaschatterjee11" }, { "code": null, "e": 7375, "s": 7360, "text": "allanturning94" }, { "code": null, "e": 7389, "s": 7375, "text": "sumitgumber28" }, { "code": null, "e": 7396, "s": 7389, "text": "Python" }, { "code": null, "e": 7494, "s": 7396, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7512, "s": 7494, "text": "Python Dictionary" }, { "code": null, "e": 7554, "s": 7512, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 7576, "s": 7554, "text": "Enumerate() in Python" }, { "code": null, "e": 7611, "s": 7576, "text": "Read a file line by line in Python" }, { "code": null, "e": 7637, "s": 7611, "text": "Python String | replace()" }, { "code": null, "e": 7669, "s": 7637, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 7698, "s": 7669, "text": "*args and **kwargs in Python" }, { "code": null, "e": 7725, "s": 7698, "text": "Python Classes and Objects" }, { "code": null, "e": 7755, "s": 7725, "text": "Iterate over a list in Python" } ]
Bash Script – Read User Input
14 Feb, 2022 In this article, we’ll discuss how to read user input in BASH. We can simply get user input from the read command in BASH. It provides a lot of options and arguments along with it for more flexible usage, but we’ll cover them in the next few sections. For now, let’s see how a basic read command can be used. #!usr/bin/env bash read name echo "Hello, $name" So, in the above script, the “#!/usr/bin/env bash” is the shebang operator that indicates the interpreter to run the script in the BASH environment. We have used the read command to get the user input in the variable name. The echo command is an optional command to just verify that we have stored the input in the name variable. We use $ in front of the variable command so as to fetch and parse the literal value of the variable. Read command provides a lot of arguments that can be passed to it so as to get the user input in a flexible way. Some of the few arguments are discussed here: Prompt String (-p) Password Input (-s) Changing the Delimiter (IFS) Parsing to the array (-a) Limiting Length of the Input (-n) Timed Input (-t) Using this argument, we can prompt a string before the input. This allows the user to get the idea of what to input without using echo before the read command. Let us take a look at the demonstration of the argument of prompting a string to the read command. #!usr/bin/env bash read -p "Enter your name : " name echo "Hello, $name" From the demonstration, we can see that there was a string prompt before the input from the user because we have used the “-p” argument before the input variable, which gives one more argument the string before the variable. This allows a better interface and readability of the program. We can say that this kind of built-in echo functionality is in the read command with the string prompt. Now assume that we want to type in the password in the input and how insecure it would be to display while the user is typing. Well, we have the solution for that. We can use the -s argument to silent the echo from the user input. This allows working with the read command in a secure way. #!usr/bin/env bash read -sp "Enter your password : " pswd echo -e "\nYour password is $pswd" In the above demonstration, the input is silenced i.e. the interface doesn’t print what the user is typing. But we can see that I typed 12345 and is stored and retrieved later from the variable. You can notice that we have nested the arguments -s and -p as -sp to use both the arguments together. Also, the echo command is modified as we use the -e argument to use formatted strings i.e use “\n” and other special characters in the string. Using this argument we can change the way we assign the variables the value i.e. if we want to get the multiple inputs using single read command we can do that using space-separated values. #!usr/bin/env bash read -p "Enter name age and country : " name age country echo "Name : $name" echo "Age : $age" echo "Country : $country" From the above example, we can see that it cleverly assigned the variables to the values provided. You can see that the last variable had 3 spaces so since it was the last input, it assigned itself everything but if it was not the last input, it could mess up the format. If we had provided four inputs then the word “United” would have been the country variable and the rest of the stuff in the last variable. We got a bit understanding of delimiters here, delimiters are the patterns or characters that are used to distinguish different sets of entities in our case the input variables. We can change the delimiters, by default we have space as the delimiters in the read command. Let’s look at how we can achieve that. #!usr/bin/env bash IFS="," read -p "Enter name, age, city and country : " name age city country echo "Name : $name" echo "Age : $age" echo "City : $city" echo "Country : $country" In the following example, we have used the IFS or the Internal Field Separator. We have set the IFS as “,” at the beginning of the read command. As you can see this doesn’t count the space as the separator in the variable assignment. This leads to proper and formatted inputs as desired, you can choose IFS as the character that is not used in the inputs internally otherwise it can disorient the format as expected. We can use IFS as “.“, “,“, “/“, “\“. “;“, etc. as this is not used commonly in the input and it also depends on the goal you are trying to achieve. We can parse the input directly to an array at once. We can specify the -a argument to do the same. This creates an element and assigns the array elements the input value. Let’s see the demonstration. #!usr/bin/env bash read -a array -p "Enter the elements of array : " for n in ${array[*]}; do echo "$n" done In this example, we are inputting the values to the array variable which is a list/array. The name can be anything relevant to your program. The delimiter here is as said space by default, you can use the IFS argument at the beginning of the read command to format the input as said in the above section. But here for the demonstration, I have kept it default to space. We can add the argument –a to append the input to an array provided just after that. We can verify that the read command worked and stored all the elements by iterating over the array. We can use the range-based for loops for simplicity and print the value of each element in the array. We can use the “{}” to identify the variable and [*] indicating all the elements in the array, we have the iterator as “n” which we print the value after every iteration. Hence in the output, we were able to get all the elements of the array. We can even use “[@]” instead of “[*]” as it would iterate over the array in a little different way but serve the same purpose. We can even limit the length of input in the read command. If we want the user to restrict the user with certain limitations on the input we can do this using the -n argument. #!usr/bin/env bash read -n 6 -p "Enter the name : " name echo -e "\nName : $name" In the above demonstration, we can see that even if I don’t hit Carriage Return/ Enter / Newline, the command stops after entering the 6th character in the input. Thus this can be used in limiting the user with some sensitive inputs like username, password, etc. We enter the argument -n followed by the number of characters we want to limit to. This is done to input from the user in a time-constrained way. We can specify the argument as -t and the number of seconds we want to wait till exiting from the input prompt. #!usr/bin/env bash read -p "Enter the name : " -t 8 name echo -e "\nName : $name" Thus, we can see that the prompt waited for 8 seconds but we didn’t press Enter and hence it returned with no input to the further instructions in the script if any. We can pass in the -t argument to set the timeout followed by the number of seconds to wait for the user to input the required value. rkbhola5 Bash-Script Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Docker - COPY Instruction scp command in Linux with Examples chown command in Linux with Examples SED command in Linux | Set 2 mv command in Linux with examples chmod command in Linux with examples nohup Command in Linux with Examples Introduction to Linux Operating System Array Basics in Shell Scripting | Set 1 Basic Operators in Shell Scripting
[ { "code": null, "e": 54, "s": 26, "text": "\n14 Feb, 2022" }, { "code": null, "e": 117, "s": 54, "text": "In this article, we’ll discuss how to read user input in BASH." }, { "code": null, "e": 363, "s": 117, "text": "We can simply get user input from the read command in BASH. It provides a lot of options and arguments along with it for more flexible usage, but we’ll cover them in the next few sections. For now, let’s see how a basic read command can be used." }, { "code": null, "e": 414, "s": 363, "text": "#!usr/bin/env bash\n\nread name\n\necho \"Hello, $name\"" }, { "code": null, "e": 847, "s": 414, "text": "So, in the above script, the “#!/usr/bin/env bash” is the shebang operator that indicates the interpreter to run the script in the BASH environment. We have used the read command to get the user input in the variable name. The echo command is an optional command to just verify that we have stored the input in the name variable. We use $ in front of the variable command so as to fetch and parse the literal value of the variable. " }, { "code": null, "e": 1006, "s": 847, "text": "Read command provides a lot of arguments that can be passed to it so as to get the user input in a flexible way. Some of the few arguments are discussed here:" }, { "code": null, "e": 1025, "s": 1006, "text": "Prompt String (-p)" }, { "code": null, "e": 1045, "s": 1025, "text": "Password Input (-s)" }, { "code": null, "e": 1074, "s": 1045, "text": "Changing the Delimiter (IFS)" }, { "code": null, "e": 1100, "s": 1074, "text": "Parsing to the array (-a)" }, { "code": null, "e": 1134, "s": 1100, "text": "Limiting Length of the Input (-n)" }, { "code": null, "e": 1151, "s": 1134, "text": "Timed Input (-t)" }, { "code": null, "e": 1410, "s": 1151, "text": "Using this argument, we can prompt a string before the input. This allows the user to get the idea of what to input without using echo before the read command. Let us take a look at the demonstration of the argument of prompting a string to the read command." }, { "code": null, "e": 1485, "s": 1410, "text": "#!usr/bin/env bash\n\nread -p \"Enter your name : \" name\n\necho \"Hello, $name\"" }, { "code": null, "e": 1882, "s": 1488, "text": "From the demonstration, we can see that there was a string prompt before the input from the user because we have used the “-p” argument before the input variable, which gives one more argument the string before the variable. This allows a better interface and readability of the program. We can say that this kind of built-in echo functionality is in the read command with the string prompt. " }, { "code": null, "e": 2173, "s": 1882, "text": "Now assume that we want to type in the password in the input and how insecure it would be to display while the user is typing. Well, we have the solution for that. We can use the -s argument to silent the echo from the user input. This allows working with the read command in a secure way. " }, { "code": null, "e": 2268, "s": 2173, "text": "#!usr/bin/env bash\n\nread -sp \"Enter your password : \" pswd\n\necho -e \"\\nYour password is $pswd\"" }, { "code": null, "e": 2708, "s": 2268, "text": "In the above demonstration, the input is silenced i.e. the interface doesn’t print what the user is typing. But we can see that I typed 12345 and is stored and retrieved later from the variable. You can notice that we have nested the arguments -s and -p as -sp to use both the arguments together. Also, the echo command is modified as we use the -e argument to use formatted strings i.e use “\\n” and other special characters in the string." }, { "code": null, "e": 2898, "s": 2708, "text": "Using this argument we can change the way we assign the variables the value i.e. if we want to get the multiple inputs using single read command we can do that using space-separated values." }, { "code": null, "e": 3040, "s": 2898, "text": "#!usr/bin/env bash\n\nread -p \"Enter name age and country : \" name age country\n\necho \"Name : $name\"\necho \"Age : $age\"\necho \"Country : $country\"" }, { "code": null, "e": 3313, "s": 3040, "text": "From the above example, we can see that it cleverly assigned the variables to the values provided. You can see that the last variable had 3 spaces so since it was the last input, it assigned itself everything but if it was not the last input, it could mess up the format. " }, { "code": null, "e": 3763, "s": 3313, "text": "If we had provided four inputs then the word “United” would have been the country variable and the rest of the stuff in the last variable. We got a bit understanding of delimiters here, delimiters are the patterns or characters that are used to distinguish different sets of entities in our case the input variables. We can change the delimiters, by default we have space as the delimiters in the read command. Let’s look at how we can achieve that." }, { "code": null, "e": 3945, "s": 3763, "text": "#!usr/bin/env bash\n\nIFS=\",\" read -p \"Enter name, age, city and country : \" name age city country\n\necho \"Name : $name\"\necho \"Age : $age\"\necho \"City : $city\"\necho \"Country : $country\"" }, { "code": null, "e": 4511, "s": 3945, "text": "In the following example, we have used the IFS or the Internal Field Separator. We have set the IFS as “,” at the beginning of the read command. As you can see this doesn’t count the space as the separator in the variable assignment. This leads to proper and formatted inputs as desired, you can choose IFS as the character that is not used in the inputs internally otherwise it can disorient the format as expected. We can use IFS as “.“, “,“, “/“, “\\“. “;“, etc. as this is not used commonly in the input and it also depends on the goal you are trying to achieve." }, { "code": null, "e": 4712, "s": 4511, "text": "We can parse the input directly to an array at once. We can specify the -a argument to do the same. This creates an element and assigns the array elements the input value. Let’s see the demonstration." }, { "code": null, "e": 4828, "s": 4712, "text": "#!usr/bin/env bash\n\nread -a array -p \"Enter the elements of array : \" \nfor n in ${array[*]};\ndo \n echo \"$n\"\ndone" }, { "code": null, "e": 5383, "s": 4828, "text": "In this example, we are inputting the values to the array variable which is a list/array. The name can be anything relevant to your program. The delimiter here is as said space by default, you can use the IFS argument at the beginning of the read command to format the input as said in the above section. But here for the demonstration, I have kept it default to space. We can add the argument –a to append the input to an array provided just after that. We can verify that the read command worked and stored all the elements by iterating over the array." }, { "code": null, "e": 5856, "s": 5383, "text": "We can use the range-based for loops for simplicity and print the value of each element in the array. We can use the “{}” to identify the variable and [*] indicating all the elements in the array, we have the iterator as “n” which we print the value after every iteration. Hence in the output, we were able to get all the elements of the array. We can even use “[@]” instead of “[*]” as it would iterate over the array in a little different way but serve the same purpose." }, { "code": null, "e": 6032, "s": 5856, "text": "We can even limit the length of input in the read command. If we want the user to restrict the user with certain limitations on the input we can do this using the -n argument." }, { "code": null, "e": 6115, "s": 6032, "text": "#!usr/bin/env bash\n\nread -n 6 -p \"Enter the name : \" name\necho -e \"\\nName : $name\"" }, { "code": null, "e": 6462, "s": 6115, "text": "In the above demonstration, we can see that even if I don’t hit Carriage Return/ Enter / Newline, the command stops after entering the 6th character in the input. Thus this can be used in limiting the user with some sensitive inputs like username, password, etc. We enter the argument -n followed by the number of characters we want to limit to." }, { "code": null, "e": 6638, "s": 6462, "text": "This is done to input from the user in a time-constrained way. We can specify the argument as -t and the number of seconds we want to wait till exiting from the input prompt. " }, { "code": null, "e": 6721, "s": 6638, "text": "#!usr/bin/env bash\n\nread -p \"Enter the name : \" -t 8 name\necho -e \"\\nName : $name\"" }, { "code": null, "e": 7021, "s": 6721, "text": "Thus, we can see that the prompt waited for 8 seconds but we didn’t press Enter and hence it returned with no input to the further instructions in the script if any. We can pass in the -t argument to set the timeout followed by the number of seconds to wait for the user to input the required value." }, { "code": null, "e": 7030, "s": 7021, "text": "rkbhola5" }, { "code": null, "e": 7042, "s": 7030, "text": "Bash-Script" }, { "code": null, "e": 7049, "s": 7042, "text": "Picked" }, { "code": null, "e": 7060, "s": 7049, "text": "Linux-Unix" }, { "code": null, "e": 7158, "s": 7060, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7184, "s": 7158, "text": "Docker - COPY Instruction" }, { "code": null, "e": 7219, "s": 7184, "text": "scp command in Linux with Examples" }, { "code": null, "e": 7256, "s": 7219, "text": "chown command in Linux with Examples" }, { "code": null, "e": 7285, "s": 7256, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 7319, "s": 7285, "text": "mv command in Linux with examples" }, { "code": null, "e": 7356, "s": 7319, "text": "chmod command in Linux with examples" }, { "code": null, "e": 7393, "s": 7356, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 7432, "s": 7393, "text": "Introduction to Linux Operating System" }, { "code": null, "e": 7472, "s": 7432, "text": "Array Basics in Shell Scripting | Set 1" } ]
Building a Recommendation System Using Neural Network Embeddings | by Will Koehrsen | Towards Data Science
Deep learning can do some incredible things, but often the uses are obscured in academic papers or require computing resources available only to large corporations. Nonetheless, there are applications of deep learning that can be done on a personal computer with no advanced degree required. In this article, we will see how to use neural network embeddings to create a book recommendation system using all Wikipedia articles on books. Our recommendation system will be built on the idea that books which link to similar Wikipedia pages are similar to one another. We can represent this similarity and hence make recommendations by learning embeddings of books and Wikipedia links using a neural network. The end result is an effective recommendation system and a practical application of deep learning. The complete code for this project is available as a Jupyter Notebook on GitHub. If you don’t have a GPU, you can also find the notebook on Kaggle where you can train your neural network with a GPU for free.This article will focus on the implementation, with the concepts of neural network embeddings covered in an earlier article. (To see how to retrieve the data we’ll use — all book articles on Wikipedia — take a look at this article.) This project was adapted from the Deep Learning Cookbook, an excellent book with hands-on examples for applying deep learning. Embeddings are a way to represent discrete — categorical — variables as continuous vectors. In contrast to an encoding method like one-hot encoding, neural network embeddings are low-dimensional and learned, which means they place similar entities closer to one another in the embedding space. In order to create embeddings, we need a neural network embedding model and a supervised machine learning task. The end outcome of our network will be a representation of each book as a vector of 50 continuous numbers. While the embeddings themselves are not that interesting — they are just vectors — they can be used for three primary purposes: Finding nearest neighbors in the embedding spaceAs input to a machine learning modelVisualization in low dimensions Finding nearest neighbors in the embedding space As input to a machine learning model Visualization in low dimensions This project covers primarily the first use case, but we’ll also see how to create visualizations from the embeddings. Practical applications of neural network embeddings include word embeddings for machine translation and entity embeddings for categorical variables. As usual with a data science project, we need to start with a high-quality dataset. In this article, we saw how to download and process every single article on Wikipedia, searching for any pages about books. We saved the book title, basic information, links on the book’s page that point to other Wikipedia pages (wikilinks), and links to external sites. To create the recommendation system, the only information we need are the title and wikilinks. Book Title: 'The Better Angels of Our Nature'Wikilinks: ['Steven Pinker', 'Nation state', 'commerce', 'literacy', 'Influence of mass media', 'Rationality', "Abraham Lincoln's first inaugural address", 'nature versus nurture', 'Leviathan'] Even when working with a neural network, it’s important to explore and clean the data, and in the notebook I make several corrections to the raw data. For example, looking at the most linked pages: We see that the top four pages are generic and won’t help in making recommendations. The format of a book tells us nothing about the content: knowing a book is paperback or hardcover does not allow us — or a neural network —to figure out the other books it is similar to. Therefore, we can remove these links to help the neural network distinguish between books. Thinking about the end purpose can help in the data cleaning stage and this action alone significantly improves the recommendations. Out of pure curiosity, I wanted to find the books most linked to by other books on Wikipedia. These are the 10 “most connected” Wikipedia books: This is a mix of reference works and classic books which makes sense. After data cleaning, we have a set of 41758 unique wikilinks and 37020 unique books. Hopefully there is a book in there for everyone! Once we’re confident our data is clean, we need to develop a supervised machine learning task with labeled training examples. To learn meaningful embeddings, our neural network must be trained to accomplish an objective. Working from the guiding assumption of the project — that similar books link to similar Wikipedia pages — we can formulate the problem as follows: given a (book title, wikilink) pair, determine if the wikilink is present in the book’s article. We won’t actually need to give the network the book article. Instead, we’ll feed in hundreds of thousands of training examples consisting of book title, wikilink, and label. We give the network some true examples — actually present in the dataset — and some false examples, and eventually it learns embeddings to distinguish when a wikilink is on a book’s page. Expressing the supervised learning task is the most important part of this project. Embeddings are learned for a specific task and are relevant only to that problem. If our task was to determine which books were written by Jane Austen, then the embeddings would reflect that goal, placing books written by Austen closer together in embedding space. We hope that by training to tell if a book has a certain wikilink on its page, the network learns embeddings that places similar books — in terms of content — closer to one another. Once we’ve outlined the learning task, we need to implement it in code. To get started, because the neural network can only accept integer inputs, we create a mapping from each unique book to an integer: # Mapping of books to index and index to booksbook_index = {book[0]: idx for idx, book in enumerate(books)}book_index['Anna Karenina']22494 We also do the same thing with the links. After this, to create a training set, we make a list of all (book, wikilink) pairs in the data. This requires iterating through each book and recording an example for each wikilink on its page: pairs = []# Iterate through each bookfor book in books: title = book[0] book_links = book[2] # Iterate through wikilinks in book article for link in book_links: # Add index of book and index of link to pairs pairs.extend((book_index[title], link_index[link])) This gives us a total of 772798 true examples that we can sample from to train the model. To generate the false examples — done later — we’ll simply pick a link index and book index at random, make sure it’s not in the pairs, and then use it as a negative observation. Note about Training / Testing Sets While using a separate validation and testing set is a must for a normal supervised machine learning task, in this case, our primary objective is not to make the most accurate model, but to generate embeddings. The prediction task is just the means by which we train our network for those embeddings. At the end of training, we are not going to be testing our model on new data, so we don’t need to evaluate the performance or use a validation set to prevent overfitting. To get the best embeddings, we’ll use all examples for training. Although neural network embeddings sound technically complex, they are relatively easy to implement with the Keras deep learning framework. (I recommend starting with Keras if you are new to deep learning. TensorFlow may give you more control, but Keras cannot be beat for development). The embedding model has 5 layers: Input: parallel inputs for the book and linkEmbedding: parallel length 50 embeddings for the book and linkDot: merges embeddings by computing dot productReshape: needed to shape the dot product to a single numberDense: one output neuron with sigmoid activation Input: parallel inputs for the book and link Embedding: parallel length 50 embeddings for the book and link Dot: merges embeddings by computing dot product Reshape: needed to shape the dot product to a single number Dense: one output neuron with sigmoid activation In an embedding neural network, the embeddings are the parameters — weights — of the neural network that are adjusted during training in order to minimize loss on the objective. The neural network takes in a book and a link as integers and outputs a prediction between 0 and 1 that is compared to the true value. The model is compiled with the Adam optimizer (a variant on Stochastic Gradient Descent) which, during training, alters the embeddings to minimize the binary_crossentropy for this binary classification problem. Below is the code for the complete model: This same framework can be used for many embedding models. The important point to understand is that the embeddings are the model parameters (weights) and also the final result we want. We don’t really care if the model is accurate, what we want is relevant embeddings. We’re used to the weights in a model being a means to make accurate predictions, but in an embedding model, the weights are the objective and the predictions are a means to learn an embedding. There are almost 4 million weights as shown by the model summary: With this approach, we’ll get embeddings not only for books, but also for links which means we can compare all Wikipedia pages that are linked to by books. Neural networks are batch learners because they are trained on a small set of samples — observations — at a time over many rounds called epochs. A common approach for training neural networks is to use a generator. This is a function that yields (not returns) batches of samples so the entire result is not held in memory. Although it’s not an issue in this problem, the benefit of a generator is that large training sets do not need to all be loaded into memory. Our generator takes in the training pairs, the number of positive samples per batch ( n_positive ) , and the ratio of negative:positive samples per batch ( negative_ratio ). The generator yields a new batch of positive and negative samples each time it is called. To get positive examples, we randomly sample true pairs. For the negative examples, we randomly sample a book and link, make sure this pairing is not in the true pairs, and then add it to the batch. The code below shows the generator in its entirety. Each time we call next on the generator, we get a new training batch. next(generate_batch(pairs, n_positive = 2, negative_ratio = 2))({'book': array([ 6895., 29814., 22162., 7206., 25757., 28410.]), 'link': array([ 260., 11452., 5588., 34924., 22920., 33217.])}, array([ 1., -1., 1., -1., -1., -1.])) With a supervised task, a training generator, and an embedding model, we’re ready to learn book embeddings. There are a few training parameters to select. The first is the number of positive examples in each batch. Generally, I try to start with a small batch size and increase it until performance starts to decline. Also, we need to choose the number of negative examples trained for each positive example. I’d recommend experimenting with a few options to see what works best. Since we’re not using a validation set to implement early stopping, I choose a number of epochs beyond which the training loss does not decrease. n_positive = 1024gen = generate_batch(pairs, n_positive, negative_ratio = 2)# Trainh = model.fit_generator(gen, epochs = 15, steps_per_epoch = len(pairs) // n_positive) (If the training parameters seem arbitrary, in a sense they are, but based on best practices outlined in Deep Learning. Like most aspects of machine learning, training a neural network is largely empirical.) Once the network is done training, we can extract the embeddings. # Extract embeddingsbook_layer = model.get_layer('book_embedding')book_weights = book_layer.get_weights()[0] The embeddings themselves are fairly uninteresting: they are just 50-number vectors for each book and each link: However, we can use these vectors for two different purposes, the first of which is to make our book recommendation system. To find the closest book to a query book in the embedding space, we take the vector for that book and find its dot product with the vectors for all other books. If our embeddings are normalized, then the dot product between the vectors represents the cosine similarity, ranging from -1, most dissimilar, to +1, most similar. Querying the embeddings for the classic War and Peace by Leo Tolstoy yields: Books closest to War and Peace.Book: Anna Karenina Similarity: 0.92Book: The Master and Margarita Similarity: 0.92Book: Demons (Dostoevsky novel) Similarity: 0.91Book: The Idiot Similarity: 0.9Book: Crime and Punishment Similarity: 0.9 The recommendations make sense! These are all classic Russian novels. Sure we could have gone to GoodReads for these same recommendations, but why not build the system ourselves? I encourage you to work with the notebook and explore the embeddings yourself. Books closest to The Fellowship of the Ring.Book: The Return of the King Similarity: 0.96Book: The Silmarillion Similarity: 0.93Book: Beren and Lúthien Similarity: 0.91Book: The Two Towers Similarity: 0.91 In addition to embedding the books, we also embedded the links which means we can find the most similar links to a given Wikipedia page: Pages closest to steven pinker.Page: the blank slate Similarity: 0.83Page: evolutionary psychology Similarity: 0.83Page: reductionism Similarity: 0.81Page: how the mind works Similarity: 0.79 Currently, I’m reading a fantastic collection of essays by Stephen Jay Gould called Bully for Brontosaurus. What should I read next? One of the most intriguing aspects of embeddings are that they can be used to visualize concepts such as novel or nonfiction relative to one another. This requires a further dimension reduction technique to get the dimensions to 2 or 3. The most popular technique for reduction is another embedding method: t-Distributed Stochastic Neighbor Embedding (TSNE). Starting with the 37,000-dimensional space of all books on Wikipedia, we map it to 50 dimensions using embeddings, and then to just 2 dimensions with TSNE. This results in the following image: By itself this image is not that illuminating, but once we start coloring it by book characteristics, we start to see clusters emerge: There are some definite clumps (only the top 10 genres are highlighted) with non-fiction and science fiction having distinct sections. The novels seem to be all over the place which makes sense given the diversity in novel content. We can also do embeddings with the country: I was a little surprised at how distinctive the countries are! Evidently Australian books are quite unique. Furthermore, we can highlight certain books in the Wikipedia map: There are a lot more visualizations in the notebook and you make your own. I’ll leave you with one more showing the 10 “most connected” books: One thing to note about TSNE is that it tries to preserve distances between vectors in the original space, but because it reduces the number of dimensions, it may distort the original separation. Therefore, books that are close to one another in the 50-dimensional embedding space may not be closest neighbors in the 2-dimensional TSNE embedding. These visualizations are pretty interesting, but we can make stunning interactive figures with TensorFlow’s projector tool specifically designed for visualizing neural network embeddings. I plan on writing an article on how to use this tool, but for now here are some of the results: To explore a sample of the books interactively, head here. Data science projects aren’t usually invented entirely on their own. A lot of the projects I work on are ideas from other data scientists that I adapt, improve, and build on to make a unique project. (This project was inspired by a similar project for movie recommendations in the Deep Learning Cookbook.) With that attitude in mind, here are a few ways to build on this work: Create embeddings using the external links instead of wikilinks. These are to web pages outside Wikipedia and might produce different embeddings.Use the embeddings to train a supervised machine learning model to predict the book characteristics which include genre, author, and country.Pick a topic category on Wikipedia and create your own recommendation system. You could use people, landmarks, or even historical events. You can use this notebook to get the data and this notebook for embeddings. Create embeddings using the external links instead of wikilinks. These are to web pages outside Wikipedia and might produce different embeddings. Use the embeddings to train a supervised machine learning model to predict the book characteristics which include genre, author, and country. Pick a topic category on Wikipedia and create your own recommendation system. You could use people, landmarks, or even historical events. You can use this notebook to get the data and this notebook for embeddings. This is by no means a homework assignment, just some project ideas if you want to put what you’ve read into practice. If you do decide to take on a project, I’d enjoy hearing about it! Neural network embeddings are a method to represent discrete categorical variables as continuous vectors. As a learned low-dimensional representation, they are useful for finding similar categories, as input into a machine learning model, or to visualize maps of concepts. In this project, we used neural network embeddings to create an effective book recommendation system built on the idea that books which link to similar pages are similar to each other. The steps for creating neural network embeddings are: Gather data. Neural networks require many training examples.Formulate a supervised task to learn embeddings that reflect the problem.Build and train an embedding neural network model.Extract the embeddings for making recommendations and visualizations. Gather data. Neural networks require many training examples. Formulate a supervised task to learn embeddings that reflect the problem. Build and train an embedding neural network model. Extract the embeddings for making recommendations and visualizations. The details can be found in the notebook and I’d encourage anyone to build on this project. While deep learning may seem overwhelming because of technical complexity or computational resources, this is one of many applications that can be done on a personal computer with a limited amount of studying. Deep learning is a constantly evolving field, and this project is a good way to get started by building a useful system. And, when you’re not studying deep learning, now you know what you should be reading! As always, I welcome feedback and constructive criticism. I can be reached on Twitter @koehrsen_will or on my personal website at willk.online.
[ { "code": null, "e": 607, "s": 171, "text": "Deep learning can do some incredible things, but often the uses are obscured in academic papers or require computing resources available only to large corporations. Nonetheless, there are applications of deep learning that can be done on a personal computer with no advanced degree required. In this article, we will see how to use neural network embeddings to create a book recommendation system using all Wikipedia articles on books." }, { "code": null, "e": 975, "s": 607, "text": "Our recommendation system will be built on the idea that books which link to similar Wikipedia pages are similar to one another. We can represent this similarity and hence make recommendations by learning embeddings of books and Wikipedia links using a neural network. The end result is an effective recommendation system and a practical application of deep learning." }, { "code": null, "e": 1415, "s": 975, "text": "The complete code for this project is available as a Jupyter Notebook on GitHub. If you don’t have a GPU, you can also find the notebook on Kaggle where you can train your neural network with a GPU for free.This article will focus on the implementation, with the concepts of neural network embeddings covered in an earlier article. (To see how to retrieve the data we’ll use — all book articles on Wikipedia — take a look at this article.)" }, { "code": null, "e": 1542, "s": 1415, "text": "This project was adapted from the Deep Learning Cookbook, an excellent book with hands-on examples for applying deep learning." }, { "code": null, "e": 1836, "s": 1542, "text": "Embeddings are a way to represent discrete — categorical — variables as continuous vectors. In contrast to an encoding method like one-hot encoding, neural network embeddings are low-dimensional and learned, which means they place similar entities closer to one another in the embedding space." }, { "code": null, "e": 2055, "s": 1836, "text": "In order to create embeddings, we need a neural network embedding model and a supervised machine learning task. The end outcome of our network will be a representation of each book as a vector of 50 continuous numbers." }, { "code": null, "e": 2183, "s": 2055, "text": "While the embeddings themselves are not that interesting — they are just vectors — they can be used for three primary purposes:" }, { "code": null, "e": 2299, "s": 2183, "text": "Finding nearest neighbors in the embedding spaceAs input to a machine learning modelVisualization in low dimensions" }, { "code": null, "e": 2348, "s": 2299, "text": "Finding nearest neighbors in the embedding space" }, { "code": null, "e": 2385, "s": 2348, "text": "As input to a machine learning model" }, { "code": null, "e": 2417, "s": 2385, "text": "Visualization in low dimensions" }, { "code": null, "e": 2685, "s": 2417, "text": "This project covers primarily the first use case, but we’ll also see how to create visualizations from the embeddings. Practical applications of neural network embeddings include word embeddings for machine translation and entity embeddings for categorical variables." }, { "code": null, "e": 3135, "s": 2685, "text": "As usual with a data science project, we need to start with a high-quality dataset. In this article, we saw how to download and process every single article on Wikipedia, searching for any pages about books. We saved the book title, basic information, links on the book’s page that point to other Wikipedia pages (wikilinks), and links to external sites. To create the recommendation system, the only information we need are the title and wikilinks." }, { "code": null, "e": 3383, "s": 3135, "text": "Book Title: 'The Better Angels of Our Nature'Wikilinks: ['Steven Pinker', 'Nation state', 'commerce', 'literacy', 'Influence of mass media', 'Rationality', \"Abraham Lincoln's first inaugural address\", 'nature versus nurture', 'Leviathan']" }, { "code": null, "e": 3581, "s": 3383, "text": "Even when working with a neural network, it’s important to explore and clean the data, and in the notebook I make several corrections to the raw data. For example, looking at the most linked pages:" }, { "code": null, "e": 3944, "s": 3581, "text": "We see that the top four pages are generic and won’t help in making recommendations. The format of a book tells us nothing about the content: knowing a book is paperback or hardcover does not allow us — or a neural network —to figure out the other books it is similar to. Therefore, we can remove these links to help the neural network distinguish between books." }, { "code": null, "e": 4077, "s": 3944, "text": "Thinking about the end purpose can help in the data cleaning stage and this action alone significantly improves the recommendations." }, { "code": null, "e": 4222, "s": 4077, "text": "Out of pure curiosity, I wanted to find the books most linked to by other books on Wikipedia. These are the 10 “most connected” Wikipedia books:" }, { "code": null, "e": 4292, "s": 4222, "text": "This is a mix of reference works and classic books which makes sense." }, { "code": null, "e": 4426, "s": 4292, "text": "After data cleaning, we have a set of 41758 unique wikilinks and 37020 unique books. Hopefully there is a book in there for everyone!" }, { "code": null, "e": 4552, "s": 4426, "text": "Once we’re confident our data is clean, we need to develop a supervised machine learning task with labeled training examples." }, { "code": null, "e": 4891, "s": 4552, "text": "To learn meaningful embeddings, our neural network must be trained to accomplish an objective. Working from the guiding assumption of the project — that similar books link to similar Wikipedia pages — we can formulate the problem as follows: given a (book title, wikilink) pair, determine if the wikilink is present in the book’s article." }, { "code": null, "e": 5253, "s": 4891, "text": "We won’t actually need to give the network the book article. Instead, we’ll feed in hundreds of thousands of training examples consisting of book title, wikilink, and label. We give the network some true examples — actually present in the dataset — and some false examples, and eventually it learns embeddings to distinguish when a wikilink is on a book’s page." }, { "code": null, "e": 5784, "s": 5253, "text": "Expressing the supervised learning task is the most important part of this project. Embeddings are learned for a specific task and are relevant only to that problem. If our task was to determine which books were written by Jane Austen, then the embeddings would reflect that goal, placing books written by Austen closer together in embedding space. We hope that by training to tell if a book has a certain wikilink on its page, the network learns embeddings that places similar books — in terms of content — closer to one another." }, { "code": null, "e": 5988, "s": 5784, "text": "Once we’ve outlined the learning task, we need to implement it in code. To get started, because the neural network can only accept integer inputs, we create a mapping from each unique book to an integer:" }, { "code": null, "e": 6128, "s": 5988, "text": "# Mapping of books to index and index to booksbook_index = {book[0]: idx for idx, book in enumerate(books)}book_index['Anna Karenina']22494" }, { "code": null, "e": 6364, "s": 6128, "text": "We also do the same thing with the links. After this, to create a training set, we make a list of all (book, wikilink) pairs in the data. This requires iterating through each book and recording an example for each wikilink on its page:" }, { "code": null, "e": 6691, "s": 6364, "text": "pairs = []# Iterate through each bookfor book in books: title = book[0] book_links = book[2] # Iterate through wikilinks in book article for link in book_links: # Add index of book and index of link to pairs pairs.extend((book_index[title], link_index[link]))" }, { "code": null, "e": 6960, "s": 6691, "text": "This gives us a total of 772798 true examples that we can sample from to train the model. To generate the false examples — done later — we’ll simply pick a link index and book index at random, make sure it’s not in the pairs, and then use it as a negative observation." }, { "code": null, "e": 6995, "s": 6960, "text": "Note about Training / Testing Sets" }, { "code": null, "e": 7532, "s": 6995, "text": "While using a separate validation and testing set is a must for a normal supervised machine learning task, in this case, our primary objective is not to make the most accurate model, but to generate embeddings. The prediction task is just the means by which we train our network for those embeddings. At the end of training, we are not going to be testing our model on new data, so we don’t need to evaluate the performance or use a validation set to prevent overfitting. To get the best embeddings, we’ll use all examples for training." }, { "code": null, "e": 7819, "s": 7532, "text": "Although neural network embeddings sound technically complex, they are relatively easy to implement with the Keras deep learning framework. (I recommend starting with Keras if you are new to deep learning. TensorFlow may give you more control, but Keras cannot be beat for development)." }, { "code": null, "e": 7853, "s": 7819, "text": "The embedding model has 5 layers:" }, { "code": null, "e": 8114, "s": 7853, "text": "Input: parallel inputs for the book and linkEmbedding: parallel length 50 embeddings for the book and linkDot: merges embeddings by computing dot productReshape: needed to shape the dot product to a single numberDense: one output neuron with sigmoid activation" }, { "code": null, "e": 8159, "s": 8114, "text": "Input: parallel inputs for the book and link" }, { "code": null, "e": 8222, "s": 8159, "text": "Embedding: parallel length 50 embeddings for the book and link" }, { "code": null, "e": 8270, "s": 8222, "text": "Dot: merges embeddings by computing dot product" }, { "code": null, "e": 8330, "s": 8270, "text": "Reshape: needed to shape the dot product to a single number" }, { "code": null, "e": 8379, "s": 8330, "text": "Dense: one output neuron with sigmoid activation" }, { "code": null, "e": 8903, "s": 8379, "text": "In an embedding neural network, the embeddings are the parameters — weights — of the neural network that are adjusted during training in order to minimize loss on the objective. The neural network takes in a book and a link as integers and outputs a prediction between 0 and 1 that is compared to the true value. The model is compiled with the Adam optimizer (a variant on Stochastic Gradient Descent) which, during training, alters the embeddings to minimize the binary_crossentropy for this binary classification problem." }, { "code": null, "e": 8945, "s": 8903, "text": "Below is the code for the complete model:" }, { "code": null, "e": 9215, "s": 8945, "text": "This same framework can be used for many embedding models. The important point to understand is that the embeddings are the model parameters (weights) and also the final result we want. We don’t really care if the model is accurate, what we want is relevant embeddings." }, { "code": null, "e": 9408, "s": 9215, "text": "We’re used to the weights in a model being a means to make accurate predictions, but in an embedding model, the weights are the objective and the predictions are a means to learn an embedding." }, { "code": null, "e": 9474, "s": 9408, "text": "There are almost 4 million weights as shown by the model summary:" }, { "code": null, "e": 9630, "s": 9474, "text": "With this approach, we’ll get embeddings not only for books, but also for links which means we can compare all Wikipedia pages that are linked to by books." }, { "code": null, "e": 10094, "s": 9630, "text": "Neural networks are batch learners because they are trained on a small set of samples — observations — at a time over many rounds called epochs. A common approach for training neural networks is to use a generator. This is a function that yields (not returns) batches of samples so the entire result is not held in memory. Although it’s not an issue in this problem, the benefit of a generator is that large training sets do not need to all be loaded into memory." }, { "code": null, "e": 10557, "s": 10094, "text": "Our generator takes in the training pairs, the number of positive samples per batch ( n_positive ) , and the ratio of negative:positive samples per batch ( negative_ratio ). The generator yields a new batch of positive and negative samples each time it is called. To get positive examples, we randomly sample true pairs. For the negative examples, we randomly sample a book and link, make sure this pairing is not in the true pairs, and then add it to the batch." }, { "code": null, "e": 10609, "s": 10557, "text": "The code below shows the generator in its entirety." }, { "code": null, "e": 10679, "s": 10609, "text": "Each time we call next on the generator, we get a new training batch." }, { "code": null, "e": 10917, "s": 10679, "text": "next(generate_batch(pairs, n_positive = 2, negative_ratio = 2))({'book': array([ 6895., 29814., 22162., 7206., 25757., 28410.]), 'link': array([ 260., 11452., 5588., 34924., 22920., 33217.])}, array([ 1., -1., 1., -1., -1., -1.]))" }, { "code": null, "e": 11025, "s": 10917, "text": "With a supervised task, a training generator, and an embedding model, we’re ready to learn book embeddings." }, { "code": null, "e": 11543, "s": 11025, "text": "There are a few training parameters to select. The first is the number of positive examples in each batch. Generally, I try to start with a small batch size and increase it until performance starts to decline. Also, we need to choose the number of negative examples trained for each positive example. I’d recommend experimenting with a few options to see what works best. Since we’re not using a validation set to implement early stopping, I choose a number of epochs beyond which the training loss does not decrease." }, { "code": null, "e": 11736, "s": 11543, "text": "n_positive = 1024gen = generate_batch(pairs, n_positive, negative_ratio = 2)# Trainh = model.fit_generator(gen, epochs = 15, steps_per_epoch = len(pairs) // n_positive)" }, { "code": null, "e": 11944, "s": 11736, "text": "(If the training parameters seem arbitrary, in a sense they are, but based on best practices outlined in Deep Learning. Like most aspects of machine learning, training a neural network is largely empirical.)" }, { "code": null, "e": 12010, "s": 11944, "text": "Once the network is done training, we can extract the embeddings." }, { "code": null, "e": 12119, "s": 12010, "text": "# Extract embeddingsbook_layer = model.get_layer('book_embedding')book_weights = book_layer.get_weights()[0]" }, { "code": null, "e": 12232, "s": 12119, "text": "The embeddings themselves are fairly uninteresting: they are just 50-number vectors for each book and each link:" }, { "code": null, "e": 12681, "s": 12232, "text": "However, we can use these vectors for two different purposes, the first of which is to make our book recommendation system. To find the closest book to a query book in the embedding space, we take the vector for that book and find its dot product with the vectors for all other books. If our embeddings are normalized, then the dot product between the vectors represents the cosine similarity, ranging from -1, most dissimilar, to +1, most similar." }, { "code": null, "e": 12758, "s": 12681, "text": "Querying the embeddings for the classic War and Peace by Leo Tolstoy yields:" }, { "code": null, "e": 13038, "s": 12758, "text": "Books closest to War and Peace.Book: Anna Karenina Similarity: 0.92Book: The Master and Margarita Similarity: 0.92Book: Demons (Dostoevsky novel) Similarity: 0.91Book: The Idiot Similarity: 0.9Book: Crime and Punishment Similarity: 0.9" }, { "code": null, "e": 13296, "s": 13038, "text": "The recommendations make sense! These are all classic Russian novels. Sure we could have gone to GoodReads for these same recommendations, but why not build the system ourselves? I encourage you to work with the notebook and explore the embeddings yourself." }, { "code": null, "e": 13546, "s": 13296, "text": "Books closest to The Fellowship of the Ring.Book: The Return of the King Similarity: 0.96Book: The Silmarillion Similarity: 0.93Book: Beren and Lúthien Similarity: 0.91Book: The Two Towers Similarity: 0.91" }, { "code": null, "e": 13683, "s": 13546, "text": "In addition to embedding the books, we also embedded the links which means we can find the most similar links to a given Wikipedia page:" }, { "code": null, "e": 13907, "s": 13683, "text": "Pages closest to steven pinker.Page: the blank slate Similarity: 0.83Page: evolutionary psychology Similarity: 0.83Page: reductionism Similarity: 0.81Page: how the mind works Similarity: 0.79" }, { "code": null, "e": 14040, "s": 13907, "text": "Currently, I’m reading a fantastic collection of essays by Stephen Jay Gould called Bully for Brontosaurus. What should I read next?" }, { "code": null, "e": 14399, "s": 14040, "text": "One of the most intriguing aspects of embeddings are that they can be used to visualize concepts such as novel or nonfiction relative to one another. This requires a further dimension reduction technique to get the dimensions to 2 or 3. The most popular technique for reduction is another embedding method: t-Distributed Stochastic Neighbor Embedding (TSNE)." }, { "code": null, "e": 14592, "s": 14399, "text": "Starting with the 37,000-dimensional space of all books on Wikipedia, we map it to 50 dimensions using embeddings, and then to just 2 dimensions with TSNE. This results in the following image:" }, { "code": null, "e": 14727, "s": 14592, "text": "By itself this image is not that illuminating, but once we start coloring it by book characteristics, we start to see clusters emerge:" }, { "code": null, "e": 14959, "s": 14727, "text": "There are some definite clumps (only the top 10 genres are highlighted) with non-fiction and science fiction having distinct sections. The novels seem to be all over the place which makes sense given the diversity in novel content." }, { "code": null, "e": 15003, "s": 14959, "text": "We can also do embeddings with the country:" }, { "code": null, "e": 15111, "s": 15003, "text": "I was a little surprised at how distinctive the countries are! Evidently Australian books are quite unique." }, { "code": null, "e": 15177, "s": 15111, "text": "Furthermore, we can highlight certain books in the Wikipedia map:" }, { "code": null, "e": 15320, "s": 15177, "text": "There are a lot more visualizations in the notebook and you make your own. I’ll leave you with one more showing the 10 “most connected” books:" }, { "code": null, "e": 15667, "s": 15320, "text": "One thing to note about TSNE is that it tries to preserve distances between vectors in the original space, but because it reduces the number of dimensions, it may distort the original separation. Therefore, books that are close to one another in the 50-dimensional embedding space may not be closest neighbors in the 2-dimensional TSNE embedding." }, { "code": null, "e": 15951, "s": 15667, "text": "These visualizations are pretty interesting, but we can make stunning interactive figures with TensorFlow’s projector tool specifically designed for visualizing neural network embeddings. I plan on writing an article on how to use this tool, but for now here are some of the results:" }, { "code": null, "e": 16010, "s": 15951, "text": "To explore a sample of the books interactively, head here." }, { "code": null, "e": 16316, "s": 16010, "text": "Data science projects aren’t usually invented entirely on their own. A lot of the projects I work on are ideas from other data scientists that I adapt, improve, and build on to make a unique project. (This project was inspired by a similar project for movie recommendations in the Deep Learning Cookbook.)" }, { "code": null, "e": 16387, "s": 16316, "text": "With that attitude in mind, here are a few ways to build on this work:" }, { "code": null, "e": 16887, "s": 16387, "text": "Create embeddings using the external links instead of wikilinks. These are to web pages outside Wikipedia and might produce different embeddings.Use the embeddings to train a supervised machine learning model to predict the book characteristics which include genre, author, and country.Pick a topic category on Wikipedia and create your own recommendation system. You could use people, landmarks, or even historical events. You can use this notebook to get the data and this notebook for embeddings." }, { "code": null, "e": 17033, "s": 16887, "text": "Create embeddings using the external links instead of wikilinks. These are to web pages outside Wikipedia and might produce different embeddings." }, { "code": null, "e": 17175, "s": 17033, "text": "Use the embeddings to train a supervised machine learning model to predict the book characteristics which include genre, author, and country." }, { "code": null, "e": 17389, "s": 17175, "text": "Pick a topic category on Wikipedia and create your own recommendation system. You could use people, landmarks, or even historical events. You can use this notebook to get the data and this notebook for embeddings." }, { "code": null, "e": 17574, "s": 17389, "text": "This is by no means a homework assignment, just some project ideas if you want to put what you’ve read into practice. If you do decide to take on a project, I’d enjoy hearing about it!" }, { "code": null, "e": 18032, "s": 17574, "text": "Neural network embeddings are a method to represent discrete categorical variables as continuous vectors. As a learned low-dimensional representation, they are useful for finding similar categories, as input into a machine learning model, or to visualize maps of concepts. In this project, we used neural network embeddings to create an effective book recommendation system built on the idea that books which link to similar pages are similar to each other." }, { "code": null, "e": 18086, "s": 18032, "text": "The steps for creating neural network embeddings are:" }, { "code": null, "e": 18339, "s": 18086, "text": "Gather data. Neural networks require many training examples.Formulate a supervised task to learn embeddings that reflect the problem.Build and train an embedding neural network model.Extract the embeddings for making recommendations and visualizations." }, { "code": null, "e": 18400, "s": 18339, "text": "Gather data. Neural networks require many training examples." }, { "code": null, "e": 18474, "s": 18400, "text": "Formulate a supervised task to learn embeddings that reflect the problem." }, { "code": null, "e": 18525, "s": 18474, "text": "Build and train an embedding neural network model." }, { "code": null, "e": 18595, "s": 18525, "text": "Extract the embeddings for making recommendations and visualizations." }, { "code": null, "e": 19104, "s": 18595, "text": "The details can be found in the notebook and I’d encourage anyone to build on this project. While deep learning may seem overwhelming because of technical complexity or computational resources, this is one of many applications that can be done on a personal computer with a limited amount of studying. Deep learning is a constantly evolving field, and this project is a good way to get started by building a useful system. And, when you’re not studying deep learning, now you know what you should be reading!" } ]
Saving all the open Matplotlib figures in one file at once
To save all the open Matplotlib figures in one file at once, we can take follwong steps − Set the figure size and adjust the padding between and around the subplots. Create a new figure (fig1) or activate an existing figure using figure() method. Plot the first line using plot() method. Create a new figure (fig2) or activate an existing figure using figure() method. Plot the Second line using plot() method. Initialize a variable, filename, to make a pdf file. Create a user-defind function, save_multi_image, and call it to save all the open matplotlib figures in one file at once. Create a new PdfPages object, pp. Get the number of open figures. Iterate the opened figures and save them into a file. To display the figure, use show() method. from matplotlib import pyplot as plt from matplotlib.backends.backend_pdf import PdfPages plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True fig1 = plt.figure() plt.plot([2, 1, 7, 1, 2], color='red', lw=5) fig2 = plt.figure() plt.plot([3, 5, 1, 5, 3], color='green', lw=5) def save_multi_image(filename): pp = PdfPages(filename) fig_nums = plt.get_fignums() figs = [plt.figure(n) for n in fig_nums] for fig in figs: fig.savefig(pp, format='pdf') pp.close() filename = "multi.pdf" save_multi_image(filename) When we execute the code, it will save the following two plots as a PDF file (multi.pdf) in the project directory.
[ { "code": null, "e": 1152, "s": 1062, "text": "To save all the open Matplotlib figures in one file at once, we can take follwong steps −" }, { "code": null, "e": 1228, "s": 1152, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1309, "s": 1228, "text": "Create a new figure (fig1) or activate an existing figure using figure() method." }, { "code": null, "e": 1350, "s": 1309, "text": "Plot the first line using plot() method." }, { "code": null, "e": 1431, "s": 1350, "text": "Create a new figure (fig2) or activate an existing figure using figure() method." }, { "code": null, "e": 1473, "s": 1431, "text": "Plot the Second line using plot() method." }, { "code": null, "e": 1526, "s": 1473, "text": "Initialize a variable, filename, to make a pdf file." }, { "code": null, "e": 1682, "s": 1526, "text": "Create a user-defind function, save_multi_image, and call it to save all the open matplotlib figures in one file at once. Create a new PdfPages object, pp." }, { "code": null, "e": 1714, "s": 1682, "text": "Get the number of open figures." }, { "code": null, "e": 1768, "s": 1714, "text": "Iterate the opened figures and save them into a file." }, { "code": null, "e": 1810, "s": 1768, "text": "To display the figure, use show() method." }, { "code": null, "e": 2379, "s": 1810, "text": "from matplotlib import pyplot as plt\nfrom matplotlib.backends.backend_pdf import PdfPages\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nfig1 = plt.figure()\nplt.plot([2, 1, 7, 1, 2], color='red', lw=5)\n\nfig2 = plt.figure()\nplt.plot([3, 5, 1, 5, 3], color='green', lw=5)\n\ndef save_multi_image(filename):\n pp = PdfPages(filename)\n fig_nums = plt.get_fignums()\n figs = [plt.figure(n) for n in fig_nums]\n for fig in figs:\n fig.savefig(pp, format='pdf')\n pp.close()\n\nfilename = \"multi.pdf\"\nsave_multi_image(filename)" }, { "code": null, "e": 2494, "s": 2379, "text": "When we execute the code, it will save the following two plots as a PDF file (multi.pdf) in the project directory." } ]
Fast Feature Engineering in Python: Image Data | by Sayar Banerjee | Towards Data Science
“Finding patterns is easy in any kind of data-rich environment; that’s what mediocre gamblers do. The key is in determining whether the patterns represent noise or signal.”― Nate Silver This article is part 2 of my “Fast Feature Engineering” series. If you have not read my first article which talks about tabular data, then I request you to check it out here: towardsdatascience.com This article will look at some of the best practices to follow when performing image processing as part of our machine learning workflow. import randomfrom PIL import Imageimport cv2import numpy as npfrom matplotlib import pyplot as pltimport jsonimport albumentations as Aimport torchimport torchvision.models as modelsimport torchvision.transforms as transformsimport torch.nn as nnfrom tqdm import tqdm_notebookfrom torch.utils.data import DataLoaderfrom torchvision.datasets import CIFAR10 Resizing is the most fundamental transformation done by deep learning practitioners in the field. The primary reason for doing this is to ensure that the input received by our deep learning system is consistent. Another reason for resizing is to reduce the number of parameters in the model. Smaller dimensions signify a smaller neural network and hence, saves us the time and computation power required to train our model. Some information is indeed lost when you resize down from a larger image. However, depending on your task, you can choose how much information you’re willing to sacrifice for training time and compute resources. For example, an object detection task will require you to maintain the image's aspect ratio since the goal is to detect the exact position of objects. In contrast, an image classification task may require you to resize all images down to a specified size (224 x 224 is a good rule of thumb). After resizing our image looks like this: Similar to tabular data, scaling images for classification tasks can help our deep learning model's learning rate to converge to the minima better. Scaling ensures that a particular dimension does not dominate others. I found a fantastic answer on StackExchange regarding this. You can read it here. One type of feature scaling is the process of standardizing our pixel values. We do this by subtracting the mean of each channel from its pixel value and then divide it via standard deviation. This is a popular choice of feature engineering when training models for classification tasks. Note: Like resizing, one may not want to do image scaling when performing object detection and image generation tasks. The example code above demonstrates the process of scaling an image via standardization. There are other forms of scaling such as centering and normalization. The primary motivation behind augmenting images is due to the appreciable data requirement for computer vision tasks. Often, obtaining enough images for training can prove to be challenging for a multitude of reasons. Image augmentation enables us to create new training samples by slightly modifying the original ones. In this example, we will look at how to apply vanilla augmentations for a classification task. We can use the out of the box implementations of the Albumentations library to do this: By applying image augmentations, our deep learning models can generalize better to the task (avoid overfitting), thereby increasing its predictive power on unseen data. The Albumentations library can also be used to create augmentations for other tasks such as object detections. Object detection requires us to create bounding boxes around the object of interest. Working with raw data can prove to be challenging when trying to annotate images with the coordinates for the bounding boxes. Fortunately, there are many publicly and freely available datasets that we can use to create an augmentation pipeline for object detection. One such dataset is the Chess Dataset. The dataset contains 606 images of chess pieces on a chessboard. Along with the images, a JSON file is provided that contains all the information pertaining to the bounding boxes for each chess piece in a single image. By writing a simple function, we can visualize the data after the augmentation is applied: Now, let’s try to create an augmentation pipeline using Albumentations. The JSON file that contains the annotation information has the following keys: dict_keys([‘info’, ‘licenses’, ‘categories’, ‘images’, ‘annotations’]) images contains information about the image file whereas annotations contains information about the bounding boxes for each object in an image. Finally, categories contains keys that map to the type of chess pieces in the image. image_list = json_file.get('images')anno_list = json_file.get('annotations')cat_list = json_file.get('categories') image_list : [{'id': 0, 'license': 1, 'file_name': 'IMG_0317_JPG.rf.00207d2fe8c0a0f20715333d49d22b4f.jpg', 'height': 416, 'width': 416, 'date_captured': '2021-02-23T17:32:58+00:00'}, {'id': 1, 'license': 1, 'file_name': '5a8433ec79c881f84ef19a07dc73665d_jpg.rf.00544a8110f323e0d7721b3acf2a9e1e.jpg', 'height': 416, 'width': 416, 'date_captured': '2021-02-23T17:32:58+00:00'}, {'id': 2, 'license': 1, 'file_name': '675619f2c8078824cfd182cec2eeba95_jpg.rf.0130e3c26b1bf275bf240894ba73ed7c.jpg', 'height': 416, 'width': 416, 'date_captured': '2021-02-23T17:32:58+00:00'},.... anno_list : [{'id': 0, 'image_id': 0, 'category_id': 7, 'bbox': [220, 14, 18, 46.023746508293286], 'area': 828.4274371492792, 'segmentation': [], 'iscrowd': 0}, {'id': 1, 'image_id': 1, 'category_id': 8, 'bbox': [187, 103, 22.686527154676014, 59.127992255841036], 'area': 1341.4088019136107, 'segmentation': [], 'iscrowd': 0}, {'id': 2, 'image_id': 2, 'category_id': 10, 'bbox': [203, 24, 24.26037020843023, 60.5], 'area': 1467.752397610029, 'segmentation': [], 'iscrowd': 0},.... cat_list : [{'id': 0, 'name': 'pieces', 'supercategory': 'none'}, {'id': 1, 'name': 'bishop', 'supercategory': 'pieces'}, {'id': 2, 'name': 'black-bishop', 'supercategory': 'pieces'}, {'id': 3, 'name': 'black-king', 'supercategory': 'pieces'}, {'id': 4, 'name': 'black-knight', 'supercategory': 'pieces'}, {'id': 5, 'name': 'black-pawn', 'supercategory': 'pieces'}, {'id': 6, 'name': 'black-queen', 'supercategory': 'pieces'}, {'id': 7, 'name': 'black-rook', 'supercategory': 'pieces'}, {'id': 8, 'name': 'white-bishop', 'supercategory': 'pieces'}, {'id': 9, 'name': 'white-king', 'supercategory': 'pieces'}, {'id': 10, 'name': 'white-knight', 'supercategory': 'pieces'}, {'id': 11, 'name': 'white-pawn', 'supercategory': 'pieces'}, {'id': 12, 'name': 'white-queen', 'supercategory': 'pieces'}, {'id': 13, 'name': 'white-rook', 'supercategory': 'pieces'}] We have to alter the structure of these lists to create an efficient pipeline: Now, let’s create a simple augmentation pipeline that flips our image horizontally and adds a parameter for bounding boxes: Lastly, we will create a dataset similar to the Dataset class offered by Pytorch. To do this, we need to define a class that implements the methods __len__ and __getitem__. Here are some of the results while iterating on the custom dataset: Thus, we can now easily pass this custom dataset to a data loader to train our model. You may have heard of pre-trained models being used to train image classifiers and for other supervised learning tasks. But, did you know that you can also use pre-trained models for feature extraction of images? In short feature extraction is a form of dimensionality reduction where a large number of pixels are reduced to a more efficient representation. This is primarily useful for unsupervised machine learning tasks such as reverse image search. Let’s try to extract features from images using Pytorch’s pre-trained models. To do this, we must first define our feature extractor class: Note that in line 4, a new model is created with all of the layers of the original save for the last one. You will recall that the last layer in a neural network is a dense layer used for prediction outputs. However, since we are only interested in extracting features, we do not require this last layer. Hence, it is excluded. We then utilize torchvision’s pre-trained resnet34 model by passing it to the ResnetFeatureExtractor constructor. Let’s use the famous CIFAR10 dataset (50000 images), and loop over it to extract the features. We now have a list of 50000 image feature vectors with each feature vector of size 512 (output size of the penultimate layer of the original resnet model). print(f"Number of feature vectors: {len(feature_list)}") #50000print(f"Number of feature vectors: {len(feature_list[0])}") #512 Thus, this list of feature vectors can now be used by statistical learning models such as KNN to search for similar images. If you have reached this far then thank you very much for reading this article! I hope you have a fantastic day ahead! 😄 👉 Code used in the article Until next time! ✋
[ { "code": null, "e": 358, "s": 172, "text": "“Finding patterns is easy in any kind of data-rich environment; that’s what mediocre gamblers do. The key is in determining whether the patterns represent noise or signal.”― Nate Silver" }, { "code": null, "e": 533, "s": 358, "text": "This article is part 2 of my “Fast Feature Engineering” series. If you have not read my first article which talks about tabular data, then I request you to check it out here:" }, { "code": null, "e": 556, "s": 533, "text": "towardsdatascience.com" }, { "code": null, "e": 694, "s": 556, "text": "This article will look at some of the best practices to follow when performing image processing as part of our machine learning workflow." }, { "code": null, "e": 1050, "s": 694, "text": "import randomfrom PIL import Imageimport cv2import numpy as npfrom matplotlib import pyplot as pltimport jsonimport albumentations as Aimport torchimport torchvision.models as modelsimport torchvision.transforms as transformsimport torch.nn as nnfrom tqdm import tqdm_notebookfrom torch.utils.data import DataLoaderfrom torchvision.datasets import CIFAR10" }, { "code": null, "e": 1262, "s": 1050, "text": "Resizing is the most fundamental transformation done by deep learning practitioners in the field. The primary reason for doing this is to ensure that the input received by our deep learning system is consistent." }, { "code": null, "e": 1474, "s": 1262, "text": "Another reason for resizing is to reduce the number of parameters in the model. Smaller dimensions signify a smaller neural network and hence, saves us the time and computation power required to train our model." }, { "code": null, "e": 1686, "s": 1474, "text": "Some information is indeed lost when you resize down from a larger image. However, depending on your task, you can choose how much information you’re willing to sacrifice for training time and compute resources." }, { "code": null, "e": 1837, "s": 1686, "text": "For example, an object detection task will require you to maintain the image's aspect ratio since the goal is to detect the exact position of objects." }, { "code": null, "e": 1978, "s": 1837, "text": "In contrast, an image classification task may require you to resize all images down to a specified size (224 x 224 is a good rule of thumb)." }, { "code": null, "e": 2020, "s": 1978, "text": "After resizing our image looks like this:" }, { "code": null, "e": 2168, "s": 2020, "text": "Similar to tabular data, scaling images for classification tasks can help our deep learning model's learning rate to converge to the minima better." }, { "code": null, "e": 2320, "s": 2168, "text": "Scaling ensures that a particular dimension does not dominate others. I found a fantastic answer on StackExchange regarding this. You can read it here." }, { "code": null, "e": 2513, "s": 2320, "text": "One type of feature scaling is the process of standardizing our pixel values. We do this by subtracting the mean of each channel from its pixel value and then divide it via standard deviation." }, { "code": null, "e": 2608, "s": 2513, "text": "This is a popular choice of feature engineering when training models for classification tasks." }, { "code": null, "e": 2727, "s": 2608, "text": "Note: Like resizing, one may not want to do image scaling when performing object detection and image generation tasks." }, { "code": null, "e": 2886, "s": 2727, "text": "The example code above demonstrates the process of scaling an image via standardization. There are other forms of scaling such as centering and normalization." }, { "code": null, "e": 3104, "s": 2886, "text": "The primary motivation behind augmenting images is due to the appreciable data requirement for computer vision tasks. Often, obtaining enough images for training can prove to be challenging for a multitude of reasons." }, { "code": null, "e": 3206, "s": 3104, "text": "Image augmentation enables us to create new training samples by slightly modifying the original ones." }, { "code": null, "e": 3389, "s": 3206, "text": "In this example, we will look at how to apply vanilla augmentations for a classification task. We can use the out of the box implementations of the Albumentations library to do this:" }, { "code": null, "e": 3558, "s": 3389, "text": "By applying image augmentations, our deep learning models can generalize better to the task (avoid overfitting), thereby increasing its predictive power on unseen data." }, { "code": null, "e": 3754, "s": 3558, "text": "The Albumentations library can also be used to create augmentations for other tasks such as object detections. Object detection requires us to create bounding boxes around the object of interest." }, { "code": null, "e": 3880, "s": 3754, "text": "Working with raw data can prove to be challenging when trying to annotate images with the coordinates for the bounding boxes." }, { "code": null, "e": 4059, "s": 3880, "text": "Fortunately, there are many publicly and freely available datasets that we can use to create an augmentation pipeline for object detection. One such dataset is the Chess Dataset." }, { "code": null, "e": 4124, "s": 4059, "text": "The dataset contains 606 images of chess pieces on a chessboard." }, { "code": null, "e": 4278, "s": 4124, "text": "Along with the images, a JSON file is provided that contains all the information pertaining to the bounding boxes for each chess piece in a single image." }, { "code": null, "e": 4369, "s": 4278, "text": "By writing a simple function, we can visualize the data after the augmentation is applied:" }, { "code": null, "e": 4441, "s": 4369, "text": "Now, let’s try to create an augmentation pipeline using Albumentations." }, { "code": null, "e": 4520, "s": 4441, "text": "The JSON file that contains the annotation information has the following keys:" }, { "code": null, "e": 4591, "s": 4520, "text": "dict_keys([‘info’, ‘licenses’, ‘categories’, ‘images’, ‘annotations’])" }, { "code": null, "e": 4735, "s": 4591, "text": "images contains information about the image file whereas annotations contains information about the bounding boxes for each object in an image." }, { "code": null, "e": 4820, "s": 4735, "text": "Finally, categories contains keys that map to the type of chess pieces in the image." }, { "code": null, "e": 4935, "s": 4820, "text": "image_list = json_file.get('images')anno_list = json_file.get('annotations')cat_list = json_file.get('categories')" }, { "code": null, "e": 4948, "s": 4935, "text": "image_list :" }, { "code": null, "e": 5523, "s": 4948, "text": "[{'id': 0, 'license': 1, 'file_name': 'IMG_0317_JPG.rf.00207d2fe8c0a0f20715333d49d22b4f.jpg', 'height': 416, 'width': 416, 'date_captured': '2021-02-23T17:32:58+00:00'}, {'id': 1, 'license': 1, 'file_name': '5a8433ec79c881f84ef19a07dc73665d_jpg.rf.00544a8110f323e0d7721b3acf2a9e1e.jpg', 'height': 416, 'width': 416, 'date_captured': '2021-02-23T17:32:58+00:00'}, {'id': 2, 'license': 1, 'file_name': '675619f2c8078824cfd182cec2eeba95_jpg.rf.0130e3c26b1bf275bf240894ba73ed7c.jpg', 'height': 416, 'width': 416, 'date_captured': '2021-02-23T17:32:58+00:00'},...." }, { "code": null, "e": 5535, "s": 5523, "text": "anno_list :" }, { "code": null, "e": 6022, "s": 5535, "text": "[{'id': 0, 'image_id': 0, 'category_id': 7, 'bbox': [220, 14, 18, 46.023746508293286], 'area': 828.4274371492792, 'segmentation': [], 'iscrowd': 0}, {'id': 1, 'image_id': 1, 'category_id': 8, 'bbox': [187, 103, 22.686527154676014, 59.127992255841036], 'area': 1341.4088019136107, 'segmentation': [], 'iscrowd': 0}, {'id': 2, 'image_id': 2, 'category_id': 10, 'bbox': [203, 24, 24.26037020843023, 60.5], 'area': 1467.752397610029, 'segmentation': [], 'iscrowd': 0},...." }, { "code": null, "e": 6033, "s": 6022, "text": "cat_list :" }, { "code": null, "e": 6878, "s": 6033, "text": "[{'id': 0, 'name': 'pieces', 'supercategory': 'none'}, {'id': 1, 'name': 'bishop', 'supercategory': 'pieces'}, {'id': 2, 'name': 'black-bishop', 'supercategory': 'pieces'}, {'id': 3, 'name': 'black-king', 'supercategory': 'pieces'}, {'id': 4, 'name': 'black-knight', 'supercategory': 'pieces'}, {'id': 5, 'name': 'black-pawn', 'supercategory': 'pieces'}, {'id': 6, 'name': 'black-queen', 'supercategory': 'pieces'}, {'id': 7, 'name': 'black-rook', 'supercategory': 'pieces'}, {'id': 8, 'name': 'white-bishop', 'supercategory': 'pieces'}, {'id': 9, 'name': 'white-king', 'supercategory': 'pieces'}, {'id': 10, 'name': 'white-knight', 'supercategory': 'pieces'}, {'id': 11, 'name': 'white-pawn', 'supercategory': 'pieces'}, {'id': 12, 'name': 'white-queen', 'supercategory': 'pieces'}, {'id': 13, 'name': 'white-rook', 'supercategory': 'pieces'}]" }, { "code": null, "e": 6957, "s": 6878, "text": "We have to alter the structure of these lists to create an efficient pipeline:" }, { "code": null, "e": 7081, "s": 6957, "text": "Now, let’s create a simple augmentation pipeline that flips our image horizontally and adds a parameter for bounding boxes:" }, { "code": null, "e": 7254, "s": 7081, "text": "Lastly, we will create a dataset similar to the Dataset class offered by Pytorch. To do this, we need to define a class that implements the methods __len__ and __getitem__." }, { "code": null, "e": 7322, "s": 7254, "text": "Here are some of the results while iterating on the custom dataset:" }, { "code": null, "e": 7408, "s": 7322, "text": "Thus, we can now easily pass this custom dataset to a data loader to train our model." }, { "code": null, "e": 7528, "s": 7408, "text": "You may have heard of pre-trained models being used to train image classifiers and for other supervised learning tasks." }, { "code": null, "e": 7621, "s": 7528, "text": "But, did you know that you can also use pre-trained models for feature extraction of images?" }, { "code": null, "e": 7766, "s": 7621, "text": "In short feature extraction is a form of dimensionality reduction where a large number of pixels are reduced to a more efficient representation." }, { "code": null, "e": 7861, "s": 7766, "text": "This is primarily useful for unsupervised machine learning tasks such as reverse image search." }, { "code": null, "e": 8001, "s": 7861, "text": "Let’s try to extract features from images using Pytorch’s pre-trained models. To do this, we must first define our feature extractor class:" }, { "code": null, "e": 8209, "s": 8001, "text": "Note that in line 4, a new model is created with all of the layers of the original save for the last one. You will recall that the last layer in a neural network is a dense layer used for prediction outputs." }, { "code": null, "e": 8329, "s": 8209, "text": "However, since we are only interested in extracting features, we do not require this last layer. Hence, it is excluded." }, { "code": null, "e": 8443, "s": 8329, "text": "We then utilize torchvision’s pre-trained resnet34 model by passing it to the ResnetFeatureExtractor constructor." }, { "code": null, "e": 8538, "s": 8443, "text": "Let’s use the famous CIFAR10 dataset (50000 images), and loop over it to extract the features." }, { "code": null, "e": 8694, "s": 8538, "text": "We now have a list of 50000 image feature vectors with each feature vector of size 512 (output size of the penultimate layer of the original resnet model)." }, { "code": null, "e": 8822, "s": 8694, "text": "print(f\"Number of feature vectors: {len(feature_list)}\") #50000print(f\"Number of feature vectors: {len(feature_list[0])}\") #512" }, { "code": null, "e": 8946, "s": 8822, "text": "Thus, this list of feature vectors can now be used by statistical learning models such as KNN to search for similar images." }, { "code": null, "e": 9067, "s": 8946, "text": "If you have reached this far then thank you very much for reading this article! I hope you have a fantastic day ahead! 😄" }, { "code": null, "e": 9094, "s": 9067, "text": "👉 Code used in the article" } ]
Categorical Feature Encoding. A beginner’s guide to addressing... | by Joseph Cohen | Towards Data Science
IntroductionCategorical DataWhy Encode Categorical Data?Example DatasetOne-Hot EncodingLabel Encoding and Ordinal EncodingTarget EncodingModelsConclusionResources Introduction Categorical Data Why Encode Categorical Data? Example Dataset One-Hot Encoding Label Encoding and Ordinal Encoding Target Encoding Models Conclusion Resources Let’s get started. Categorical feature encoding is often a key part of the data science process and can be done in multiple ways leading to different results and a different understanding of input data. Today’s post will address this topic and run some models to point out the differences in my three favorite categorical feature encoding methods. Table of contents Naturally, the first topic to be addressed is the definition of what categorical data actually is and what other types of data one normally encounters looks like. Categorical data is non-numeric and often can be characterized into categories or groups. A simple example is is color; red, blue, and yellow are all distinct colors. Another example could be age groups or other interval-type data. Like 1–25 years old, 25–50 years old, and so on. The data used represents numbers, but the intervals themselves are categorical. Discrete data is similar, but is still numeric. An example of discrete data is the sum of two dice thrown. There are a finite and known set of outcomes, but these outcomes are represented numerically. Continuous data concerns data that can take on infinite values between any two points. A good example that really proves this point is that there are infinite values between 1 and 1.01. Continuous data is generally numeric, like in our example above, but can sometimes be represented in date-time format. Table of contents We encode categorical data numerically because math is generally done using numbers. A big part of natural language processing is converting text to numbers. Just like that, our algorithms cannot run and process data if that data is not numerical. Therefore, data scientists need to have tools at their disposal to transform colors like red, yellow, and blue into numbers like 1, 2, and 3 for all the backend math to take place. Now that we know what categorical data looks like and have seen some examples, we will examine three common methods to turn our categorical data into numeric data. Table of contents Before me move forward, we’ll need some data to work with to show what categorical feature encoding looks like in python and how different methods affect model efficiency. My data comes from kaggle.com, concerns diamond pricing, and can be found here. We will do some basic data preparation just to get a clean data set. Afterwards, using our three methods of categorical feature encoding, we will create three distinct data sets and see which one leads to the best models. The target feature is continuous, so will be predicted via regressor-like methods. Install libraries !pip install -U scikit-learn!pip install xgboost Imports import warningswarnings.filterwarnings('ignore')import pandas as pdimport numpy as npimport matplotlib.pyplot as plt%matplotlib inlineimport seaborn as snsfrom scipy import statsfrom sklearn.preprocessing import *from sklearn. metrics import *from sklearn.linear_model import LinearRegression, SGDRegressorfrom sklearn.ensemble import RandomForestRegressorfrom xgboost import XGBClassifier, XGBRegressorfrom sklearn.model_selection import train_test_splitfrom imblearn.datasets import make_imbalancefrom category_encoders.target_encoder import TargetEncoderimport statsmodels.api as sm Read data df = pd.read_csv('diamonds.csv')print(df.shape)df.head() Delete unnamed: 0 and add volume in place of x, y, and z df['volume']=df.x*df.y*df.zdf.drop(['Unnamed: 0','x','y','z'],axis=1,inplace=True) One-hot encoding is a method of identifying whether a unique categorical value from a categorical feature is present or not. What I mean by this is that if our feature is primary color (and each row has only one primary color), one-hot encoding would represent whether the color present in each row is red, blue, or yellow. This is accomplished by adding a new column for each possible color. With these three columns representing color in place for every row of the data, we go through each row and assign the value 1 to the column representing the color present in our current row and fill in the other color columns of that row with a 0 to represent their absence. Let’s look at how we can do this in python and the benefits and drawbacks to this method. There are a couple ways to accomplish this task in python, and I’ll focus on what I believe to be the two easiest methods. Building one_hot_encoder_one function The inputs are the data and feature you wish to encode The first part is instantiating a one-hot encoder from scikit-learn and more information on this function can be found at the documentation Next, I use this function to transform my data into new columns in a separate data frame with 1s and 0s I am also going to retain information about what features are represented in each column using the get_feature_name function that can be found at the documentation referenced above My next step is optional, but I am basically just adding a prefix referencing my variable which is being encoded and removing some of the text the one-hot encoder will by-default add Next, I add the new data frame back into the same data frame with the old data and delete the column that was just one-hot encoded I have one last optional step at the end which allows you to drop one column from the new one-hot encoded columns or to not drop one column (we would drop one column for the purposes of removing autocorrelation) The return value is the original data with new one-hot encoded columns Building one_hot_encoder_two function The inputs remain the same as above This function is very similar, except we leverage the pandas.get_dummies() function, whose documentation can be found here The get_dummies basically accomplishes the same task as the one-hot encoder, except we never lose the information regarding what feature is represented in each column and therefore we don’t need get_feature_names in the code The rest is the same; we combine the data and potentially remove one column for auto correlation These functions will work well, but are only meant for categorical data Let’s look at the output of each function We’ll start with the basic data one_hot_encoder_one one_hot_encoder_two We clearly see two paths to the same answer Let’s run a loop and save our data as df_one_hot for the models we will later run df_one_hot=df.copy()for col in df.select_dtypes(include='O').columns: df_one_hot=one_hot_encoder_one(df_one_hot,col) We see above that row two has a clarity rating of “SI1” (look at kaggle for more information on what this means) and that row one has a cut rating of “ideal.” One obvious benefit of one-hot encoding is that you notice if any particular unique values within a set of values have an outsized or strong impact in either a positive or negative direction. For example, I used one-hot encoding on a recent project I worked on to measure the likeliness of getting a deal on Shark Tank given the presence of each shark during a particular pitch. Unlike other types of encoding, with one-hot encoding you maintain information on the values of each variable. With label encoding, as we will see below, we get a good measure of the impact of a particular feature on models, but not the specific impacts of unique values of that feature. While it’s nice to know the impact, positive or negative, of each unique occurrence in categorical data, it could sometimes make models less accurate. More importantly though, if some unique values are far more common than others, we may erroneously assume that these values are very important when they actually are not. For example, let’s say that you work in a building with the same 1000 people coming in and out every day. One day, someone who has never been to the building walks in, we’ll call him Joseph (my name), and the power in the building goes out. It would be pretty silly to blame Joseph for the power outage, but our data does in fact indicate that 100% of the time Joseph is in the building, we witness a power outage. For this reason, I like using one-hot encoding for features when there aren’t an overwhelming amount of unique values and/or the distribution of unique values is relatively balanced. Similarly, the size of the data set should be large enough so the amount of unique values and their distributions won’t be problematic. One other problem is that since we delete our feature once encoding it, the feature itself’s effect may be somewhat lost as we shift our attention to the values of the feature and not the feature itself. Table of contents Label encoding is probably the most basic type of categorical feature encoding method after one-hot encoding. Label encoding doesn’t add any extra columns to the data but instead assigns a number to each unique value in a feature. Let’s use the colors example again. Instead of adding a column for red, another one for blue, and one more for yellow, we just assign each value a number. Red is 1, blue is 2, and yellow is 3. We saved a lot of room and don’t add more columns to our data, resulting in a much cleaner look for the data. The numbers assigned for red, blue, and yellow are arbitrary and their labels have no actual meaning, but they are simple to deal with. Ordinal encoding is a slightly-advanced form of label encoding; we assign labels based on an order or hierarchy. For colors, I am not an artist, so I see no reason to not assign numbers to color at random. However, if we are dealing with cuts of diamonds, as the data for this blog deals with, we may want to set up a system where the worse cuts are either assigned a higher or lower number. In the code below we will use both label and ordinal encoding. For label encoding, we have a very simple and easy python function whose documentation can be found here We will once again run a loop and save the data as label_encoded_df le = LabelEncoder()label_encoded_df = df.copy()for col in label_encoded_df.select_dtypes(include='O').columns: label_encoded_df[col]=le.fit_transform(label_encoded_df[col]) Now, for cut, clarity, and color, we have arbitrary numeric representations For ordinal encoding, python has a package whose documentation can be found here. I personally like to perform ordinal encoding using dictionary mapping though. Even if you were to use the python package there is still some manual work to be done, therefore I will present a function for ordinal encoding below Building ordinal_encoder function The inputs are the data, a feature to encode, and an ordered list of unique values from the feature (be consistent on whether you want the best value to be low or high) An empty dictionary is created and the subsequently filled with a number for each value (I write +1, to start our values at 1 and not 0) This structure is then mapped onto each occurrence of the feature in the data The return value is the old data frame with the new encoding in place Let’s quickly see one example of this strategy Original data New look at data We clearly see ideal is represented by 1 and lower grades have higher numbers An obvious benefit to label encoding is that it’s quick, easy, and doesn’t create a messy data frame in the way that one-hot encoding adds a lot of columns. Ordinal encoding, which I consider to be an extension of label encoding, imposes extra meaning to the labels assigned through label encoding. In label encoding, one major drawback is that our labels are rather arbitrary. Even in ordinal encoding, who’s to say that the step between rank 4 and 5 is the same as a step between 2 and 3? Maybe the difference between what we call 4 and 5 is marginal, while the difference between what we call 2 and 3 is huge. As mentioned above, one other drawback is that while we can find how strong or weak the impact of a particular feature is, we lose all information on unique values within that feature (this is moderately addressed with ordinal encoding, but the effect is marginal). Finally, this method may not work well with outliers as there is the possibility that certain labels may not appear in similar frequencies to the other labels. We see this same problem with target encoding. Table of contents Target encoding happens to be my favorite method of encoding as I find it most often produces the strongest models. Target encoding aligns unique categorical values with the target feature based on the average relationship. Say we are presented with a data set trying to predict a house’s price range based on color. Like above, our colors are red, yellow, and blue. Let’s also say our price ranges for houses are 1, 2, 3, and 4 and our features include basic housing things like square footage and other features (but also color). If we see that red houses tend to fall on average at a 3.35, it means red houses are slightly above a 3 but far below a 4. We then assign every occurrence of the value red to 3.35 as that is the mean target value. This is taking label and ordinal encoding to the next level. We introduce meaningful numbers to take the place of colors as opposed to arbitrary numbers. Also, if blue houses fall at 3.34, or even at 3.35 like red, we have no problem and can assign the number 3.34 or 3.35 to blue. This “double-labeling” (that’s what I have decided to call it) would be impossible with label or ordinal encoding. Target encoding, like other encoders has a python package. It’s a user-friendly package and I will show how to use it. I will also, however, add a more descriptive function to give you further insight into the backend of target encoding. First, the python package whose documentation can be found here. te_df=df.copy()for col in te_df.select_dtypes(include='O').columns: te=TargetEncoder() te_df[col]=te.fit_transform(te_df[col],te_df.price) Original data New data Now, for a more descriptive function Building target_encoding function Inputs are data, a feature, and the target feature A new data frame is created containing each unique value of a feature from the data which is then grouped by it’s mean target value An empty dictionary is then created, filled with this data, and mapped to each unique value of the particular feature The return value is the data frame with new target encodings in place Let’s see the same result with the new function te_df=df.copy()for col in te_df.select_dtypes(include='O').columns: target_encoding(te_df,col,'price') Original Data New Data Notice how color remains the same number through the first three rows per our expectations We’ll save this data as te_df Target encoding is the most meaningful way I can think of to attach numbers to categorical values. It’s a simple concept and is easy and expedient to apply. I also find that it usually generates the best models. Just like label and ordinal encoding, we lose the name of the actual values for each particular feature. A far greater drawback, however, is the fact that as its name implies, we can only use target encoding when dealing with labeled data. If we don’t know what the target is, then this all goes out the window. I also believe that when you have very few features in a dataset, target encoding may lead to overfitting as you are integrating the target column into your data directly and this may have an overpowering effect with few unique features or relatively few unique values per feature. Table of contents Before I run the models, I want to quickly apply max-absolute scaling so that we can compare coefficients of different magnitudes. More information on max-absolute scaling can be found at the documentation. I should re-iterate that this will not affect our models in any extreme way as the accuracy remains basically the same even without scaling but the coefficients cannot be compared at different scales. Next, I’ll make a function to run and evaluate models. Building reg_model function Input is data frame to test Inputs is set to X and target to y Train test split on data for model validation purposes (see documentation for more) Instantiate linear regression and fit on train data Store predictions on test data Print score and error in predictions Create and return data frame containing coefficient data Interestingly, one-hot performed best in this setting. I also like using one-hot encoding here due to the fact there are few unique categorical values. Another interesting observation is the difference in clarity’s effect between label and target encoding. I’m a little perplexed by what I see in the one-hot model coefficients, and definitely will have to investigate this further. Table of contents This post served as introduction to the problem categorical data represents in data science and we addressed the benefits and drawbacks of various common methods available. We also ran some models to see each method in action. I hope this post will help readers think of creative and strategic ways to address categorical data in their future projects. Table of contents What are categorical, discrete, and continuous variables? Retrieved from: https://support.minitab.com/en-us/minitab-express/1/help-and-how-to/modeling-statistics/regression/supporting-topics/basics/what-are-categorical-discrete-and-continuous-variables/#:~:text=Categorical%20variables%20contain%20a%20finite,not%20have%20a%20logical%20order.&text=Continuous%20variables%20are%20numeric%20variables,be%20numeric%20or%20date%2Ftime. Agrawal, S. Diamonds. Retrieved from: https://www.kaggle.com/shivam2503/diamonds Svideloc, 2020. Retrieved from: https://medium.com/analytics-vidhya/target-encoding-vs-one-hot-encoding-with-simple-examples-276a7e7b3e64#:~:text=Limitations%20of%20Target%20Encoding,improvements%20some%20of%20the%20time. Table of contents
[ { "code": null, "e": 335, "s": 172, "text": "IntroductionCategorical DataWhy Encode Categorical Data?Example DatasetOne-Hot EncodingLabel Encoding and Ordinal EncodingTarget EncodingModelsConclusionResources" }, { "code": null, "e": 348, "s": 335, "text": "Introduction" }, { "code": null, "e": 365, "s": 348, "text": "Categorical Data" }, { "code": null, "e": 394, "s": 365, "text": "Why Encode Categorical Data?" }, { "code": null, "e": 410, "s": 394, "text": "Example Dataset" }, { "code": null, "e": 427, "s": 410, "text": "One-Hot Encoding" }, { "code": null, "e": 463, "s": 427, "text": "Label Encoding and Ordinal Encoding" }, { "code": null, "e": 479, "s": 463, "text": "Target Encoding" }, { "code": null, "e": 486, "s": 479, "text": "Models" }, { "code": null, "e": 497, "s": 486, "text": "Conclusion" }, { "code": null, "e": 507, "s": 497, "text": "Resources" }, { "code": null, "e": 526, "s": 507, "text": "Let’s get started." }, { "code": null, "e": 855, "s": 526, "text": "Categorical feature encoding is often a key part of the data science process and can be done in multiple ways leading to different results and a different understanding of input data. Today’s post will address this topic and run some models to point out the differences in my three favorite categorical feature encoding methods." }, { "code": null, "e": 873, "s": 855, "text": "Table of contents" }, { "code": null, "e": 1903, "s": 873, "text": "Naturally, the first topic to be addressed is the definition of what categorical data actually is and what other types of data one normally encounters looks like. Categorical data is non-numeric and often can be characterized into categories or groups. A simple example is is color; red, blue, and yellow are all distinct colors. Another example could be age groups or other interval-type data. Like 1–25 years old, 25–50 years old, and so on. The data used represents numbers, but the intervals themselves are categorical. Discrete data is similar, but is still numeric. An example of discrete data is the sum of two dice thrown. There are a finite and known set of outcomes, but these outcomes are represented numerically. Continuous data concerns data that can take on infinite values between any two points. A good example that really proves this point is that there are infinite values between 1 and 1.01. Continuous data is generally numeric, like in our example above, but can sometimes be represented in date-time format." }, { "code": null, "e": 1921, "s": 1903, "text": "Table of contents" }, { "code": null, "e": 2514, "s": 1921, "text": "We encode categorical data numerically because math is generally done using numbers. A big part of natural language processing is converting text to numbers. Just like that, our algorithms cannot run and process data if that data is not numerical. Therefore, data scientists need to have tools at their disposal to transform colors like red, yellow, and blue into numbers like 1, 2, and 3 for all the backend math to take place. Now that we know what categorical data looks like and have seen some examples, we will examine three common methods to turn our categorical data into numeric data." }, { "code": null, "e": 2532, "s": 2514, "text": "Table of contents" }, { "code": null, "e": 3089, "s": 2532, "text": "Before me move forward, we’ll need some data to work with to show what categorical feature encoding looks like in python and how different methods affect model efficiency. My data comes from kaggle.com, concerns diamond pricing, and can be found here. We will do some basic data preparation just to get a clean data set. Afterwards, using our three methods of categorical feature encoding, we will create three distinct data sets and see which one leads to the best models. The target feature is continuous, so will be predicted via regressor-like methods." }, { "code": null, "e": 3107, "s": 3089, "text": "Install libraries" }, { "code": null, "e": 3156, "s": 3107, "text": "!pip install -U scikit-learn!pip install xgboost" }, { "code": null, "e": 3164, "s": 3156, "text": "Imports" }, { "code": null, "e": 3750, "s": 3164, "text": "import warningswarnings.filterwarnings('ignore')import pandas as pdimport numpy as npimport matplotlib.pyplot as plt%matplotlib inlineimport seaborn as snsfrom scipy import statsfrom sklearn.preprocessing import *from sklearn. metrics import *from sklearn.linear_model import LinearRegression, SGDRegressorfrom sklearn.ensemble import RandomForestRegressorfrom xgboost import XGBClassifier, XGBRegressorfrom sklearn.model_selection import train_test_splitfrom imblearn.datasets import make_imbalancefrom category_encoders.target_encoder import TargetEncoderimport statsmodels.api as sm" }, { "code": null, "e": 3760, "s": 3750, "text": "Read data" }, { "code": null, "e": 3817, "s": 3760, "text": "df = pd.read_csv('diamonds.csv')print(df.shape)df.head()" }, { "code": null, "e": 3874, "s": 3817, "text": "Delete unnamed: 0 and add volume in place of x, y, and z" }, { "code": null, "e": 3957, "s": 3874, "text": "df['volume']=df.x*df.y*df.zdf.drop(['Unnamed: 0','x','y','z'],axis=1,inplace=True)" }, { "code": null, "e": 4715, "s": 3957, "text": "One-hot encoding is a method of identifying whether a unique categorical value from a categorical feature is present or not. What I mean by this is that if our feature is primary color (and each row has only one primary color), one-hot encoding would represent whether the color present in each row is red, blue, or yellow. This is accomplished by adding a new column for each possible color. With these three columns representing color in place for every row of the data, we go through each row and assign the value 1 to the column representing the color present in our current row and fill in the other color columns of that row with a 0 to represent their absence. Let’s look at how we can do this in python and the benefits and drawbacks to this method." }, { "code": null, "e": 4838, "s": 4715, "text": "There are a couple ways to accomplish this task in python, and I’ll focus on what I believe to be the two easiest methods." }, { "code": null, "e": 4876, "s": 4838, "text": "Building one_hot_encoder_one function" }, { "code": null, "e": 4931, "s": 4876, "text": "The inputs are the data and feature you wish to encode" }, { "code": null, "e": 5071, "s": 4931, "text": "The first part is instantiating a one-hot encoder from scikit-learn and more information on this function can be found at the documentation" }, { "code": null, "e": 5175, "s": 5071, "text": "Next, I use this function to transform my data into new columns in a separate data frame with 1s and 0s" }, { "code": null, "e": 5356, "s": 5175, "text": "I am also going to retain information about what features are represented in each column using the get_feature_name function that can be found at the documentation referenced above" }, { "code": null, "e": 5539, "s": 5356, "text": "My next step is optional, but I am basically just adding a prefix referencing my variable which is being encoded and removing some of the text the one-hot encoder will by-default add" }, { "code": null, "e": 5670, "s": 5539, "text": "Next, I add the new data frame back into the same data frame with the old data and delete the column that was just one-hot encoded" }, { "code": null, "e": 5882, "s": 5670, "text": "I have one last optional step at the end which allows you to drop one column from the new one-hot encoded columns or to not drop one column (we would drop one column for the purposes of removing autocorrelation)" }, { "code": null, "e": 5953, "s": 5882, "text": "The return value is the original data with new one-hot encoded columns" }, { "code": null, "e": 5991, "s": 5953, "text": "Building one_hot_encoder_two function" }, { "code": null, "e": 6027, "s": 5991, "text": "The inputs remain the same as above" }, { "code": null, "e": 6150, "s": 6027, "text": "This function is very similar, except we leverage the pandas.get_dummies() function, whose documentation can be found here" }, { "code": null, "e": 6375, "s": 6150, "text": "The get_dummies basically accomplishes the same task as the one-hot encoder, except we never lose the information regarding what feature is represented in each column and therefore we don’t need get_feature_names in the code" }, { "code": null, "e": 6472, "s": 6375, "text": "The rest is the same; we combine the data and potentially remove one column for auto correlation" }, { "code": null, "e": 6544, "s": 6472, "text": "These functions will work well, but are only meant for categorical data" }, { "code": null, "e": 6586, "s": 6544, "text": "Let’s look at the output of each function" }, { "code": null, "e": 6618, "s": 6586, "text": "We’ll start with the basic data" }, { "code": null, "e": 6638, "s": 6618, "text": "one_hot_encoder_one" }, { "code": null, "e": 6658, "s": 6638, "text": "one_hot_encoder_two" }, { "code": null, "e": 6702, "s": 6658, "text": "We clearly see two paths to the same answer" }, { "code": null, "e": 6784, "s": 6702, "text": "Let’s run a loop and save our data as df_one_hot for the models we will later run" }, { "code": null, "e": 6904, "s": 6784, "text": "df_one_hot=df.copy()for col in df.select_dtypes(include='O').columns: df_one_hot=one_hot_encoder_one(df_one_hot,col)" }, { "code": null, "e": 7063, "s": 6904, "text": "We see above that row two has a clarity rating of “SI1” (look at kaggle for more information on what this means) and that row one has a cut rating of “ideal.”" }, { "code": null, "e": 7730, "s": 7063, "text": "One obvious benefit of one-hot encoding is that you notice if any particular unique values within a set of values have an outsized or strong impact in either a positive or negative direction. For example, I used one-hot encoding on a recent project I worked on to measure the likeliness of getting a deal on Shark Tank given the presence of each shark during a particular pitch. Unlike other types of encoding, with one-hot encoding you maintain information on the values of each variable. With label encoding, as we will see below, we get a good measure of the impact of a particular feature on models, but not the specific impacts of unique values of that feature." }, { "code": null, "e": 8990, "s": 7730, "text": "While it’s nice to know the impact, positive or negative, of each unique occurrence in categorical data, it could sometimes make models less accurate. More importantly though, if some unique values are far more common than others, we may erroneously assume that these values are very important when they actually are not. For example, let’s say that you work in a building with the same 1000 people coming in and out every day. One day, someone who has never been to the building walks in, we’ll call him Joseph (my name), and the power in the building goes out. It would be pretty silly to blame Joseph for the power outage, but our data does in fact indicate that 100% of the time Joseph is in the building, we witness a power outage. For this reason, I like using one-hot encoding for features when there aren’t an overwhelming amount of unique values and/or the distribution of unique values is relatively balanced. Similarly, the size of the data set should be large enough so the amount of unique values and their distributions won’t be problematic. One other problem is that since we delete our feature once encoding it, the feature itself’s effect may be somewhat lost as we shift our attention to the values of the feature and not the feature itself." }, { "code": null, "e": 9008, "s": 8990, "text": "Table of contents" }, { "code": null, "e": 10133, "s": 9008, "text": "Label encoding is probably the most basic type of categorical feature encoding method after one-hot encoding. Label encoding doesn’t add any extra columns to the data but instead assigns a number to each unique value in a feature. Let’s use the colors example again. Instead of adding a column for red, another one for blue, and one more for yellow, we just assign each value a number. Red is 1, blue is 2, and yellow is 3. We saved a lot of room and don’t add more columns to our data, resulting in a much cleaner look for the data. The numbers assigned for red, blue, and yellow are arbitrary and their labels have no actual meaning, but they are simple to deal with. Ordinal encoding is a slightly-advanced form of label encoding; we assign labels based on an order or hierarchy. For colors, I am not an artist, so I see no reason to not assign numbers to color at random. However, if we are dealing with cuts of diamonds, as the data for this blog deals with, we may want to set up a system where the worse cuts are either assigned a higher or lower number. In the code below we will use both label and ordinal encoding." }, { "code": null, "e": 10238, "s": 10133, "text": "For label encoding, we have a very simple and easy python function whose documentation can be found here" }, { "code": null, "e": 10306, "s": 10238, "text": "We will once again run a loop and save the data as label_encoded_df" }, { "code": null, "e": 10482, "s": 10306, "text": "le = LabelEncoder()label_encoded_df = df.copy()for col in label_encoded_df.select_dtypes(include='O').columns: label_encoded_df[col]=le.fit_transform(label_encoded_df[col])" }, { "code": null, "e": 10558, "s": 10482, "text": "Now, for cut, clarity, and color, we have arbitrary numeric representations" }, { "code": null, "e": 10869, "s": 10558, "text": "For ordinal encoding, python has a package whose documentation can be found here. I personally like to perform ordinal encoding using dictionary mapping though. Even if you were to use the python package there is still some manual work to be done, therefore I will present a function for ordinal encoding below" }, { "code": null, "e": 10903, "s": 10869, "text": "Building ordinal_encoder function" }, { "code": null, "e": 11072, "s": 10903, "text": "The inputs are the data, a feature to encode, and an ordered list of unique values from the feature (be consistent on whether you want the best value to be low or high)" }, { "code": null, "e": 11209, "s": 11072, "text": "An empty dictionary is created and the subsequently filled with a number for each value (I write +1, to start our values at 1 and not 0)" }, { "code": null, "e": 11287, "s": 11209, "text": "This structure is then mapped onto each occurrence of the feature in the data" }, { "code": null, "e": 11357, "s": 11287, "text": "The return value is the old data frame with the new encoding in place" }, { "code": null, "e": 11404, "s": 11357, "text": "Let’s quickly see one example of this strategy" }, { "code": null, "e": 11418, "s": 11404, "text": "Original data" }, { "code": null, "e": 11435, "s": 11418, "text": "New look at data" }, { "code": null, "e": 11513, "s": 11435, "text": "We clearly see ideal is represented by 1 and lower grades have higher numbers" }, { "code": null, "e": 11812, "s": 11513, "text": "An obvious benefit to label encoding is that it’s quick, easy, and doesn’t create a messy data frame in the way that one-hot encoding adds a lot of columns. Ordinal encoding, which I consider to be an extension of label encoding, imposes extra meaning to the labels assigned through label encoding." }, { "code": null, "e": 12599, "s": 11812, "text": "In label encoding, one major drawback is that our labels are rather arbitrary. Even in ordinal encoding, who’s to say that the step between rank 4 and 5 is the same as a step between 2 and 3? Maybe the difference between what we call 4 and 5 is marginal, while the difference between what we call 2 and 3 is huge. As mentioned above, one other drawback is that while we can find how strong or weak the impact of a particular feature is, we lose all information on unique values within that feature (this is moderately addressed with ordinal encoding, but the effect is marginal). Finally, this method may not work well with outliers as there is the possibility that certain labels may not appear in similar frequencies to the other labels. We see this same problem with target encoding." }, { "code": null, "e": 12617, "s": 12599, "text": "Table of contents" }, { "code": null, "e": 13760, "s": 12617, "text": "Target encoding happens to be my favorite method of encoding as I find it most often produces the strongest models. Target encoding aligns unique categorical values with the target feature based on the average relationship. Say we are presented with a data set trying to predict a house’s price range based on color. Like above, our colors are red, yellow, and blue. Let’s also say our price ranges for houses are 1, 2, 3, and 4 and our features include basic housing things like square footage and other features (but also color). If we see that red houses tend to fall on average at a 3.35, it means red houses are slightly above a 3 but far below a 4. We then assign every occurrence of the value red to 3.35 as that is the mean target value. This is taking label and ordinal encoding to the next level. We introduce meaningful numbers to take the place of colors as opposed to arbitrary numbers. Also, if blue houses fall at 3.34, or even at 3.35 like red, we have no problem and can assign the number 3.34 or 3.35 to blue. This “double-labeling” (that’s what I have decided to call it) would be impossible with label or ordinal encoding." }, { "code": null, "e": 13998, "s": 13760, "text": "Target encoding, like other encoders has a python package. It’s a user-friendly package and I will show how to use it. I will also, however, add a more descriptive function to give you further insight into the backend of target encoding." }, { "code": null, "e": 14063, "s": 13998, "text": "First, the python package whose documentation can be found here." }, { "code": null, "e": 14208, "s": 14063, "text": "te_df=df.copy()for col in te_df.select_dtypes(include='O').columns: te=TargetEncoder() te_df[col]=te.fit_transform(te_df[col],te_df.price)" }, { "code": null, "e": 14222, "s": 14208, "text": "Original data" }, { "code": null, "e": 14231, "s": 14222, "text": "New data" }, { "code": null, "e": 14268, "s": 14231, "text": "Now, for a more descriptive function" }, { "code": null, "e": 14302, "s": 14268, "text": "Building target_encoding function" }, { "code": null, "e": 14353, "s": 14302, "text": "Inputs are data, a feature, and the target feature" }, { "code": null, "e": 14485, "s": 14353, "text": "A new data frame is created containing each unique value of a feature from the data which is then grouped by it’s mean target value" }, { "code": null, "e": 14603, "s": 14485, "text": "An empty dictionary is then created, filled with this data, and mapped to each unique value of the particular feature" }, { "code": null, "e": 14673, "s": 14603, "text": "The return value is the data frame with new target encodings in place" }, { "code": null, "e": 14721, "s": 14673, "text": "Let’s see the same result with the new function" }, { "code": null, "e": 14827, "s": 14721, "text": "te_df=df.copy()for col in te_df.select_dtypes(include='O').columns: target_encoding(te_df,col,'price')" }, { "code": null, "e": 14841, "s": 14827, "text": "Original Data" }, { "code": null, "e": 14850, "s": 14841, "text": "New Data" }, { "code": null, "e": 14941, "s": 14850, "text": "Notice how color remains the same number through the first three rows per our expectations" }, { "code": null, "e": 14971, "s": 14941, "text": "We’ll save this data as te_df" }, { "code": null, "e": 15183, "s": 14971, "text": "Target encoding is the most meaningful way I can think of to attach numbers to categorical values. It’s a simple concept and is easy and expedient to apply. I also find that it usually generates the best models." }, { "code": null, "e": 15777, "s": 15183, "text": "Just like label and ordinal encoding, we lose the name of the actual values for each particular feature. A far greater drawback, however, is the fact that as its name implies, we can only use target encoding when dealing with labeled data. If we don’t know what the target is, then this all goes out the window. I also believe that when you have very few features in a dataset, target encoding may lead to overfitting as you are integrating the target column into your data directly and this may have an overpowering effect with few unique features or relatively few unique values per feature." }, { "code": null, "e": 15795, "s": 15777, "text": "Table of contents" }, { "code": null, "e": 16203, "s": 15795, "text": "Before I run the models, I want to quickly apply max-absolute scaling so that we can compare coefficients of different magnitudes. More information on max-absolute scaling can be found at the documentation. I should re-iterate that this will not affect our models in any extreme way as the accuracy remains basically the same even without scaling but the coefficients cannot be compared at different scales." }, { "code": null, "e": 16258, "s": 16203, "text": "Next, I’ll make a function to run and evaluate models." }, { "code": null, "e": 16286, "s": 16258, "text": "Building reg_model function" }, { "code": null, "e": 16314, "s": 16286, "text": "Input is data frame to test" }, { "code": null, "e": 16349, "s": 16314, "text": "Inputs is set to X and target to y" }, { "code": null, "e": 16433, "s": 16349, "text": "Train test split on data for model validation purposes (see documentation for more)" }, { "code": null, "e": 16485, "s": 16433, "text": "Instantiate linear regression and fit on train data" }, { "code": null, "e": 16516, "s": 16485, "text": "Store predictions on test data" }, { "code": null, "e": 16553, "s": 16516, "text": "Print score and error in predictions" }, { "code": null, "e": 16610, "s": 16553, "text": "Create and return data frame containing coefficient data" }, { "code": null, "e": 16993, "s": 16610, "text": "Interestingly, one-hot performed best in this setting. I also like using one-hot encoding here due to the fact there are few unique categorical values. Another interesting observation is the difference in clarity’s effect between label and target encoding. I’m a little perplexed by what I see in the one-hot model coefficients, and definitely will have to investigate this further." }, { "code": null, "e": 17011, "s": 16993, "text": "Table of contents" }, { "code": null, "e": 17364, "s": 17011, "text": "This post served as introduction to the problem categorical data represents in data science and we addressed the benefits and drawbacks of various common methods available. We also ran some models to see each method in action. I hope this post will help readers think of creative and strategic ways to address categorical data in their future projects." }, { "code": null, "e": 17382, "s": 17364, "text": "Table of contents" }, { "code": null, "e": 17814, "s": 17382, "text": "What are categorical, discrete, and continuous variables? Retrieved from: https://support.minitab.com/en-us/minitab-express/1/help-and-how-to/modeling-statistics/regression/supporting-topics/basics/what-are-categorical-discrete-and-continuous-variables/#:~:text=Categorical%20variables%20contain%20a%20finite,not%20have%20a%20logical%20order.&text=Continuous%20variables%20are%20numeric%20variables,be%20numeric%20or%20date%2Ftime." }, { "code": null, "e": 17895, "s": 17814, "text": "Agrawal, S. Diamonds. Retrieved from: https://www.kaggle.com/shivam2503/diamonds" }, { "code": null, "e": 18117, "s": 17895, "text": "Svideloc, 2020. Retrieved from: https://medium.com/analytics-vidhya/target-encoding-vs-one-hot-encoding-with-simple-examples-276a7e7b3e64#:~:text=Limitations%20of%20Target%20Encoding,improvements%20some%20of%20the%20time." } ]
Check if the door is open or closed | Practice | GeeksforGeeks
Given N doors and N persons. The doors are numbered from 1 to N and persons are given id’s numbered from 1 to N. Each door can have only two statuses i.e. open (1) or closed (0) . Initially all the doors have status closed. Find the final status of all the doors, when all the persons have changed the status of the doors of which they are authorized. i.e. if status open then change the status to closed and vice versa. A person with id ‘i’ is authorized to change the status of door numbered ‘j’ if ‘j’ is a multiple of ‘i’. Note: A person has to change the current status of all the doors for which he is authorized exactly once. Example 1: Input: N = 3 Output: 1 0 0 Explanation: Initiall status of rooms - 0 0 0. Person with id 2 changes room 2 to open, i.e. (0 1 0). Person with id 1 changes room 1, 2, 3 status (1 0 1). Person with id 3 changes room 3 status i.e. (1 0 0). Example 2: Input: N = 2 Output: 1 0 Explanation: Initiall status of rooms - 0 0. Person with id 2 changes room 2 to open, i.e. (0 1). Person with id 1 changes room 1, 2 status (1 0). Your Task: You don't need to read input or print anything. Your task is to complete the function checkDoorStatus() which takes an Integer N as input and returns an array as the answer. Expected Time Complexity: O(N*sqrt(N)) Expected Auxiliary Space: O(N) Constraints: 1 <= N <= 104 0 mayank20212 weeks ago C++ : 0.03/1.4int *checkDoorStatus(int N) { // int arr[N]; int *arr = new int[N]; for(int i=1; i<= N ; i++) { int sqrti=sqrt(i); if(sqrti*sqrti==i) arr[i-1]=1; else arr[i-1]=0; } return arr; } +2 ncln538jsgdizpte5utrdkgdmv73rde23vovyyh52 months ago int numberoffactor(int n){ int count = 0; for(int i=1;i*i<=n;i++){ if(n%i==0){ count++; if(n/i!=i){ count++; } } } return count; } int *checkDoorStatus(int N) { // code here int *arr = new int[N]; for(int i=0;i<N;i++){ arr[i] = 0; } for(int i=4;i<=N;i++){ if(numberoffactor(i)%2 !=0){ arr[i-1] = 1; } } arr[0] = 1; return arr; } 0 gayathrisrujanareddy2 months ago class Solution: def checkDoorStatus(self, N): # code here l=[] for i in range(N): l.append(0) for i in range(1,N+1): ans=math.sqrt(i) if ans==int(ans): l[i-1]=1 return l 0 abhishekpundir5264 months ago int *checkDoorStatus(int N) { int *arr = new int [N]; int i = 1; while(i*i <= N){ arr[(i*i) - 1] = 1; i++; } return arr; } +1 badgujarsachin835 months ago int *checkDoorStatus(int N) { // code here int *a=(int*)malloc(sizeof(int)*N); for(int i=0;i<=N;i++){ int no=sqrt(i); if(no*no==i){ a[i-1]=1; } } return a; } -1 s87647 months ago import mathclass Solution: def checkDoorStatus(self, N): # code here status=[0]*N for i in range(1,N+1): sq=math.sqrt(i) if sq==int(sq): status[i-1]=1 return status '''here if the no of factors are odd then the door will be opened to check if the no of factors are odd just check whether the sq of number == int(sq of number) if yes then it will have odd factors''' 0 s8764 This comment was deleted. -1 chaithrarhsn7 months ago def checkDoorStatus(self, N): self.N=N c=[] for i in range(1,self.N+1): num=int(math.sqrt(i)) if num*num==i: c.append(1) else: c.append(0) return c 0 Laksh Chanan8 months ago Laksh Chanan JAVA SOLUTIONstatic int[] checkDoorStatus(int n) { int[] res = new int[n]; for(int i = 1;i*i <= n;i++) res[i*i-1] = 1; return res; } -1 Pritam Majumder9 months ago Pritam Majumder class Solution { public: int *checkDoorStatus(int N) { int *a = (int *)malloc(sizeof(int) * N); for(int i = 1; i <= N; i++) { int num = (int)sqrt(i); /*if num is a perfect square then door is open*/ if((num*num) == i) { /*i-1 because here loop starts from 1 but array starts from index 0 (i-1)*/ a[i-1] = 1; } } return a; }}; 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": 871, "s": 238, "text": "Given N doors and N persons. The doors are numbered from 1 to N and persons are given id’s numbered from 1 to N. Each door can have only two statuses i.e. open (1) or closed (0) . Initially all the doors have status closed. Find the final status of all the doors, when all the persons have changed the status of the doors of which they are authorized. i.e. if status open then change the status to closed and vice versa. A person with id ‘i’ is authorized to change the status of door numbered ‘j’ if ‘j’ is a multiple of ‘i’.\nNote: A person has to change the current status of all the doors for which he is authorized exactly once." }, { "code": null, "e": 885, "s": 873, "text": "Example 1: " }, { "code": null, "e": 1123, "s": 885, "text": "Input:\nN = 3\nOutput:\n1 0 0 \nExplanation:\nInitiall status of rooms - 0 0 0. \nPerson with id 2 changes room 2 to open,\ni.e. (0 1 0). Person with id 1 changes\nroom 1, 2, 3 status (1 0 1).\nPerson with id 3 changes room 3\nstatus i.e. (1 0 0)." }, { "code": null, "e": 1135, "s": 1123, "text": "Example 2: " }, { "code": null, "e": 1309, "s": 1135, "text": "Input:\nN = 2\nOutput:\n1 0\nExplanation:\nInitiall status of rooms - 0 0. \nPerson with id 2 changes room 2 to open,\ni.e. (0 1). Person with id 1 changes\nroom 1, 2 status (1 0).\n" }, { "code": null, "e": 1496, "s": 1311, "text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function checkDoorStatus() which takes an Integer N as input and returns an array as the answer." }, { "code": null, "e": 1568, "s": 1498, "text": "Expected Time Complexity: O(N*sqrt(N))\nExpected Auxiliary Space: O(N)" }, { "code": null, "e": 1597, "s": 1570, "text": "Constraints:\n1 <= N <= 104" }, { "code": null, "e": 1599, "s": 1597, "text": "0" }, { "code": null, "e": 1621, "s": 1599, "text": "mayank20212 weeks ago" }, { "code": null, "e": 1685, "s": 1621, "text": "C++ : 0.03/1.4int *checkDoorStatus(int N) { // int arr[N];" }, { "code": null, "e": 1892, "s": 1685, "text": " int *arr = new int[N]; for(int i=1; i<= N ; i++) { int sqrti=sqrt(i); if(sqrti*sqrti==i) arr[i-1]=1; else arr[i-1]=0; } return arr; }" }, { "code": null, "e": 1895, "s": 1892, "text": "+2" }, { "code": null, "e": 1948, "s": 1895, "text": "ncln538jsgdizpte5utrdkgdmv73rde23vovyyh52 months ago" }, { "code": null, "e": 2480, "s": 1948, "text": "int numberoffactor(int n){ int count = 0; for(int i=1;i*i<=n;i++){ if(n%i==0){ count++; if(n/i!=i){ count++; } } } return count; } int *checkDoorStatus(int N) { // code here int *arr = new int[N]; for(int i=0;i<N;i++){ arr[i] = 0; } for(int i=4;i<=N;i++){ if(numberoffactor(i)%2 !=0){ arr[i-1] = 1; } } arr[0] = 1; return arr; }" }, { "code": null, "e": 2482, "s": 2480, "text": "0" }, { "code": null, "e": 2515, "s": 2482, "text": "gayathrisrujanareddy2 months ago" }, { "code": null, "e": 2771, "s": 2515, "text": "class Solution:\n def checkDoorStatus(self, N):\n # code here\n l=[]\n for i in range(N):\n l.append(0)\n for i in range(1,N+1):\n ans=math.sqrt(i)\n if ans==int(ans):\n l[i-1]=1\n return l" }, { "code": null, "e": 2773, "s": 2771, "text": "0" }, { "code": null, "e": 2803, "s": 2773, "text": "abhishekpundir5264 months ago" }, { "code": null, "e": 3003, "s": 2803, "text": " int *checkDoorStatus(int N) { int *arr = new int [N]; int i = 1; while(i*i <= N){ arr[(i*i) - 1] = 1; i++; } return arr; }" }, { "code": null, "e": 3006, "s": 3003, "text": "+1" }, { "code": null, "e": 3035, "s": 3006, "text": "badgujarsachin835 months ago" }, { "code": null, "e": 3279, "s": 3035, "text": "int *checkDoorStatus(int N) {\n // code here\n int *a=(int*)malloc(sizeof(int)*N);\n for(int i=0;i<=N;i++){\n int no=sqrt(i);\n if(no*no==i){\n a[i-1]=1;\n }\n }\n return a;\n }" }, { "code": null, "e": 3282, "s": 3279, "text": "-1" }, { "code": null, "e": 3300, "s": 3282, "text": "s87647 months ago" }, { "code": null, "e": 3763, "s": 3300, "text": "import mathclass Solution: def checkDoorStatus(self, N): # code here status=[0]*N for i in range(1,N+1): sq=math.sqrt(i) if sq==int(sq): status[i-1]=1 return status '''here if the no of factors are odd then the door will be opened to check if the no of factors are odd just check whether the sq of number == int(sq of number) if yes then it will have odd factors''' " }, { "code": null, "e": 3765, "s": 3763, "text": "0" }, { "code": null, "e": 3771, "s": 3765, "text": "s8764" }, { "code": null, "e": 3797, "s": 3771, "text": "This comment was deleted." }, { "code": null, "e": 3800, "s": 3797, "text": "-1" }, { "code": null, "e": 3825, "s": 3800, "text": "chaithrarhsn7 months ago" }, { "code": null, "e": 4071, "s": 3825, "text": " def checkDoorStatus(self, N): self.N=N c=[] for i in range(1,self.N+1): num=int(math.sqrt(i)) if num*num==i: c.append(1) else: c.append(0) return c" }, { "code": null, "e": 4073, "s": 4071, "text": "0" }, { "code": null, "e": 4098, "s": 4073, "text": "Laksh Chanan8 months ago" }, { "code": null, "e": 4111, "s": 4098, "text": "Laksh Chanan" }, { "code": null, "e": 4283, "s": 4111, "text": "JAVA SOLUTIONstatic int[] checkDoorStatus(int n) { int[] res = new int[n]; for(int i = 1;i*i <= n;i++) res[i*i-1] = 1; return res; }" }, { "code": null, "e": 4286, "s": 4283, "text": "-1" }, { "code": null, "e": 4314, "s": 4286, "text": "Pritam Majumder9 months ago" }, { "code": null, "e": 4330, "s": 4314, "text": "Pritam Majumder" }, { "code": null, "e": 4793, "s": 4330, "text": "class Solution { public: int *checkDoorStatus(int N) { int *a = (int *)malloc(sizeof(int) * N); for(int i = 1; i <= N; i++) { int num = (int)sqrt(i); /*if num is a perfect square then door is open*/ if((num*num) == i) { /*i-1 because here loop starts from 1 but array starts from index 0 (i-1)*/ a[i-1] = 1; } } return a; }};" }, { "code": null, "e": 4939, "s": 4793, "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": 4975, "s": 4939, "text": " Login to access your submissions. " }, { "code": null, "e": 4985, "s": 4975, "text": "\nProblem\n" }, { "code": null, "e": 4995, "s": 4985, "text": "\nContest\n" }, { "code": null, "e": 5058, "s": 4995, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5206, "s": 5058, "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": 5414, "s": 5206, "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": 5520, "s": 5414, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
C# | Static Class - GeeksforGeeks
22 Jul, 2021 In C#, one is allowed to create a static class, by using static keyword. A static class can only contain static data members, static methods, and a static constructor.It is not allowed to create objects of the static class. Static classes are sealed, means you cannot inherit a static class from another class. Syntax: static class Class_Name { // static data members // static method } In C#, the static class contains two types of static members as follows: Static Data Members: As static class always contains static data members, so static data members are declared using static keyword and they are directly accessed by using the class name. The memory of static data members is allocating individually without any relation with the object.Syntax: static class Class_name { public static nameofdatamember; } Static Methods: As static class always contains static methods, so static methods are declared using static keyword. These methods only access static data members, they can not access non-static data members. Syntax: static class Class_name { public static nameofmethod() { // code } } Example 1: C# // C# program to illustrate the// concept of static classusing System; namespace ExampleOfStaticClass { // Creating static class// Using static keywordstatic class Author { // Static data members of Author public static string A_name = "Ankita"; public static string L_name = "CSharp"; public static int T_no = 84; // Static method of Author public static void details() { Console.WriteLine("The details of Author is:"); }} // Driver Classpublic class GFG { // Main Method static public void Main() { // Calling static method of Author Author.details(); // Accessing the static data members of Author Console.WriteLine("Author name : {0} ", Author.A_name); Console.WriteLine("Language : {0} ", Author.L_name); Console.WriteLine("Total number of articles : {0} ", Author.T_no); }}} The details of Author is: Author name : Ankita Language : CSharp Total number of articles : 84 Example 2: C# // C# program to demonstrate// the concept of static classusing System; // declaring a static classpublic static class GFG { // declaring static Method static void display() { Console.WriteLine("Static Method of class GFG"); } } // trying to inherit the class GFG// it will give error as static// class can't be inheritedclass GFG2 : GFG { public static void Main(String[] args) { }} Compile Time Error: prog.cs(20,7): error CS0709: `GFG2′: Cannot derive from static class `GFG’ Explanation: In the above example, we have a static class named as Author by using static keyword. The Author class contains static data members named A_name, L_name, and T_no, and a static method named as details(). The method of a static class is simply called by using its class name like Author.details();. As we know that static class doesn’t consist object so the data member of the Author class is accessed by its class name, like Author.A_name, Author.L_name, and Author.T_no. sumitgumber28 CSharp-OOP C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C# | Method Overriding C# Dictionary with examples Difference between Ref and Out keywords in C# Top 50 C# Interview Questions & Answers Introduction to .NET Framework C# | Constructors C# | Abstract Classes C# | String.IndexOf( ) Method | Set - 1 Different ways to sort an array in descending order in C# C# | Arrays
[ { "code": null, "e": 23485, "s": 23457, "text": "\n22 Jul, 2021" }, { "code": null, "e": 23796, "s": 23485, "text": "In C#, one is allowed to create a static class, by using static keyword. A static class can only contain static data members, static methods, and a static constructor.It is not allowed to create objects of the static class. Static classes are sealed, means you cannot inherit a static class from another class." }, { "code": null, "e": 23805, "s": 23796, "text": "Syntax: " }, { "code": null, "e": 23886, "s": 23805, "text": "static class Class_Name\n{\n\n // static data members \n // static method\n}" }, { "code": null, "e": 23959, "s": 23886, "text": "In C#, the static class contains two types of static members as follows:" }, { "code": null, "e": 24253, "s": 23959, "text": "Static Data Members: As static class always contains static data members, so static data members are declared using static keyword and they are directly accessed by using the class name. The memory of static data members is allocating individually without any relation with the object.Syntax: " }, { "code": null, "e": 24318, "s": 24253, "text": "static class Class_name \n{\n public static nameofdatamember;\n}" }, { "code": null, "e": 24536, "s": 24318, "text": "Static Methods: As static class always contains static methods, so static methods are declared using static keyword. These methods only access static data members, they can not access non-static data members. Syntax: " }, { "code": null, "e": 24629, "s": 24536, "text": "static class Class_name {\n\n public static nameofmethod()\n {\n // code \n }\n}" }, { "code": null, "e": 24641, "s": 24629, "text": "Example 1: " }, { "code": null, "e": 24644, "s": 24641, "text": "C#" }, { "code": "// C# program to illustrate the// concept of static classusing System; namespace ExampleOfStaticClass { // Creating static class// Using static keywordstatic class Author { // Static data members of Author public static string A_name = \"Ankita\"; public static string L_name = \"CSharp\"; public static int T_no = 84; // Static method of Author public static void details() { Console.WriteLine(\"The details of Author is:\"); }} // Driver Classpublic class GFG { // Main Method static public void Main() { // Calling static method of Author Author.details(); // Accessing the static data members of Author Console.WriteLine(\"Author name : {0} \", Author.A_name); Console.WriteLine(\"Language : {0} \", Author.L_name); Console.WriteLine(\"Total number of articles : {0} \", Author.T_no); }}}", "e": 25560, "s": 24644, "text": null }, { "code": null, "e": 25657, "s": 25560, "text": "The details of Author is:\nAuthor name : Ankita \nLanguage : CSharp \nTotal number of articles : 84" }, { "code": null, "e": 25670, "s": 25659, "text": "Example 2:" }, { "code": null, "e": 25673, "s": 25670, "text": "C#" }, { "code": "// C# program to demonstrate// the concept of static classusing System; // declaring a static classpublic static class GFG { // declaring static Method static void display() { Console.WriteLine(\"Static Method of class GFG\"); } } // trying to inherit the class GFG// it will give error as static// class can't be inheritedclass GFG2 : GFG { public static void Main(String[] args) { }}", "e": 26115, "s": 25673, "text": null }, { "code": null, "e": 26135, "s": 26115, "text": "Compile Time Error:" }, { "code": null, "e": 26210, "s": 26135, "text": "prog.cs(20,7): error CS0709: `GFG2′: Cannot derive from static class `GFG’" }, { "code": null, "e": 26697, "s": 26210, "text": "Explanation: In the above example, we have a static class named as Author by using static keyword. The Author class contains static data members named A_name, L_name, and T_no, and a static method named as details(). The method of a static class is simply called by using its class name like Author.details();. As we know that static class doesn’t consist object so the data member of the Author class is accessed by its class name, like Author.A_name, Author.L_name, and Author.T_no. " }, { "code": null, "e": 26713, "s": 26699, "text": "sumitgumber28" }, { "code": null, "e": 26724, "s": 26713, "text": "CSharp-OOP" }, { "code": null, "e": 26727, "s": 26724, "text": "C#" }, { "code": null, "e": 26825, "s": 26727, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26834, "s": 26825, "text": "Comments" }, { "code": null, "e": 26847, "s": 26834, "text": "Old Comments" }, { "code": null, "e": 26870, "s": 26847, "text": "C# | Method Overriding" }, { "code": null, "e": 26898, "s": 26870, "text": "C# Dictionary with examples" }, { "code": null, "e": 26944, "s": 26898, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 26984, "s": 26944, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 27015, "s": 26984, "text": "Introduction to .NET Framework" }, { "code": null, "e": 27033, "s": 27015, "text": "C# | Constructors" }, { "code": null, "e": 27055, "s": 27033, "text": "C# | Abstract Classes" }, { "code": null, "e": 27095, "s": 27055, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 27153, "s": 27095, "text": "Different ways to sort an array in descending order in C#" } ]
A hands-on intuitive approach to Deep Learning Methods for Text Data — Word2Vec, GloVe and FastText | by Dipanjan (DJ) Sarkar | Towards Data Science
Working with unstructured text data is hard especially when you are trying to build an intelligent system which interprets and understands free flowing natural language just like humans. You need to be able to process and transform noisy, unstructured textual data into some structured, vectorized formats which can be understood by any machine learning algorithm. Principles from Natural Language Processing, Machine Learning or Deep Learning all of which fall under the broad umbrella of Artificial Intelligence are effective tools of the trade. Based on my previous posts, an important point to remember here is that any machine learning algorithm is based on principles of statistics, math and optimization. Hence they are not intelligent enough to start processing text in their raw, native form. We covered some traditional strategies for extracting meaningful features from text data in Part-3: Traditional Methods for Text Data. I encourage you to check out the same for a brief refresher. In this article, we will be looking at more advanced feature engineering strategies which often leverage deep learning models. More specifically we will be covering the Word2Vec, GloVe and FastText models. We have discussed time and again including in our previous article that Feature Engineering is the secret sauce to creating superior and better performing machine learning models. Always remember that even with the advent of automated feature engineering capabilities, you would still need to understand the core concepts behind applying the techniques. Otherwise they would just be black box models which you wouldn’t know how to tweak and tune for the problem you are trying to solve. Traditional (count-based) feature engineering strategies for textual data involve models belonging to a family of models popularly known as the Bag of Words model. This includes term frequencies, TF-IDF (term frequency-inverse document frequency), N-grams and so on. While they are effective methods for extracting features from text, due to the inherent nature of the model being just a bag of unstructured words, we lose additional information like the semantics, structure, sequence and context around nearby words in each text document. This forms as enough motivation for us to explore more sophisticated models which can capture this information and give us features which are vector representation of words, popularly known as embeddings. While this does make some sense, why should we be motivated enough to learn and build these word embeddings? With regard to speech or image recognition systems, all the information is already present in the form of rich dense feature vectors embedded in high-dimensional datasets like audio spectrograms and image pixel intensities. However when it comes to raw text data, especially count based models like Bag of Words, we are dealing with individual words which may have their own identifiers and do not capture the semantic relationship amongst words. This leads to huge sparse word vectors for textual data and thus if we do not have enough data, we may end up getting poor models or even overfitting the data due to the curse of dimensionality. To overcome the shortcomings of losing out semantics and feature sparsity in bag of words model based features, we need to make use of Vector Space Models (VSMs) in such a way that we can embed word vectors in this continuous vector space based on semantic and contextual similarity. In fact the distributional hypothesis in the field of distributional semantics tells us that words which occur and are used in the same context, are semantically similar to one another and have similar meanings. In simple terms, ‘a word is characterized by the company it keeps’. One of the famous papers talking about these semantic word vectors and various types in detail is ‘Don’t count, predict! A systematic comparison of context-counting vs. context-predicting semantic vectors’ by Baroni et al. We won’t go into extensive depth but in short, there are two main types of methods for contextual word vectors. Count-based methods like Latent Semantic Analysis (LSA) which can be used to compute some statistical measures of how often words occur with their neighboring words in a corpus and then building out dense word vectors for each word from these measures. Predictive methods like Neural Network based language models try to predict words from its neighboring words looking at word sequences in the corpus and in the process it learns distributed representations giving us dense word embeddings. We will be focusing on these predictive methods in this article. Let’s look at some of these advanced strategies for handling text data and extracting meaningful features from the same, which can be used in downstream machine learning systems. Do note that you can access all the code used in this article in my GitHub repository also for future reference. We’ll start by loading up some basic dependencies and settings. import pandas as pdimport numpy as npimport reimport nltkimport matplotlib.pyplot as pltpd.options.display.max_colwidth = 200%matplotlib inline We will now take a few corpora of documents on which we will perform all our analyses. For one of the corpora, we will reuse our corpus from our previous article, Part-3: Traditional Methods for Text Data. We mention the code as follows for ease of understanding. Our toy corpus consists of documents belonging to several categories. Another corpus we will use in this article is the The King James Version of the Bible available freely from Project Gutenberg through the corpus module in nltk. We will load this up shortly, in the next section. Before we talk about feature engineering, we need to pre-process and normalize this text. There can be multiple ways of cleaning and pre-processing textual data. The most important techniques which are used heavily in Natural Language Processing (NLP) pipelines have been highlighted in detail in the ‘Text pre-processing’ section in Part 3 of this series. Since the focus of this article is on feature engineering, just like our previous article, we will re-use our simple text pre-processor which focuses on removing special characters, extra whitespaces, digits, stopwords and lower casing the text corpus. Once we have our basic pre-processing pipeline ready, let’s first apply the same to our toy corpus. norm_corpus = normalize_corpus(corpus)norm_corpusOutput------array(['sky blue beautiful', 'love blue beautiful sky', 'quick brown fox jumps lazy dog', 'kings breakfast sausages ham bacon eggs toast beans', 'love green eggs ham sausages bacon', 'brown fox quick blue dog lazy', 'sky blue sky beautiful today', 'dog lazy brown fox quick'], dtype='<U51') Let’s now load up our other corpus based on The King James Version of the Bible using nltk and pre-process the text. The following output shows the total number of lines in our corpus and how the pre-processing works on the textual content. Output------Total lines: 30103Sample line: ['1', ':', '6', 'And', 'God', 'said', ',', 'Let', 'there', 'be', 'a', 'firmament', 'in', 'the', 'midst', 'of', 'the', 'waters', ',', 'and', 'let', 'it', 'divide', 'the', 'waters', 'from', 'the', 'waters', '.']Processed line: god said let firmament midst waters let divide waters waters Let’s look at some of the popular word embedding models now and engineering features from our corpora! This model was created by Google in 2013 and is a predictive deep learning based model to compute and generate high quality, distributed and continuous dense vector representations of words, which capture contextual and semantic similarity. Essentially these are unsupervised models which can take in massive textual corpora, create a vocabulary of possible words and generate dense word embeddings for each word in the vector space representing that vocabulary. Usually you can specify the size of the word embedding vectors and the total number of vectors are essentially the size of the vocabulary. This makes the dimensionality of this dense vector space much lower than the high-dimensional sparse vector space built using traditional Bag of Words models. There are two different model architectures which can be leveraged by Word2Vec to create these word embedding representations. These include, The Continuous Bag of Words (CBOW) Model The Skip-gram Model There were originally introduced by Mikolov et al. and I recommend interested readers to read up on the original papers around these models which include, ‘Distributed Representations of Words and Phrases and their Compositionality’ by Mikolov et al. and ‘Efficient Estimation of Word Representations in Vector Space’ by Mikolov et al. to gain some good in-depth perspective. The CBOW model architecture tries to predict the current target word (the center word) based on the source context words (surrounding words). Considering a simple sentence, “the quick brown fox jumps over the lazy dog”, this can be pairs of (context_window, target_word) where if we consider a context window of size 2, we have examples like ([quick, fox], brown), ([the, brown], quick), ([the, dog], lazy) and so on. Thus the model tries to predict the target_word based on the context_window words. While the Word2Vec family of models are unsupervised, what this means is that you can just give it a corpus without additional labels or information and it can construct dense word embeddings from the corpus. But you will still need to leverage a supervised, classification methodology once you have this corpus to get to these embeddings. But we will do that from within the corpus itself, without any auxiliary information. We can model this CBOW architecture now as a deep learning classification model such that we take in the context words as our input, X and try to predict the target word, Y. In fact building this architecture is simpler than the skip-gram model where we try to predict a whole bunch of context words from a source target word. While it’s excellent to use robust frameworks which have the Word2Vec model like gensim, let’s try and implement this from scratch to gain some perspective on how things really work behind the scenes. We will leverage our Bible corpus contained in the norm_bible variable for training our model. The implementation will focus on four parts Build the corpus vocabulary Build a CBOW (context, target) generator Build the CBOW model architecture Train the Model Get Word Embeddings Without further delay, let’s get started! To start off, we will first build our corpus vocabulary where we extract out each unique word from our vocabulary and map a unique numeric identifier to it. Output------Vocabulary Size: 12425Vocabulary Sample: [('perceived', 1460), ('flagon', 7287), ('gardener', 11641), ('named', 973), ('remain', 732), ('sticketh', 10622), ('abstinence', 11848), ('rufus', 8190), ('adversary', 2018), ('jehoiachin', 3189)] Thus you can see that we have created a vocabulary of unique words in our corpus and also ways to map a word to its unique identifier and vice versa. The PAD term is typically used to pad context words to a fixed length if needed. We need pairs which consist of a target centre word and surround context words. In our implementation, a target word is of length 1 and surrounding context is of length 2 x window_size where we take window_size words before and after the target word in our corpus. This will become clearer with the following example. Context (X): ['old','testament','james','bible'] -> Target (Y): kingContext (X): ['first','book','called','genesis'] -> Target(Y): mosesContext(X):['beginning','god','heaven','earth'] -> Target(Y):createdContext (X):['earth','without','void','darkness'] -> Target(Y): formContext (X): ['without','form','darkness','upon'] -> Target(Y): voidContext (X): ['form', 'void', 'upon', 'face'] -> Target(Y): darknessContext (X): ['void', 'darkness', 'face', 'deep'] -> Target(Y): uponContext (X): ['spirit', 'god', 'upon', 'face'] -> Target (Y): movedContext (X): ['god', 'moved', 'face', 'waters'] -> Target (Y): uponContext (X): ['god', 'said', 'light', 'light'] -> Target (Y): letContext (X): ['god', 'saw', 'good', 'god'] -> Target (Y): light The preceding output should give you some more perspective of how X forms our context words and we are trying to predict the target center word Y based on this context. For example, if the original text was ‘in the beginning god created heaven and earth’ which after pre-processing and removal of stopwords became ‘beginning god created heaven earth’ and for us, what we are trying to achieve is that. Given [beginning, god, heaven, earth] as the context, what the target center word is, which is ‘created’ in this case. We now leverage keras on top of tensorflow to build our deep learning architecture for the CBOW model. For this our inputs will be our context words which are passed to an embedding layer (initialized with random weights). The word embeddings are propagated to a lambda layer where we average out the word embeddings (hence called CBOW because we don’t really consider the order or sequence in the context words when averaged) and then we pass this averaged context embedding to a dense softmax layer which predicts our target word. We match this with the actual target word, compute the loss by leveraging the categorical_crossentropy loss and perform backpropagation with each epoch to update the embedding layer in the process. Following code shows us our model architecture. In case you still have difficulty in visualizing the above deep learning model, I would recommend you to read through the papers I mentioned earlier. I will try to summarize the core concepts of this model in simple terms. We have input context words of dimensions (2 x window_size), we will pass them to an embedding layer of size (vocab_size x embed_size) which will give us dense word embeddings for each of these context words (1 x embed_size for each word). Next up we use a lambda layer to average out these embeddings and get an average dense embedding (1 x embed_size) which is sent to the dense softmax layer which outputs the most likely target word. We compare this with the actual target word, compute the loss, backpropagate the errors to adjust the weights (in the embedding layer) and repeat this process for all (context, target) pairs for multiple epochs. The following figure tries to explain the same. We are now ready to train this model on our corpus using our data generator to feed in (context, target_word) pairs. Running the model on our complete corpus takes a fair bit of time, so I just ran it for 5 epochs. You can leverage the following code and increase it for more epochs if necessary. Epoch: 1 Loss: 4257900.60084Epoch: 2 Loss: 4256209.59646Epoch: 3 Loss: 4247990.90456Epoch: 4 Loss: 4225663.18927Epoch: 5 Loss: 4104501.48929 Note: Running this model is computationally expensive and works better if trained using a GPU. I trained this on an AWS p2.x instance with a Tesla K80 GPU and it took me close to 1.5 hours for just 5 epochs! Once this model is trained, similar words should have similar weights based off the embedding layer and we can test out the same. To get word embeddings for our entire vocabulary, we can extract out the same from our embedding layer by leveraging the following code. We don’t take the embedding at position 0 since it belongs to the padding (PAD) term which is not really a word of interest. Thus you can clearly see that each word has a dense embedding of size (1x100) as depicted in the preceding output. Let’s try and find out some contextually similar words for specific words of interest based on these embeddings. For this, we build out a pairwise distance matrix amongst all the words in our vocabulary based on the dense embedding vectors and then find out the n-nearest neighbors of each word of interest based on the shortest (euclidean) distance. (12424, 12424){'egypt': ['destroy', 'none', 'whole', 'jacob', 'sea'], 'famine': ['wickedness', 'sore', 'countries', 'cease', 'portion'], 'god': ['therefore', 'heard', 'may', 'behold', 'heaven'], 'gospel': ['church', 'fowls', 'churches', 'preached', 'doctrine'], 'jesus': ['law', 'heard', 'world', 'many', 'dead'], 'john': ['dream', 'bones', 'held', 'present', 'alive'], 'moses': ['pharaoh', 'gate', 'jews', 'departed', 'lifted'], 'noah': ['abram', 'plagues', 'hananiah', 'korah', 'sarah']} You can clearly see that some of these make sense contextually (god, heaven), (gospel, church) and so on and some may not. Training for more epochs usually ends up giving better results. We will now explore the skip-gram architecture which often gives better results as compared to CBOW. The Skip-gram model architecture usually tries to achieve the reverse of what the CBOW model does. It tries to predict the source context words (surrounding words) given a target word (the center word). Considering our simple sentence from earlier, “the quick brown fox jumps over the lazy dog”. If we used the CBOW model, we get pairs of (context_window, target_word) where if we consider a context window of size 2, we have examples like ([quick, fox], brown), ([the, brown], quick), ([the, dog], lazy) and so on. Now considering that the skip-gram model’s aim is to predict the context from the target word, the model typically inverts the contexts and targets, and tries to predict each context word from its target word. Hence the task becomes to predict the context [quick, fox] given target word ‘brown’ or [the, brown] given target word ‘quick’ and so on. Thus the model tries to predict the context_window words based on the target_word. Just like we discussed in the CBOW model, we need to model this Skip-gram architecture now as a deep learning classification model such that we take in the target word as our input and try to predict the context words.This becomes slightly complex since we have multiple words in our context. We simplify this further by breaking down each (target, context_words) pair into (target, context) pairs such that each context consists of only one word. Hence our dataset from earlier gets transformed into pairs like (brown, quick), (brown, fox), (quick, the), (quick, brown) and so on. But how to supervise or train the model to know what is contextual and what is not? For this, we feed our skip-gram model pairs of (X, Y) where X is our input and Y is our label. We do this by using [(target, context), 1] pairs as positive input samples where target is our word of interest and context is a context word occurring near the target word and the positive label 1 indicates this is a contextually relevant pair. We also feed in [(target, random), 0] pairs as negative input samples where target is again our word of interest but random is just a randomly selected word from our vocabulary which has no context or association with our target word. Hence the negative label 0 indicates this is a contextually irrelevant pair. We do this so that the model can then learn which pairs of words are contextually relevant and which are not and generate similar embeddings for semantically similar words. Let’s now try and implement this model from scratch to gain some perspective on how things work behind the scenes and also so that we can compare it with our implementation of the CBOW model. We will leverage our Bible corpus as usual which is contained in the norm_bible variable for training our model. The implementation will focus on five parts Build the corpus vocabulary Build a skip-gram [(target, context), relevancy] generator Build the skip-gram model architecture Train the Model Get Word Embeddings Let’s get cracking and build our skip-gram Word2Vec model! To start off, we will follow the standard process of building our corpus vocabulary where we extract out each unique word from our vocabulary and assign a unique identifier, similar to what we did in the CBOW model. We also maintain mappings to transform words to their unique identifiers and vice-versa. Vocabulary Size: 12425Vocabulary Sample: [('perceived', 1460), ('flagon', 7287), ('gardener', 11641), ('named', 973), ('remain', 732), ('sticketh', 10622), ('abstinence', 11848), ('rufus', 8190), ('adversary', 2018), ('jehoiachin', 3189)] Just like we wanted, each unique word from the corpus is a part of our vocabulary now with a unique numeric identifier. It’s now time to build out our skip-gram generator which will give us pair of words and their relevance like we discussed earlier. Luckily, keras has a nifty skipgrams utility which can be used and we don’t have to manually implement this generator like we did in CBOW. Note: The function skipgrams(...) is present in keras.preprocessing.sequence This function transforms a sequence of word indexes (list of integers) into tuples of words of the form: - (word, word in the same window), with label 1 (positive samples). - (word, random word from the vocabulary), with label 0 (negative samples). (james (1154), king (13)) -> 1(king (13), james (1154)) -> 1(james (1154), perform (1249)) -> 0(bible (5766), dismissed (6274)) -> 0(king (13), alter (5275)) -> 0(james (1154), bible (5766)) -> 1(king (13), bible (5766)) -> 1(bible (5766), king (13)) -> 1(king (13), compassion (1279)) -> 0(james (1154), foreskins (4844)) -> 0 Thus you can see we have successfully generated our required skip-grams and based on the sample skip-grams in the preceding output, you can clearly see what is relevant and what is irrelevant based on the label (0 or 1). We now leverage keras on top of tensorflow to build our deep learning architecture for the skip-gram model. For this our inputs will be our target word and context or random word pair. Each of which are passed to an embedding layer (initialized with random weights) of it’s own. Once we obtain the word embeddings for the target and the context word, we pass it to a merge layer where we compute the dot product of these two vectors. Then we pass on this dot product value to a dense sigmoid layer which predicts either a 1 or a 0 depending on if the pair of words are contextually relevant or just random words (Y’). We match this with the actual relevance label (Y), compute the loss by leveraging the mean_squared_error loss and perform backpropagation with each epoch to update the embedding layer in the process. Following code shows us our model architecture. Understanding the above deep learning model is pretty straightforward. However, I will try to summarize the core concepts of this model in simple terms for ease of understanding. We have a pair of input words for each training example consisting of one input target word having a unique numeric identifier and one context word having a unique numeric identifier. If it is a positive sample the word has contextual meaning, is a context word and our label Y=1, else if it is a negative sample, the word has no contextual meaning, is just a random word and our label Y=0. We will pass each of them to an embedding layer of their own, having size (vocab_size x embed_size) which will give us dense word embeddings for each of these two words (1 x embed_size for each word). Next up we use a merge layer to compute the dot product of these two embeddings and get the dot product value. This is then sent to the dense sigmoid layer which outputs either a 1 or 0. We compare this with the actual label Y (1 or 0), compute the loss, backpropagate the errors to adjust the weights (in the embedding layer) and repeat this process for all (target, context) pairs for multiple epochs. The following figure tries to explain the same. Let’s now start training our model with our skip-grams. Running the model on our complete corpus takes a fair bit of time but lesser than the CBOW model. Hence I just ran it for 5 epochs. You can leverage the following code and increase it for more epochs if necessary. Epoch: 1 Loss: 4529.63803683Epoch: 2 Loss: 3750.71884749Epoch: 3 Loss: 3752.47489296Epoch: 4 Loss: 3793.9177565Epoch: 5 Loss: 3716.07605051 Once this model is trained, similar words should have similar weights based off the embedding layer and we can test out the same. To get word embeddings for our entire vocabulary, we can extract out the same from our embedding layer by leveraging the following code. Do note that we are only interested in the target word embedding layer, hence we will extract the embeddings from our word_model embedding layer. We don’t take the embedding at position 0 since none of our words in the vocabulary have a numeric identifier of 0 and we ignore it. Thus you can clearly see that each word has a dense embedding of size (1x100) as depicted in the preceding output similar to what we had obtained from the CBOW model. Let’s now apply the euclidean distance metric on these dense embedding vectors to generate a pairwise distance metric for each word in our vocabulary. We can then find out the n-nearest neighbors of each word of interest based on the shortest (euclidean) distance similar to what we did on the embeddings from our CBOW model. (12424, 12424){'egypt': ['pharaoh', 'mighty', 'houses', 'kept', 'possess'], 'famine': ['rivers', 'foot', 'pestilence', 'wash', 'sabbaths'], 'god': ['evil', 'iniquity', 'none', 'mighty', 'mercy'], 'gospel': ['grace', 'shame', 'believed', 'verily', 'everlasting'], 'jesus': ['christ', 'faith', 'disciples', 'dead', 'say'], 'john': ['ghost', 'knew', 'peter', 'alone', 'master'], 'moses': ['commanded', 'offerings', 'kept', 'presence', 'lamb'], 'noah': ['flood', 'shem', 'peleg', 'abram', 'chose']} You can clearly see from the results that a lot of the similar words for each of the words of interest are making sense and we have obtained better results as compared to our CBOW model. Let’s visualize these words embeddings now using t-SNE which stands for t-distributed stochastic neighbor embedding a popular dimensionality reduction technique to visualize higher dimension spaces in lower dimensions (e.g. 2-D). I have marked some circles in red which seemed to show different words of contextual similarity positioned near each other in the vector space. If you find any other interesting patterns feel free to let me know! While our implementations are decent enough, they are not optimized enough to work well on large corpora. The gensim framework, created by Radim Řehůřek consists of a robust, efficient and scalable implementation of the Word2Vec model. We will leverage the same on our Bible corpus. In our workflow, we will tokenize our normalized corpus and then focus on the following four parameters in the Word2Vec model to build it. size: The word embedding dimensionality window: The context window size min_count: The minimum word count sample: The downsample setting for frequent words After building our model, we will use our words of interest to see the top similar words for each of them. The similar words here definitely are more related to our words of interest and this is expected given that we ran this model for more number of iterations which must have yield better and more contextual embeddings. Do you notice any interesting associations? Let’s also visualize the words of interest and their similar words using their embedding vectors after reducing their dimensions to a 2-D space with t-SNE. The red circles have been drawn by me to point out some interesting associations which I found out. We can clearly see based on what I depicted earlier that noah and his sons are quite close to each other based on the word embeddings from our model! If you remember reading the previous article Part-3: Traditional Methods for Text Data you might have seen me using features for some actual machine learning tasks like clustering. Let’s leverage our other top corpus and try to achieve the same. To start with, we will build a simple Word2Vec model on the corpus and visualize the embeddings. Remember that our corpus is extremely small so to get meaninful word embeddings and for the model to get more context and semantics, more data helps. Now what is a word embedding in this scenario? It’s typically a dense vector for each word as depicted in the following example for the word sky. w2v_model.wv['sky']Output------array([ 0.04576328, 0.02328374, -0.04483001, 0.0086611 , 0.05173225, 0.00953358, -0.04087641, -0.00427487, -0.0456274 , 0.02155695], dtype=float32) Now suppose we wanted to cluster the eight documents from our toy corpus, we would need to get the document level embeddings from each of the words present in each document. One strategy would be to average out the word embeddings for each word in a document. This is an extremely useful strategy and you can adopt the same for your own problems. Let’s apply this now on our corpus to get features for each document. Now that we have our features for each document, let’s cluster these documents using the Affinity Propagation algorithm, which is a clustering algorithm based on the concept of “message passing” between data points and does not need the number of clusters as an explicit input which is often required by partition-based clustering algorithms. We can see that our algorithm has clustered each document into the right group based on our Word2Vec features. Pretty neat! We can also visualize how each document in positioned in each cluster by using Principal Component Analysis (PCA) to reduce the feature dimensions to 2-D and then visualizing the same (by color coding each cluster). Everything looks to be in order as documents in each cluster are closer to each other and far apart from other clusters. The GloVe model stands for Global Vectors which is an unsupervised learning model which can be used to obtain dense word vectors similar to Word2Vec. However the technique is different and training is performed on an aggregated global word-word co-occurrence matrix, giving us a vector space with meaningful sub-structures. This method was invented in Stanford by Pennington et al. and I recommend you to read the original paper on GloVe, ‘GloVe: Global Vectors for Word Representation’ by Pennington et al. which is an excellent read to get some perspective on how this model works. We won’t cover the implementation of the model from scratch in too much detail here but if you are interested in the actual code, you can check out the official GloVe page. We will keep things simple here and try to understand the basic concepts behind the GloVe model. We have talked about count based matrix factorization methods like LSA and predictive methods like Word2Vec. The paper claims that currently, both families suffer significant drawbacks. Methods like LSA efficiently leverage statistical information but they do relatively poorly on the word analogy task like how we found out semantically similar words. Methods like skip-gram may do better on the analogy task, but they poorly utilize the statistics of the corpus on a global level. The basic methodology of the GloVe model is to first create a huge word-context co-occurence matrix consisting of (word, context) pairs such that each element in this matrix represents how often a word occurs with the context (which can be a sequence of words). The idea then is to apply matrix factorization to approximate this matrix as depicted in the following figure. Considering the Word-Context (WC) matrix, Word-Feature (WF) matrix and Feature-Context (FC) matrix, we try to factorize WC = WF x FC, such that we we aim to reconstruct WC from WF and FC by multiplying them. For this, we typically initialize WF and FC with some random weights and attempt to multiply them to get WC’ (an approximation of WC) and measure how close it is to WC. We do this multiple times using Stochastic Gradient Descent (SGD) to minimize the error. Finally, the Word-Feature matrix (WF) gives us the word embeddings for each word where F can be preset to a specific number of dimensions. A very important point to remember is that both Word2Vec and GloVe models are very similar in how they work. Both of them aim to build a vector space where the position of each word is influenced by its neighboring words based on their context and semantics. Word2Vec starts with local individual examples of word co-occurrence pairs and GloVe starts with global aggregated co-occurrence statistics across all words in the corpus. Let’s try and leverage GloVe based embeddings for our document clustering task. The very popular spacy framework comes with capabilities to leverage GloVe embeddings based on different language models. You can also get pre-trained word vectors and load them up as needed using gensim or spacy. We will first install spacy and use the en_vectors_web_lg model which consists of 300-dimensional word vectors trained on Common Crawl with GloVe. # Use the following command to install spaCy> pip install -U spacyOR> conda install -c conda-forge spacy# Download the following language model and store it in diskhttps://github.com/explosion/spacy-models/releases/tag/en_vectors_web_lg-2.0.0# Link the same to spacy > python -m spacy link ./spacymodels/en_vectors_web_lg-2.0.0/en_vectors_web_lg en_vecsLinking successful ./spacymodels/en_vectors_web_lg-2.0.0/en_vectors_web_lg --> ./Anaconda3/lib/site-packages/spacy/data/en_vecsYou can now load the model via spacy.load('en_vecs') There are automated ways to install models in spacy too, you can check their Models & Languages page for more information if needed. I had some issues with the same so I had to manually load them up. We will now load up our language model using spacy. Total word vectors: 1070971 This validates that everything is working and in order. Let’s get the GloVe embeddings for each of our words now in our toy corpus. We can now use t-SNE to visualize these embeddings similar to what we did using our Word2Vec embeddings. The beauty of spacy is that it will automatically provide you the averaged embeddings for words in each document without having to implement a function like we did in Word2Vec. We will leverage the same to get document features for our corpus and use k-means clustering to cluster our documents. We see consistent clusters similar to what we obtained from our Word2Vec model which is good! The GloVe model claims to perform better than the Word2Vec model in many scenarios as illustrated in the following graph from the original paper by Pennington el al. The above experiments were done by training 300-dimensional vectors on the same 6B token corpus (Wikipedia 2014 + Gigaword 5) with the same 400,000 word vocabulary and a symmetric context window of size 10 in case anyone is interested in the details. The FastText model was first introduced by Facebook in 2016 as an extension and supposedly improvement of the vanilla Word2Vec model. Based on the original paper titled ‘Enriching Word Vectors with Subword Information’ by Mikolov et al. which is an excellent read to gain an in-depth understanding of how this model works. Overall, FastText is a framework for learning word representations and also performing robust, fast and accurate text classification. The framework is open-sourced by Facebook on GitHub and claims to have the following. Recent state-of-the-art English word vectors. Word vectors for 157 languages trained on Wikipedia and Crawl. Models for language identification and various supervised tasks. Though I haven’t implemented this model from scratch, based on the research paper, following is what I learnt about how the model works. In general, predictive models like the Word2Vec model typically considers each word as a distinct entity (e.g. where) and generates a dense embedding for the word. However this poses to be a serious limitation with languages having massive vocabularies and many rare words which may not occur a lot in different corpora. The Word2Vec model typically ignores the morphological structure of each word and considers a word as a single entity. The FastText model considers each word as a Bag of Character n-grams. This is also called as a subword model in the paper. We add special boundary symbols < and > at the beginning and end of words. This enables us to distinguish prefixes and suffixes from other character sequences. We also include the word w itself in the set of its n-grams, to learn a representation for each word (in addition to its character n-grams). Taking the word where and n=3 (tri-grams) as an example, it will be represented by the character n-grams: <wh, whe, her, ere, re> and the special sequence <where> representing the whole word. Note that the sequence , corresponding to the word <her> is different from the tri-gram her from the word where. In practice, the paper recommends in extracting all the n-grams for n ≥ 3 and n ≤ 6. This is a very simple approach, and different sets of n-grams could be considered, for example taking all prefixes and suffixes. We typically associate a vector representation (embedding) to each n-gram for a word. Thus, we can represent a word by the sum of the vector representations of its n-grams or the average of the embedding of these n-grams. Thus, due to this effect of leveraging n-grams from individual words based on their characters, there is a higher chance for rare words to get a good representation since their character based n-grams should occur across other words of the corpus. The gensim package has nice wrappers providing us interfaces to leverage the FastText model available under the gensim.models.fasttext module. Let’s apply this once again on our Bible corpus and look at our words of interest and their most similar words. You can see a lot of similarity in the results with our Word2Vec model with relevant similar words for each of our words of interest. Do you notice any interesting associations and similarities? Note: Running this model is computationally expensive and usually takes more time as compared to the skip-gram model since it considers n-grams for each word. This works better if trained using a GPU or a good CPU. I trained this on an AWS p2.x instance and it took me around 10 minutes as compared to over 2–3 hours on a regular system. Let’s now use Principal Component Analysis (PCA) to reduce the word embedding dimensions to 2-D and then visualize the same. We can see a lot of interesting patterns! Noah, his son Shem and grandfather Methuselah are close to each other. We also see God associated with Moses and Egypt where it endured the Biblical plagues including famine and pestilence. Also Jesus and some of his disciples are associated close to each other. To access any of the word embeddings you can just index the model with the word as follows. ft_model.wv['jesus']array([-0.23493268, 0.14237943, 0.35635167, 0.34680951, 0.09342121,..., -0.15021783, -0.08518736, -0.28278247, -0.19060139], dtype=float32) Having these embeddings, we can perform some interesting natural language tasks. One of these would be to find out similarity between different words (entities). print(ft_model.wv.similarity(w1='god', w2='satan'))print(ft_model.wv.similarity(w1='god', w2='jesus'))Output------0.3332608766850.698824900473 We can see that ‘god’ is more closely associated with ‘jesus’ rather than ‘satan’ based on the text in our Bible corpus. Quite relevant! Considering word embeddings being present, we can even find out odd words from a bunch of words as follows. st1 = "god jesus satan john"print('Odd one out for [',st1, ']:', ft_model.wv.doesnt_match(st1.split()))st2 = "john peter james judas"print('Odd one out for [',st2, ']:', ft_model.wv.doesnt_match(st2.split()))Output------Odd one out for [ god jesus satan john ]: satanOdd one out for [ john peter james judas ]: judas Interesting and relevant results in both cases for the odd entity amongst the other words! These examples should give you a good idea about newer and efficient strategies around leveraging deep learning language models to extract features from text data and also address problems like word semantics, context and data sparsity. Next up will be detailed strategies on leveraging deep learning models for feature engineering on image data. Stay tuned! To read about feature engineering strategies for continuous numeric data, check out Part 1 of this series! To read about feature engineering strategies for discrete categoricial data, check out Part 2 of this series! To read about traditional feature engineering strategies for unstructured text data, check out Part 3 of this series! All the code and datasets used in this article can be accessed from my GitHub The code is also available as a Jupyter notebook Architecture diagrams unless explicitly cited are my copyright. Feel free to use them, but please do remember to cite the source if you want to use them in your own work. If you have any feedback, comments or interesting insights to share about my article or data science in general, feel free to reach out to me on my LinkedIn social media channel.
[ { "code": null, "e": 1251, "s": 47, "text": "Working with unstructured text data is hard especially when you are trying to build an intelligent system which interprets and understands free flowing natural language just like humans. You need to be able to process and transform noisy, unstructured textual data into some structured, vectorized formats which can be understood by any machine learning algorithm. Principles from Natural Language Processing, Machine Learning or Deep Learning all of which fall under the broad umbrella of Artificial Intelligence are effective tools of the trade. Based on my previous posts, an important point to remember here is that any machine learning algorithm is based on principles of statistics, math and optimization. Hence they are not intelligent enough to start processing text in their raw, native form. We covered some traditional strategies for extracting meaningful features from text data in Part-3: Traditional Methods for Text Data. I encourage you to check out the same for a brief refresher. In this article, we will be looking at more advanced feature engineering strategies which often leverage deep learning models. More specifically we will be covering the Word2Vec, GloVe and FastText models." }, { "code": null, "e": 1738, "s": 1251, "text": "We have discussed time and again including in our previous article that Feature Engineering is the secret sauce to creating superior and better performing machine learning models. Always remember that even with the advent of automated feature engineering capabilities, you would still need to understand the core concepts behind applying the techniques. Otherwise they would just be black box models which you wouldn’t know how to tweak and tune for the problem you are trying to solve." }, { "code": null, "e": 2484, "s": 1738, "text": "Traditional (count-based) feature engineering strategies for textual data involve models belonging to a family of models popularly known as the Bag of Words model. This includes term frequencies, TF-IDF (term frequency-inverse document frequency), N-grams and so on. While they are effective methods for extracting features from text, due to the inherent nature of the model being just a bag of unstructured words, we lose additional information like the semantics, structure, sequence and context around nearby words in each text document. This forms as enough motivation for us to explore more sophisticated models which can capture this information and give us features which are vector representation of words, popularly known as embeddings." }, { "code": null, "e": 3235, "s": 2484, "text": "While this does make some sense, why should we be motivated enough to learn and build these word embeddings? With regard to speech or image recognition systems, all the information is already present in the form of rich dense feature vectors embedded in high-dimensional datasets like audio spectrograms and image pixel intensities. However when it comes to raw text data, especially count based models like Bag of Words, we are dealing with individual words which may have their own identifiers and do not capture the semantic relationship amongst words. This leads to huge sparse word vectors for textual data and thus if we do not have enough data, we may end up getting poor models or even overfitting the data due to the curse of dimensionality." }, { "code": null, "e": 4691, "s": 3235, "text": "To overcome the shortcomings of losing out semantics and feature sparsity in bag of words model based features, we need to make use of Vector Space Models (VSMs) in such a way that we can embed word vectors in this continuous vector space based on semantic and contextual similarity. In fact the distributional hypothesis in the field of distributional semantics tells us that words which occur and are used in the same context, are semantically similar to one another and have similar meanings. In simple terms, ‘a word is characterized by the company it keeps’. One of the famous papers talking about these semantic word vectors and various types in detail is ‘Don’t count, predict! A systematic comparison of context-counting vs. context-predicting semantic vectors’ by Baroni et al. We won’t go into extensive depth but in short, there are two main types of methods for contextual word vectors. Count-based methods like Latent Semantic Analysis (LSA) which can be used to compute some statistical measures of how often words occur with their neighboring words in a corpus and then building out dense word vectors for each word from these measures. Predictive methods like Neural Network based language models try to predict words from its neighboring words looking at word sequences in the corpus and in the process it learns distributed representations giving us dense word embeddings. We will be focusing on these predictive methods in this article." }, { "code": null, "e": 5047, "s": 4691, "text": "Let’s look at some of these advanced strategies for handling text data and extracting meaningful features from the same, which can be used in downstream machine learning systems. Do note that you can access all the code used in this article in my GitHub repository also for future reference. We’ll start by loading up some basic dependencies and settings." }, { "code": null, "e": 5191, "s": 5047, "text": "import pandas as pdimport numpy as npimport reimport nltkimport matplotlib.pyplot as pltpd.options.display.max_colwidth = 200%matplotlib inline" }, { "code": null, "e": 5455, "s": 5191, "text": "We will now take a few corpora of documents on which we will perform all our analyses. For one of the corpora, we will reuse our corpus from our previous article, Part-3: Traditional Methods for Text Data. We mention the code as follows for ease of understanding." }, { "code": null, "e": 5827, "s": 5455, "text": "Our toy corpus consists of documents belonging to several categories. Another corpus we will use in this article is the The King James Version of the Bible available freely from Project Gutenberg through the corpus module in nltk. We will load this up shortly, in the next section. Before we talk about feature engineering, we need to pre-process and normalize this text." }, { "code": null, "e": 6347, "s": 5827, "text": "There can be multiple ways of cleaning and pre-processing textual data. The most important techniques which are used heavily in Natural Language Processing (NLP) pipelines have been highlighted in detail in the ‘Text pre-processing’ section in Part 3 of this series. Since the focus of this article is on feature engineering, just like our previous article, we will re-use our simple text pre-processor which focuses on removing special characters, extra whitespaces, digits, stopwords and lower casing the text corpus." }, { "code": null, "e": 6447, "s": 6347, "text": "Once we have our basic pre-processing pipeline ready, let’s first apply the same to our toy corpus." }, { "code": null, "e": 6841, "s": 6447, "text": "norm_corpus = normalize_corpus(corpus)norm_corpusOutput------array(['sky blue beautiful', 'love blue beautiful sky', 'quick brown fox jumps lazy dog', 'kings breakfast sausages ham bacon eggs toast beans', 'love green eggs ham sausages bacon', 'brown fox quick blue dog lazy', 'sky blue sky beautiful today', 'dog lazy brown fox quick'], dtype='<U51')" }, { "code": null, "e": 6958, "s": 6841, "text": "Let’s now load up our other corpus based on The King James Version of the Bible using nltk and pre-process the text." }, { "code": null, "e": 7082, "s": 6958, "text": "The following output shows the total number of lines in our corpus and how the pre-processing works on the textual content." }, { "code": null, "e": 7411, "s": 7082, "text": "Output------Total lines: 30103Sample line: ['1', ':', '6', 'And', 'God', 'said', ',', 'Let', 'there', 'be', 'a', 'firmament', 'in', 'the', 'midst', 'of', 'the', 'waters', ',', 'and', 'let', 'it', 'divide', 'the', 'waters', 'from', 'the', 'waters', '.']Processed line: god said let firmament midst waters let divide waters waters" }, { "code": null, "e": 7514, "s": 7411, "text": "Let’s look at some of the popular word embedding models now and engineering features from our corpora!" }, { "code": null, "e": 8275, "s": 7514, "text": "This model was created by Google in 2013 and is a predictive deep learning based model to compute and generate high quality, distributed and continuous dense vector representations of words, which capture contextual and semantic similarity. Essentially these are unsupervised models which can take in massive textual corpora, create a vocabulary of possible words and generate dense word embeddings for each word in the vector space representing that vocabulary. Usually you can specify the size of the word embedding vectors and the total number of vectors are essentially the size of the vocabulary. This makes the dimensionality of this dense vector space much lower than the high-dimensional sparse vector space built using traditional Bag of Words models." }, { "code": null, "e": 8417, "s": 8275, "text": "There are two different model architectures which can be leveraged by Word2Vec to create these word embedding representations. These include," }, { "code": null, "e": 8458, "s": 8417, "text": "The Continuous Bag of Words (CBOW) Model" }, { "code": null, "e": 8478, "s": 8458, "text": "The Skip-gram Model" }, { "code": null, "e": 8854, "s": 8478, "text": "There were originally introduced by Mikolov et al. and I recommend interested readers to read up on the original papers around these models which include, ‘Distributed Representations of Words and Phrases and their Compositionality’ by Mikolov et al. and ‘Efficient Estimation of Word Representations in Vector Space’ by Mikolov et al. to gain some good in-depth perspective." }, { "code": null, "e": 9355, "s": 8854, "text": "The CBOW model architecture tries to predict the current target word (the center word) based on the source context words (surrounding words). Considering a simple sentence, “the quick brown fox jumps over the lazy dog”, this can be pairs of (context_window, target_word) where if we consider a context window of size 2, we have examples like ([quick, fox], brown), ([the, brown], quick), ([the, dog], lazy) and so on. Thus the model tries to predict the target_word based on the context_window words." }, { "code": null, "e": 10108, "s": 9355, "text": "While the Word2Vec family of models are unsupervised, what this means is that you can just give it a corpus without additional labels or information and it can construct dense word embeddings from the corpus. But you will still need to leverage a supervised, classification methodology once you have this corpus to get to these embeddings. But we will do that from within the corpus itself, without any auxiliary information. We can model this CBOW architecture now as a deep learning classification model such that we take in the context words as our input, X and try to predict the target word, Y. In fact building this architecture is simpler than the skip-gram model where we try to predict a whole bunch of context words from a source target word." }, { "code": null, "e": 10448, "s": 10108, "text": "While it’s excellent to use robust frameworks which have the Word2Vec model like gensim, let’s try and implement this from scratch to gain some perspective on how things really work behind the scenes. We will leverage our Bible corpus contained in the norm_bible variable for training our model. The implementation will focus on four parts" }, { "code": null, "e": 10476, "s": 10448, "text": "Build the corpus vocabulary" }, { "code": null, "e": 10517, "s": 10476, "text": "Build a CBOW (context, target) generator" }, { "code": null, "e": 10551, "s": 10517, "text": "Build the CBOW model architecture" }, { "code": null, "e": 10567, "s": 10551, "text": "Train the Model" }, { "code": null, "e": 10587, "s": 10567, "text": "Get Word Embeddings" }, { "code": null, "e": 10629, "s": 10587, "text": "Without further delay, let’s get started!" }, { "code": null, "e": 10786, "s": 10629, "text": "To start off, we will first build our corpus vocabulary where we extract out each unique word from our vocabulary and map a unique numeric identifier to it." }, { "code": null, "e": 11037, "s": 10786, "text": "Output------Vocabulary Size: 12425Vocabulary Sample: [('perceived', 1460), ('flagon', 7287), ('gardener', 11641), ('named', 973), ('remain', 732), ('sticketh', 10622), ('abstinence', 11848), ('rufus', 8190), ('adversary', 2018), ('jehoiachin', 3189)]" }, { "code": null, "e": 11268, "s": 11037, "text": "Thus you can see that we have created a vocabulary of unique words in our corpus and also ways to map a word to its unique identifier and vice versa. The PAD term is typically used to pad context words to a fixed length if needed." }, { "code": null, "e": 11586, "s": 11268, "text": "We need pairs which consist of a target centre word and surround context words. In our implementation, a target word is of length 1 and surrounding context is of length 2 x window_size where we take window_size words before and after the target word in our corpus. This will become clearer with the following example." }, { "code": null, "e": 12325, "s": 11586, "text": "Context (X): ['old','testament','james','bible'] -> Target (Y): kingContext (X): ['first','book','called','genesis'] -> Target(Y): mosesContext(X):['beginning','god','heaven','earth'] -> Target(Y):createdContext (X):['earth','without','void','darkness'] -> Target(Y): formContext (X): ['without','form','darkness','upon'] -> Target(Y): voidContext (X): ['form', 'void', 'upon', 'face'] -> Target(Y): darknessContext (X): ['void', 'darkness', 'face', 'deep'] -> Target(Y): uponContext (X): ['spirit', 'god', 'upon', 'face'] -> Target (Y): movedContext (X): ['god', 'moved', 'face', 'waters'] -> Target (Y): uponContext (X): ['god', 'said', 'light', 'light'] -> Target (Y): letContext (X): ['god', 'saw', 'good', 'god'] -> Target (Y): light" }, { "code": null, "e": 12846, "s": 12325, "text": "The preceding output should give you some more perspective of how X forms our context words and we are trying to predict the target center word Y based on this context. For example, if the original text was ‘in the beginning god created heaven and earth’ which after pre-processing and removal of stopwords became ‘beginning god created heaven earth’ and for us, what we are trying to achieve is that. Given [beginning, god, heaven, earth] as the context, what the target center word is, which is ‘created’ in this case." }, { "code": null, "e": 13625, "s": 12846, "text": "We now leverage keras on top of tensorflow to build our deep learning architecture for the CBOW model. For this our inputs will be our context words which are passed to an embedding layer (initialized with random weights). The word embeddings are propagated to a lambda layer where we average out the word embeddings (hence called CBOW because we don’t really consider the order or sequence in the context words when averaged) and then we pass this averaged context embedding to a dense softmax layer which predicts our target word. We match this with the actual target word, compute the loss by leveraging the categorical_crossentropy loss and perform backpropagation with each epoch to update the embedding layer in the process. Following code shows us our model architecture." }, { "code": null, "e": 14546, "s": 13625, "text": "In case you still have difficulty in visualizing the above deep learning model, I would recommend you to read through the papers I mentioned earlier. I will try to summarize the core concepts of this model in simple terms. We have input context words of dimensions (2 x window_size), we will pass them to an embedding layer of size (vocab_size x embed_size) which will give us dense word embeddings for each of these context words (1 x embed_size for each word). Next up we use a lambda layer to average out these embeddings and get an average dense embedding (1 x embed_size) which is sent to the dense softmax layer which outputs the most likely target word. We compare this with the actual target word, compute the loss, backpropagate the errors to adjust the weights (in the embedding layer) and repeat this process for all (context, target) pairs for multiple epochs. The following figure tries to explain the same." }, { "code": null, "e": 14663, "s": 14546, "text": "We are now ready to train this model on our corpus using our data generator to feed in (context, target_word) pairs." }, { "code": null, "e": 14843, "s": 14663, "text": "Running the model on our complete corpus takes a fair bit of time, so I just ran it for 5 epochs. You can leverage the following code and increase it for more epochs if necessary." }, { "code": null, "e": 14989, "s": 14843, "text": "Epoch: 1 \tLoss: 4257900.60084Epoch: 2 \tLoss: 4256209.59646Epoch: 3 \tLoss: 4247990.90456Epoch: 4 \tLoss: 4225663.18927Epoch: 5 \tLoss: 4104501.48929" }, { "code": null, "e": 15197, "s": 14989, "text": "Note: Running this model is computationally expensive and works better if trained using a GPU. I trained this on an AWS p2.x instance with a Tesla K80 GPU and it took me close to 1.5 hours for just 5 epochs!" }, { "code": null, "e": 15327, "s": 15197, "text": "Once this model is trained, similar words should have similar weights based off the embedding layer and we can test out the same." }, { "code": null, "e": 15589, "s": 15327, "text": "To get word embeddings for our entire vocabulary, we can extract out the same from our embedding layer by leveraging the following code. We don’t take the embedding at position 0 since it belongs to the padding (PAD) term which is not really a word of interest." }, { "code": null, "e": 16055, "s": 15589, "text": "Thus you can clearly see that each word has a dense embedding of size (1x100) as depicted in the preceding output. Let’s try and find out some contextually similar words for specific words of interest based on these embeddings. For this, we build out a pairwise distance matrix amongst all the words in our vocabulary based on the dense embedding vectors and then find out the n-nearest neighbors of each word of interest based on the shortest (euclidean) distance." }, { "code": null, "e": 16545, "s": 16055, "text": "(12424, 12424){'egypt': ['destroy', 'none', 'whole', 'jacob', 'sea'], 'famine': ['wickedness', 'sore', 'countries', 'cease', 'portion'], 'god': ['therefore', 'heard', 'may', 'behold', 'heaven'], 'gospel': ['church', 'fowls', 'churches', 'preached', 'doctrine'], 'jesus': ['law', 'heard', 'world', 'many', 'dead'], 'john': ['dream', 'bones', 'held', 'present', 'alive'], 'moses': ['pharaoh', 'gate', 'jews', 'departed', 'lifted'], 'noah': ['abram', 'plagues', 'hananiah', 'korah', 'sarah']}" }, { "code": null, "e": 16833, "s": 16545, "text": "You can clearly see that some of these make sense contextually (god, heaven), (gospel, church) and so on and some may not. Training for more epochs usually ends up giving better results. We will now explore the skip-gram architecture which often gives better results as compared to CBOW." }, { "code": null, "e": 17780, "s": 16833, "text": "The Skip-gram model architecture usually tries to achieve the reverse of what the CBOW model does. It tries to predict the source context words (surrounding words) given a target word (the center word). Considering our simple sentence from earlier, “the quick brown fox jumps over the lazy dog”. If we used the CBOW model, we get pairs of (context_window, target_word) where if we consider a context window of size 2, we have examples like ([quick, fox], brown), ([the, brown], quick), ([the, dog], lazy) and so on. Now considering that the skip-gram model’s aim is to predict the context from the target word, the model typically inverts the contexts and targets, and tries to predict each context word from its target word. Hence the task becomes to predict the context [quick, fox] given target word ‘brown’ or [the, brown] given target word ‘quick’ and so on. Thus the model tries to predict the context_window words based on the target_word." }, { "code": null, "e": 18446, "s": 17780, "text": "Just like we discussed in the CBOW model, we need to model this Skip-gram architecture now as a deep learning classification model such that we take in the target word as our input and try to predict the context words.This becomes slightly complex since we have multiple words in our context. We simplify this further by breaking down each (target, context_words) pair into (target, context) pairs such that each context consists of only one word. Hence our dataset from earlier gets transformed into pairs like (brown, quick), (brown, fox), (quick, the), (quick, brown) and so on. But how to supervise or train the model to know what is contextual and what is not?" }, { "code": null, "e": 19272, "s": 18446, "text": "For this, we feed our skip-gram model pairs of (X, Y) where X is our input and Y is our label. We do this by using [(target, context), 1] pairs as positive input samples where target is our word of interest and context is a context word occurring near the target word and the positive label 1 indicates this is a contextually relevant pair. We also feed in [(target, random), 0] pairs as negative input samples where target is again our word of interest but random is just a randomly selected word from our vocabulary which has no context or association with our target word. Hence the negative label 0 indicates this is a contextually irrelevant pair. We do this so that the model can then learn which pairs of words are contextually relevant and which are not and generate similar embeddings for semantically similar words." }, { "code": null, "e": 19621, "s": 19272, "text": "Let’s now try and implement this model from scratch to gain some perspective on how things work behind the scenes and also so that we can compare it with our implementation of the CBOW model. We will leverage our Bible corpus as usual which is contained in the norm_bible variable for training our model. The implementation will focus on five parts" }, { "code": null, "e": 19649, "s": 19621, "text": "Build the corpus vocabulary" }, { "code": null, "e": 19708, "s": 19649, "text": "Build a skip-gram [(target, context), relevancy] generator" }, { "code": null, "e": 19747, "s": 19708, "text": "Build the skip-gram model architecture" }, { "code": null, "e": 19763, "s": 19747, "text": "Train the Model" }, { "code": null, "e": 19783, "s": 19763, "text": "Get Word Embeddings" }, { "code": null, "e": 19842, "s": 19783, "text": "Let’s get cracking and build our skip-gram Word2Vec model!" }, { "code": null, "e": 20147, "s": 19842, "text": "To start off, we will follow the standard process of building our corpus vocabulary where we extract out each unique word from our vocabulary and assign a unique identifier, similar to what we did in the CBOW model. We also maintain mappings to transform words to their unique identifiers and vice-versa." }, { "code": null, "e": 20386, "s": 20147, "text": "Vocabulary Size: 12425Vocabulary Sample: [('perceived', 1460), ('flagon', 7287), ('gardener', 11641), ('named', 973), ('remain', 732), ('sticketh', 10622), ('abstinence', 11848), ('rufus', 8190), ('adversary', 2018), ('jehoiachin', 3189)]" }, { "code": null, "e": 20506, "s": 20386, "text": "Just like we wanted, each unique word from the corpus is a part of our vocabulary now with a unique numeric identifier." }, { "code": null, "e": 20776, "s": 20506, "text": "It’s now time to build out our skip-gram generator which will give us pair of words and their relevance like we discussed earlier. Luckily, keras has a nifty skipgrams utility which can be used and we don’t have to manually implement this generator like we did in CBOW." }, { "code": null, "e": 20853, "s": 20776, "text": "Note: The function skipgrams(...) is present in keras.preprocessing.sequence" }, { "code": null, "e": 20958, "s": 20853, "text": "This function transforms a sequence of word indexes (list of integers) into tuples of words of the form:" }, { "code": null, "e": 21026, "s": 20958, "text": "- (word, word in the same window), with label 1 (positive samples)." }, { "code": null, "e": 21102, "s": 21026, "text": "- (word, random word from the vocabulary), with label 0 (negative samples)." }, { "code": null, "e": 21430, "s": 21102, "text": "(james (1154), king (13)) -> 1(king (13), james (1154)) -> 1(james (1154), perform (1249)) -> 0(bible (5766), dismissed (6274)) -> 0(king (13), alter (5275)) -> 0(james (1154), bible (5766)) -> 1(king (13), bible (5766)) -> 1(bible (5766), king (13)) -> 1(king (13), compassion (1279)) -> 0(james (1154), foreskins (4844)) -> 0" }, { "code": null, "e": 21651, "s": 21430, "text": "Thus you can see we have successfully generated our required skip-grams and based on the sample skip-grams in the preceding output, you can clearly see what is relevant and what is irrelevant based on the label (0 or 1)." }, { "code": null, "e": 22517, "s": 21651, "text": "We now leverage keras on top of tensorflow to build our deep learning architecture for the skip-gram model. For this our inputs will be our target word and context or random word pair. Each of which are passed to an embedding layer (initialized with random weights) of it’s own. Once we obtain the word embeddings for the target and the context word, we pass it to a merge layer where we compute the dot product of these two vectors. Then we pass on this dot product value to a dense sigmoid layer which predicts either a 1 or a 0 depending on if the pair of words are contextually relevant or just random words (Y’). We match this with the actual relevance label (Y), compute the loss by leveraging the mean_squared_error loss and perform backpropagation with each epoch to update the embedding layer in the process. Following code shows us our model architecture." }, { "code": null, "e": 23740, "s": 22517, "text": "Understanding the above deep learning model is pretty straightforward. However, I will try to summarize the core concepts of this model in simple terms for ease of understanding. We have a pair of input words for each training example consisting of one input target word having a unique numeric identifier and one context word having a unique numeric identifier. If it is a positive sample the word has contextual meaning, is a context word and our label Y=1, else if it is a negative sample, the word has no contextual meaning, is just a random word and our label Y=0. We will pass each of them to an embedding layer of their own, having size (vocab_size x embed_size) which will give us dense word embeddings for each of these two words (1 x embed_size for each word). Next up we use a merge layer to compute the dot product of these two embeddings and get the dot product value. This is then sent to the dense sigmoid layer which outputs either a 1 or 0. We compare this with the actual label Y (1 or 0), compute the loss, backpropagate the errors to adjust the weights (in the embedding layer) and repeat this process for all (target, context) pairs for multiple epochs. The following figure tries to explain the same." }, { "code": null, "e": 23796, "s": 23740, "text": "Let’s now start training our model with our skip-grams." }, { "code": null, "e": 24010, "s": 23796, "text": "Running the model on our complete corpus takes a fair bit of time but lesser than the CBOW model. Hence I just ran it for 5 epochs. You can leverage the following code and increase it for more epochs if necessary." }, { "code": null, "e": 24150, "s": 24010, "text": "Epoch: 1 Loss: 4529.63803683Epoch: 2 Loss: 3750.71884749Epoch: 3 Loss: 3752.47489296Epoch: 4 Loss: 3793.9177565Epoch: 5 Loss: 3716.07605051" }, { "code": null, "e": 24280, "s": 24150, "text": "Once this model is trained, similar words should have similar weights based off the embedding layer and we can test out the same." }, { "code": null, "e": 24696, "s": 24280, "text": "To get word embeddings for our entire vocabulary, we can extract out the same from our embedding layer by leveraging the following code. Do note that we are only interested in the target word embedding layer, hence we will extract the embeddings from our word_model embedding layer. We don’t take the embedding at position 0 since none of our words in the vocabulary have a numeric identifier of 0 and we ignore it." }, { "code": null, "e": 25189, "s": 24696, "text": "Thus you can clearly see that each word has a dense embedding of size (1x100) as depicted in the preceding output similar to what we had obtained from the CBOW model. Let’s now apply the euclidean distance metric on these dense embedding vectors to generate a pairwise distance metric for each word in our vocabulary. We can then find out the n-nearest neighbors of each word of interest based on the shortest (euclidean) distance similar to what we did on the embeddings from our CBOW model." }, { "code": null, "e": 25684, "s": 25189, "text": "(12424, 12424){'egypt': ['pharaoh', 'mighty', 'houses', 'kept', 'possess'], 'famine': ['rivers', 'foot', 'pestilence', 'wash', 'sabbaths'], 'god': ['evil', 'iniquity', 'none', 'mighty', 'mercy'], 'gospel': ['grace', 'shame', 'believed', 'verily', 'everlasting'], 'jesus': ['christ', 'faith', 'disciples', 'dead', 'say'], 'john': ['ghost', 'knew', 'peter', 'alone', 'master'], 'moses': ['commanded', 'offerings', 'kept', 'presence', 'lamb'], 'noah': ['flood', 'shem', 'peleg', 'abram', 'chose']}" }, { "code": null, "e": 26101, "s": 25684, "text": "You can clearly see from the results that a lot of the similar words for each of the words of interest are making sense and we have obtained better results as compared to our CBOW model. Let’s visualize these words embeddings now using t-SNE which stands for t-distributed stochastic neighbor embedding a popular dimensionality reduction technique to visualize higher dimension spaces in lower dimensions (e.g. 2-D)." }, { "code": null, "e": 26314, "s": 26101, "text": "I have marked some circles in red which seemed to show different words of contextual similarity positioned near each other in the vector space. If you find any other interesting patterns feel free to let me know!" }, { "code": null, "e": 26739, "s": 26314, "text": "While our implementations are decent enough, they are not optimized enough to work well on large corpora. The gensim framework, created by Radim Řehůřek consists of a robust, efficient and scalable implementation of the Word2Vec model. We will leverage the same on our Bible corpus. In our workflow, we will tokenize our normalized corpus and then focus on the following four parameters in the Word2Vec model to build it." }, { "code": null, "e": 26779, "s": 26739, "text": "size: The word embedding dimensionality" }, { "code": null, "e": 26811, "s": 26779, "text": "window: The context window size" }, { "code": null, "e": 26845, "s": 26811, "text": "min_count: The minimum word count" }, { "code": null, "e": 26895, "s": 26845, "text": "sample: The downsample setting for frequent words" }, { "code": null, "e": 27002, "s": 26895, "text": "After building our model, we will use our words of interest to see the top similar words for each of them." }, { "code": null, "e": 27263, "s": 27002, "text": "The similar words here definitely are more related to our words of interest and this is expected given that we ran this model for more number of iterations which must have yield better and more contextual embeddings. Do you notice any interesting associations?" }, { "code": null, "e": 27419, "s": 27263, "text": "Let’s also visualize the words of interest and their similar words using their embedding vectors after reducing their dimensions to a 2-D space with t-SNE." }, { "code": null, "e": 27669, "s": 27419, "text": "The red circles have been drawn by me to point out some interesting associations which I found out. We can clearly see based on what I depicted earlier that noah and his sons are quite close to each other based on the word embeddings from our model!" }, { "code": null, "e": 28012, "s": 27669, "text": "If you remember reading the previous article Part-3: Traditional Methods for Text Data you might have seen me using features for some actual machine learning tasks like clustering. Let’s leverage our other top corpus and try to achieve the same. To start with, we will build a simple Word2Vec model on the corpus and visualize the embeddings." }, { "code": null, "e": 28308, "s": 28012, "text": "Remember that our corpus is extremely small so to get meaninful word embeddings and for the model to get more context and semantics, more data helps. Now what is a word embedding in this scenario? It’s typically a dense vector for each word as depicted in the following example for the word sky." }, { "code": null, "e": 28491, "s": 28308, "text": "w2v_model.wv['sky']Output------array([ 0.04576328, 0.02328374, -0.04483001, 0.0086611 , 0.05173225, 0.00953358, -0.04087641, -0.00427487, -0.0456274 , 0.02155695], dtype=float32)" }, { "code": null, "e": 28908, "s": 28491, "text": "Now suppose we wanted to cluster the eight documents from our toy corpus, we would need to get the document level embeddings from each of the words present in each document. One strategy would be to average out the word embeddings for each word in a document. This is an extremely useful strategy and you can adopt the same for your own problems. Let’s apply this now on our corpus to get features for each document." }, { "code": null, "e": 29251, "s": 28908, "text": "Now that we have our features for each document, let’s cluster these documents using the Affinity Propagation algorithm, which is a clustering algorithm based on the concept of “message passing” between data points and does not need the number of clusters as an explicit input which is often required by partition-based clustering algorithms." }, { "code": null, "e": 29591, "s": 29251, "text": "We can see that our algorithm has clustered each document into the right group based on our Word2Vec features. Pretty neat! We can also visualize how each document in positioned in each cluster by using Principal Component Analysis (PCA) to reduce the feature dimensions to 2-D and then visualizing the same (by color coding each cluster)." }, { "code": null, "e": 29712, "s": 29591, "text": "Everything looks to be in order as documents in each cluster are closer to each other and far apart from other clusters." }, { "code": null, "e": 30296, "s": 29712, "text": "The GloVe model stands for Global Vectors which is an unsupervised learning model which can be used to obtain dense word vectors similar to Word2Vec. However the technique is different and training is performed on an aggregated global word-word co-occurrence matrix, giving us a vector space with meaningful sub-structures. This method was invented in Stanford by Pennington et al. and I recommend you to read the original paper on GloVe, ‘GloVe: Global Vectors for Word Representation’ by Pennington et al. which is an excellent read to get some perspective on how this model works." }, { "code": null, "e": 31049, "s": 30296, "text": "We won’t cover the implementation of the model from scratch in too much detail here but if you are interested in the actual code, you can check out the official GloVe page. We will keep things simple here and try to understand the basic concepts behind the GloVe model. We have talked about count based matrix factorization methods like LSA and predictive methods like Word2Vec. The paper claims that currently, both families suffer significant drawbacks. Methods like LSA efficiently leverage statistical information but they do relatively poorly on the word analogy task like how we found out semantically similar words. Methods like skip-gram may do better on the analogy task, but they poorly utilize the statistics of the corpus on a global level." }, { "code": null, "e": 31422, "s": 31049, "text": "The basic methodology of the GloVe model is to first create a huge word-context co-occurence matrix consisting of (word, context) pairs such that each element in this matrix represents how often a word occurs with the context (which can be a sequence of words). The idea then is to apply matrix factorization to approximate this matrix as depicted in the following figure." }, { "code": null, "e": 32458, "s": 31422, "text": "Considering the Word-Context (WC) matrix, Word-Feature (WF) matrix and Feature-Context (FC) matrix, we try to factorize WC = WF x FC, such that we we aim to reconstruct WC from WF and FC by multiplying them. For this, we typically initialize WF and FC with some random weights and attempt to multiply them to get WC’ (an approximation of WC) and measure how close it is to WC. We do this multiple times using Stochastic Gradient Descent (SGD) to minimize the error. Finally, the Word-Feature matrix (WF) gives us the word embeddings for each word where F can be preset to a specific number of dimensions. A very important point to remember is that both Word2Vec and GloVe models are very similar in how they work. Both of them aim to build a vector space where the position of each word is influenced by its neighboring words based on their context and semantics. Word2Vec starts with local individual examples of word co-occurrence pairs and GloVe starts with global aggregated co-occurrence statistics across all words in the corpus." }, { "code": null, "e": 32899, "s": 32458, "text": "Let’s try and leverage GloVe based embeddings for our document clustering task. The very popular spacy framework comes with capabilities to leverage GloVe embeddings based on different language models. You can also get pre-trained word vectors and load them up as needed using gensim or spacy. We will first install spacy and use the en_vectors_web_lg model which consists of 300-dimensional word vectors trained on Common Crawl with GloVe." }, { "code": null, "e": 33435, "s": 32899, "text": "# Use the following command to install spaCy> pip install -U spacyOR> conda install -c conda-forge spacy# Download the following language model and store it in diskhttps://github.com/explosion/spacy-models/releases/tag/en_vectors_web_lg-2.0.0# Link the same to spacy > python -m spacy link ./spacymodels/en_vectors_web_lg-2.0.0/en_vectors_web_lg en_vecsLinking successful ./spacymodels/en_vectors_web_lg-2.0.0/en_vectors_web_lg --> ./Anaconda3/lib/site-packages/spacy/data/en_vecsYou can now load the model via spacy.load('en_vecs')" }, { "code": null, "e": 33687, "s": 33435, "text": "There are automated ways to install models in spacy too, you can check their Models & Languages page for more information if needed. I had some issues with the same so I had to manually load them up. We will now load up our language model using spacy." }, { "code": null, "e": 33715, "s": 33687, "text": "Total word vectors: 1070971" }, { "code": null, "e": 33847, "s": 33715, "text": "This validates that everything is working and in order. Let’s get the GloVe embeddings for each of our words now in our toy corpus." }, { "code": null, "e": 33952, "s": 33847, "text": "We can now use t-SNE to visualize these embeddings similar to what we did using our Word2Vec embeddings." }, { "code": null, "e": 34248, "s": 33952, "text": "The beauty of spacy is that it will automatically provide you the averaged embeddings for words in each document without having to implement a function like we did in Word2Vec. We will leverage the same to get document features for our corpus and use k-means clustering to cluster our documents." }, { "code": null, "e": 34508, "s": 34248, "text": "We see consistent clusters similar to what we obtained from our Word2Vec model which is good! The GloVe model claims to perform better than the Word2Vec model in many scenarios as illustrated in the following graph from the original paper by Pennington el al." }, { "code": null, "e": 34759, "s": 34508, "text": "The above experiments were done by training 300-dimensional vectors on the same 6B token corpus (Wikipedia 2014 + Gigaword 5) with the same 400,000 word vocabulary and a symmetric context window of size 10 in case anyone is interested in the details." }, { "code": null, "e": 35302, "s": 34759, "text": "The FastText model was first introduced by Facebook in 2016 as an extension and supposedly improvement of the vanilla Word2Vec model. Based on the original paper titled ‘Enriching Word Vectors with Subword Information’ by Mikolov et al. which is an excellent read to gain an in-depth understanding of how this model works. Overall, FastText is a framework for learning word representations and also performing robust, fast and accurate text classification. The framework is open-sourced by Facebook on GitHub and claims to have the following." }, { "code": null, "e": 35348, "s": 35302, "text": "Recent state-of-the-art English word vectors." }, { "code": null, "e": 35411, "s": 35348, "text": "Word vectors for 157 languages trained on Wikipedia and Crawl." }, { "code": null, "e": 35476, "s": 35411, "text": "Models for language identification and various supervised tasks." }, { "code": null, "e": 36176, "s": 35476, "text": "Though I haven’t implemented this model from scratch, based on the research paper, following is what I learnt about how the model works. In general, predictive models like the Word2Vec model typically considers each word as a distinct entity (e.g. where) and generates a dense embedding for the word. However this poses to be a serious limitation with languages having massive vocabularies and many rare words which may not occur a lot in different corpora. The Word2Vec model typically ignores the morphological structure of each word and considers a word as a single entity. The FastText model considers each word as a Bag of Character n-grams. This is also called as a subword model in the paper." }, { "code": null, "e": 36782, "s": 36176, "text": "We add special boundary symbols < and > at the beginning and end of words. This enables us to distinguish prefixes and suffixes from other character sequences. We also include the word w itself in the set of its n-grams, to learn a representation for each word (in addition to its character n-grams). Taking the word where and n=3 (tri-grams) as an example, it will be represented by the character n-grams: <wh, whe, her, ere, re> and the special sequence <where> representing the whole word. Note that the sequence , corresponding to the word <her> is different from the tri-gram her from the word where." }, { "code": null, "e": 37466, "s": 36782, "text": "In practice, the paper recommends in extracting all the n-grams for n ≥ 3 and n ≤ 6. This is a very simple approach, and different sets of n-grams could be considered, for example taking all prefixes and suffixes. We typically associate a vector representation (embedding) to each n-gram for a word. Thus, we can represent a word by the sum of the vector representations of its n-grams or the average of the embedding of these n-grams. Thus, due to this effect of leveraging n-grams from individual words based on their characters, there is a higher chance for rare words to get a good representation since their character based n-grams should occur across other words of the corpus." }, { "code": null, "e": 37721, "s": 37466, "text": "The gensim package has nice wrappers providing us interfaces to leverage the FastText model available under the gensim.models.fasttext module. Let’s apply this once again on our Bible corpus and look at our words of interest and their most similar words." }, { "code": null, "e": 37916, "s": 37721, "text": "You can see a lot of similarity in the results with our Word2Vec model with relevant similar words for each of our words of interest. Do you notice any interesting associations and similarities?" }, { "code": null, "e": 38254, "s": 37916, "text": "Note: Running this model is computationally expensive and usually takes more time as compared to the skip-gram model since it considers n-grams for each word. This works better if trained using a GPU or a good CPU. I trained this on an AWS p2.x instance and it took me around 10 minutes as compared to over 2–3 hours on a regular system." }, { "code": null, "e": 38379, "s": 38254, "text": "Let’s now use Principal Component Analysis (PCA) to reduce the word embedding dimensions to 2-D and then visualize the same." }, { "code": null, "e": 38684, "s": 38379, "text": "We can see a lot of interesting patterns! Noah, his son Shem and grandfather Methuselah are close to each other. We also see God associated with Moses and Egypt where it endured the Biblical plagues including famine and pestilence. Also Jesus and some of his disciples are associated close to each other." }, { "code": null, "e": 38776, "s": 38684, "text": "To access any of the word embeddings you can just index the model with the word as follows." }, { "code": null, "e": 38959, "s": 38776, "text": "ft_model.wv['jesus']array([-0.23493268, 0.14237943, 0.35635167, 0.34680951, 0.09342121,..., -0.15021783, -0.08518736, -0.28278247, -0.19060139], dtype=float32)" }, { "code": null, "e": 39121, "s": 38959, "text": "Having these embeddings, we can perform some interesting natural language tasks. One of these would be to find out similarity between different words (entities)." }, { "code": null, "e": 39264, "s": 39121, "text": "print(ft_model.wv.similarity(w1='god', w2='satan'))print(ft_model.wv.similarity(w1='god', w2='jesus'))Output------0.3332608766850.698824900473" }, { "code": null, "e": 39401, "s": 39264, "text": "We can see that ‘god’ is more closely associated with ‘jesus’ rather than ‘satan’ based on the text in our Bible corpus. Quite relevant!" }, { "code": null, "e": 39509, "s": 39401, "text": "Considering word embeddings being present, we can even find out odd words from a bunch of words as follows." }, { "code": null, "e": 39839, "s": 39509, "text": "st1 = \"god jesus satan john\"print('Odd one out for [',st1, ']:', ft_model.wv.doesnt_match(st1.split()))st2 = \"john peter james judas\"print('Odd one out for [',st2, ']:', ft_model.wv.doesnt_match(st2.split()))Output------Odd one out for [ god jesus satan john ]: satanOdd one out for [ john peter james judas ]: judas" }, { "code": null, "e": 39930, "s": 39839, "text": "Interesting and relevant results in both cases for the odd entity amongst the other words!" }, { "code": null, "e": 40289, "s": 39930, "text": "These examples should give you a good idea about newer and efficient strategies around leveraging deep learning language models to extract features from text data and also address problems like word semantics, context and data sparsity. Next up will be detailed strategies on leveraging deep learning models for feature engineering on image data. Stay tuned!" }, { "code": null, "e": 40396, "s": 40289, "text": "To read about feature engineering strategies for continuous numeric data, check out Part 1 of this series!" }, { "code": null, "e": 40506, "s": 40396, "text": "To read about feature engineering strategies for discrete categoricial data, check out Part 2 of this series!" }, { "code": null, "e": 40624, "s": 40506, "text": "To read about traditional feature engineering strategies for unstructured text data, check out Part 3 of this series!" }, { "code": null, "e": 40702, "s": 40624, "text": "All the code and datasets used in this article can be accessed from my GitHub" }, { "code": null, "e": 40751, "s": 40702, "text": "The code is also available as a Jupyter notebook" }, { "code": null, "e": 40922, "s": 40751, "text": "Architecture diagrams unless explicitly cited are my copyright. Feel free to use them, but please do remember to cite the source if you want to use them in your own work." } ]
How to find datatype of all the fields in MongoDB?
Use typeof to find datatype of all the fields − typeof db.yourCollectionName.findOne().yourFieldName; Let us first create a collection with documents − > db.findDataTypeDemo.insertOne({"ClientName":"Chris","isMarried":false}); { "acknowledged" : true, "insertedId" : ObjectId("5ccf2064dceb9a92e6aa1952") } Following is the query to display all documents from a collection with the help of find() method − > db.findDataTypeDemo.findOne(); This will produce the following output − { "_id" : ObjectId("5ccf2064dceb9a92e6aa1952"), "ClientName" : "Chris", "isMarried" : false } Following is the query to find datatype of a field in MongoDB − > typeof db.findDataTypeDemo.findOne().isMarried; This will produce the following output − Boolean Here is the query to get the data type of another field − > typeof db.findDataTypeDemo.findOne().ClientName; This will produce the following output − String You can get the value also. The query is as follows − > db.findDataTypeDemo.findOne().ClientName; Chris > db.findDataTypeDemo.findOne().isMarried; False
[ { "code": null, "e": 1110, "s": 1062, "text": "Use typeof to find datatype of all the fields −" }, { "code": null, "e": 1164, "s": 1110, "text": "typeof db.yourCollectionName.findOne().yourFieldName;" }, { "code": null, "e": 1214, "s": 1164, "text": "Let us first create a collection with documents −" }, { "code": null, "e": 1374, "s": 1214, "text": "> db.findDataTypeDemo.insertOne({\"ClientName\":\"Chris\",\"isMarried\":false});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ccf2064dceb9a92e6aa1952\")\n}" }, { "code": null, "e": 1473, "s": 1374, "text": "Following is the query to display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1506, "s": 1473, "text": "> db.findDataTypeDemo.findOne();" }, { "code": null, "e": 1547, "s": 1506, "text": "This will produce the following output −" }, { "code": null, "e": 1650, "s": 1547, "text": "{\n \"_id\" : ObjectId(\"5ccf2064dceb9a92e6aa1952\"),\n \"ClientName\" : \"Chris\",\n \"isMarried\" : false\n}" }, { "code": null, "e": 1714, "s": 1650, "text": "Following is the query to find datatype of a field in MongoDB −" }, { "code": null, "e": 1764, "s": 1714, "text": "> typeof db.findDataTypeDemo.findOne().isMarried;" }, { "code": null, "e": 1805, "s": 1764, "text": "This will produce the following output −" }, { "code": null, "e": 1813, "s": 1805, "text": "Boolean" }, { "code": null, "e": 1871, "s": 1813, "text": "Here is the query to get the data type of another field −" }, { "code": null, "e": 1922, "s": 1871, "text": "> typeof db.findDataTypeDemo.findOne().ClientName;" }, { "code": null, "e": 1963, "s": 1922, "text": "This will produce the following output −" }, { "code": null, "e": 1970, "s": 1963, "text": "String" }, { "code": null, "e": 2024, "s": 1970, "text": "You can get the value also. The query is as follows −" }, { "code": null, "e": 2123, "s": 2024, "text": "> db.findDataTypeDemo.findOne().ClientName;\nChris\n> db.findDataTypeDemo.findOne().isMarried;\nFalse" } ]
Graduating in GANs: Going from understanding generative adversarial networks to running your own | by Cecelia Shao | Towards Data Science
Generative Adversarial Networks (GANs) have taken over the public imagination —permeating pop culture with AI- generated celebrities and creating art that is selling for thousands of dollars at high-brow art auctions. In this post, we’ll explore: Brief primer on GANs Understanding and Evaluating GANs Running your own GAN There is a wealth of resources for catching up on GANs, so our focus for this article is to understand how GANs can be evaluated. We’ll also walk you through running your own GAN to generate handwritten digits like MNIST. Since its inception in 2014 with Ian Goodfellow’s ‘Generative Adversarial Networks’ paper, progress with GANs has exploded and led to increasingly realistic outputs. Just three years ago, you could find Ian Goodfellow’s reply on this Reddit thread to a user asking about whether you can use GANs for text: “GANs have not been applied to NLP because GANs are only defined for real-valued data. GANs work by training a generator network that outputs synthetic data, then running a discriminator network on the synthetic data. The gradient of the output of the discriminator network with respect to the synthetic data tells you how to slightly change the synthetic data to make it more realistic. You can make slight changes to the synthetic data only if it is based on continuous numbers. If it is based on discrete numbers, there is no way to make a slight change. For example, if you output an image with a pixel value of 1.0, you can change that pixel value to 1.0001 on the next step. If you output the word “penguin”, you can’t change that to “penguin + .001” on the next step, because there is no such word as “penguin + .001”. You have to go all the way from “penguin” to “ostrich”. Since all NLP is based on discrete values like words, characters, or bytes, no one really knows how to apply GANs to NLP yet.” Now GANs are being used to create all kinds of content including images, video, audio, and (yup) text. These outputs can be used as synthetic data for training other models or just for spawning interesting side projects like thispersondoesnotexist.com, thisairbnbdoesnotexist.com/, and This Machine Learning Medium post does not exist. 😎 A GAN is comprised of two neural networks — a generator that synthesizes new samples from scratch, and a discriminator that compares training samples with these generated samples from the generator. The discriminator’s goal is to distinguish between ‘real’ and ‘fake’ inputs (ie. classify if the samples came from the model distribution or the real distribution). As we described, these samples can be images, videos, audio snippets, and text. To synthesize these new samples, the generator is given random noise and attempts to generate realistic images from the learnt distribution of the training data. The gradient of the output of the discriminator network (a convolutional neural network) with respect to the synthetic data informs how to slightly change the synthetic data to make it more realistic. Eventually the generator converges on parameters that reproduce the real data distribution, and the discriminator is unable to detect the difference. You see and play with these converging data distributions with GAN Lab: poloclub.github.io Here’s a selection of the best guides on GANs : Stanford CS231 Lecture 13 — Generative Models Style-based GANs Understanding Generative Adversarial Networks Introduction to Generative Adversarial Networks Lillian Weng: From Gan to WGAN Dive head first into advanced GANs: exploring self-attention and spectral norm Guim Perarnau: Fantastic GANs and where to find them (Parts I & II) Quantifying the progress of a GAN can feel very subjective — “Does this generated face look realistic enough?” , “Are these generated images diverse enough?” — and GANs can feel like black boxes where it’s not clear which components of the model impact learning or result quality. To this end, a group from the MIT Computer Science and Artificial Intelligence (CSAIL) Lab, recently released a paper, ‘GAN Dissection: Visualizing and Understanding Generative Adversarial Networks’, that introduced a method for visualizing GANs and how GAN units relate to objects in an image as well as the relationship between objects. Using a segmentation-based network dissection method, the paper’s framework allow us to dissect and visualize the inner workings of a generator neural network. This occurs by looking for agreements between a set of GAN units, referred to as neurons, and concepts in the output image such as tree, sky, clouds, and more. As a result, we’re able to identify neurons that are responsible for certain objects such as buildings or clouds. Having this level of granularity into the neurons allows for edits to existing images (e.g. to add or remove trees as shown in the image) by forcefully activating and deactivating (ablating) the corresponding units for those objects. However, it’s not clear if the network is able to reason about objects in a scene or if it’s simply memorizing these objects. One way to get closer to an answer for this question was to try to distort the image in unrealistic ways. Perhaps the most impressive part of MIT CSAIL’s interactive web demo of GAN Paint was how the model is seemingly able to limit these edits to ‘photorealistic’ changes. If you try to impose grass onto the sky, here’s what happens: Even though we’re activating the corresponding neurons, it appears as though the GAN has suppressed the signal in later layers. Another interesting way of visualizing GANs is to conduct latent space interpolation (remember, the GAN generate new instances by sampling from the learned latent space). This can be a useful way of seeing how smooth the transitions across generated samples are. These visualizations can help us understand the internal representations of a GAN, but finding quantifiable ways to understand GAN progress and output quality is still an active area of research. Two commonly used evaluation metrics for image quality and diversity are: the Inception Score and the Fréchet Inception Distance (FID). Most practitioners have shifted from the Inception Score to FID after Shane Barratt and Rishi Sharma released their paper ‘A Note on the Inception Score’ on key shortcomings of the former. Invented in Salimans et al. 2016 in ‘Improved Techniques for Training GANs’, the Inception Score is based on a heuristic that realistic samples should be able to be classified when passed through a pre-trained network, such as Inception on ImageNet. Technically, this means that the sample should have a low entropy softmax prediction vector. Besides high predictability (low entropy), the Inception Score also evaluates a GAN based on how diverse the generated samples are (e.g. high variance or entropy over the distribution of generated samples). This means that there should not be any dominating classes. If both these traits are satisfied, there should be a large Inception Score. The way that you combine the two criteria is by evaluating the Kullback-Leibler (KL) divergence between the conditional label distribution of samples and the marginal distribution from all the samples. Introduced by Heusel et al. 2017, FID estimates realism by measuring the distance between the generated distribution of images and the true distribution. FID embeds a set of generated samples into a feature space given by a specific layer of Inception Net. This embedding layer is viewed as as a continuous multivariate Gaussian, then the mean and covariance are estimated for both the generated data and the real data. The Fréchet distance between these two Gaussians (a.k.a Wasserstein-2 distance) is then used to quantify the quality of generated samples. A lower FID corresponds to more similar real and generated samples. An important note is that FID needs a decent sample size to give good results (suggested size = 50k samples ). If you use too few samples, you will end up over-estimating your actual FID and the estimates will have a large variance. For a comparison of how Inception Scores and FID scores have differed across papers, see Neal Jean’s post here. Aji Borji’s paper, ‘Pros and Cons of GAN Evaluation Measures’ includes an excellent table with more exhaustive coverage of GAN evaluation metrics: Interestingly, other researchers are taking different approaches by using domain-specific evaluation metrics. For text GANs, Guy Tevet and his team proposed using traditional probability-based language model metrics to evaluate the distribution of text generated by a GAN in their paper ‘Evaluating Text GANs as Language Models’. In ‘How good is my GAN?’, Konstantin Shmelkov and his team use two measures based on image classification, GAN-train and GAN-test, which approximate the recall (diversity) and precision (quality of the image) of GANs respectively. You can see these evaluation metrics in action in the Google Brain research paper, ‘Are GANS created equal’, where they used a dataset of triangles to measure the precision and the recall of different GAN models. To illustrate GANs, we’ll be adapting this excellent tutorial from Wouter Bulten that uses Keras and the MNIST dataset to generate written digits. See the full tutorial notebook here. This GAN model takes in the MNIST training data and random noise as an input (specifically, random vectors of noise) to generate: images (in this case, image of handwritten digits). Eventually, these generated images will resemble the data distribution of the MNIST dataset. the discriminator’s prediction on the generated images The Generator and Discriminator models together form the adversarial model — for this example, the generator will perform well if the adversarial model serves an output classifying the generated images as real for all inputs. See the full code here and the full Comet Experiment with results here We’re able to track the training progress for both our Generator and Discriminator models using Comet.ml. We’re plotting both the accuracy and loss for our discriminator and adversarial models — the most important metrics to track here are: the discriminator’s loss (see blue line on the right chart)— dis_loss the adversarial model’s accuracy (see blue line on the left chart) — acc_adv See the training progression for this experiment here. You also want to confirm that your training process is actually using GPUs, which you can check in the Comet System Metrics tab. You notice that our training for-loop includes code to report images from the test vector: if i % 500 == 0: # Visualize the performance of the generator by producing images from the test vector images = net_generator.predict(vis_noise) # Map back to original range #images = (images + 1 ) * 0.5 plt.figure(figsize=(10,10)) for im in range(images.shape[0]): plt.subplot(4, 4, im+1) image = images[im, :, :, :] image = np.reshape(image, [28, 28]) plt.imshow(image, cmap='gray') plt.axis('off') plt.tight_layout() # plt.savefig('/home/ubuntu/cecelia/deeplearning-resources/output/mnist-normal/{}.png'.format(i)) plt.savefig(r'output/mnist-normal/{}.png'.format(i)) experiment.log_image(r'output/mnist-normal/{}.png'.format(i)) plt.close('all') Part of the reason why we want to report generated output every few steps is so that we can visually analyze how our generator and discriminator models are performing in terms of generating realistic handwritten digits and correctly classifying the generated digits as ‘real’ or ‘fake, respectively. Let’s take a look at these generated outputs! See the generated outputs on your own in this Comet Experiment You can see how the Generator models starts off with this fuzzy, grayish output (see 0.png below)that doesn’t really look like the handwritten digits we expect. As training progresses and our models’ losses decline, the generated digits become clearer and clear. Check out the generated outputs at: Step 500: Step 1000: Step 1500: And finally at Step 10,000 — you can see some samples of the GAN-generated digits in the red outlined boxes below Once our GAN model is done training, we can even review our reported outputs as a movie in Comet’s Graphics tab (just press the play button!). To complete the experiment, make you sure run experiment.end() to see some summary statistics around the model and GPU usage. We could train the model longer to see how that impacts performance, but let’s try iterating with a few different parameters. Some of the parameters we play around with are: the discriminator’s optimizer the learning rate dropout probability batch size From Wouter’s original blog post, he mentions his own efforts with testing parameters: I have tested both SGD, RMSprop and Adam for the optimizer of the discriminator but RMSprop performed best. RMSprop is used a low learning rate and I clip the values between -1 and 1. A small decay in the learning rate can help with stabilizing We’ll try increasing the discriminator’s dropout probability from 0.4 to 0.5 and increasing both the discriminator’s learning rate (from 0.008 to 0.0009) and the generator’s learning rate (from 0.0004 to 0.0006). Easy to see how these changes can get out of hand and difficult to track...🤯 To create a different experiment, simply run the experiment definition cell again and Comet will issue you a new url for your new experiment! It’s nice to keep track of your experiments, so you can compare the differences: Unfortunately, our adjustments did not improve the model’s performance! In fact, it generated some funky outputs: That’s it for this tutorial! If you enjoyed this post, feel free to share with a friend who might find it useful 😎
[ { "code": null, "e": 389, "s": 171, "text": "Generative Adversarial Networks (GANs) have taken over the public imagination —permeating pop culture with AI- generated celebrities and creating art that is selling for thousands of dollars at high-brow art auctions." }, { "code": null, "e": 418, "s": 389, "text": "In this post, we’ll explore:" }, { "code": null, "e": 439, "s": 418, "text": "Brief primer on GANs" }, { "code": null, "e": 473, "s": 439, "text": "Understanding and Evaluating GANs" }, { "code": null, "e": 494, "s": 473, "text": "Running your own GAN" }, { "code": null, "e": 716, "s": 494, "text": "There is a wealth of resources for catching up on GANs, so our focus for this article is to understand how GANs can be evaluated. We’ll also walk you through running your own GAN to generate handwritten digits like MNIST." }, { "code": null, "e": 882, "s": 716, "text": "Since its inception in 2014 with Ian Goodfellow’s ‘Generative Adversarial Networks’ paper, progress with GANs has exploded and led to increasingly realistic outputs." }, { "code": null, "e": 1022, "s": 882, "text": "Just three years ago, you could find Ian Goodfellow’s reply on this Reddit thread to a user asking about whether you can use GANs for text:" }, { "code": null, "e": 1109, "s": 1022, "text": "“GANs have not been applied to NLP because GANs are only defined for real-valued data." }, { "code": null, "e": 1410, "s": 1109, "text": "GANs work by training a generator network that outputs synthetic data, then running a discriminator network on the synthetic data. The gradient of the output of the discriminator network with respect to the synthetic data tells you how to slightly change the synthetic data to make it more realistic." }, { "code": null, "e": 1580, "s": 1410, "text": "You can make slight changes to the synthetic data only if it is based on continuous numbers. If it is based on discrete numbers, there is no way to make a slight change." }, { "code": null, "e": 1703, "s": 1580, "text": "For example, if you output an image with a pixel value of 1.0, you can change that pixel value to 1.0001 on the next step." }, { "code": null, "e": 1904, "s": 1703, "text": "If you output the word “penguin”, you can’t change that to “penguin + .001” on the next step, because there is no such word as “penguin + .001”. You have to go all the way from “penguin” to “ostrich”." }, { "code": null, "e": 2031, "s": 1904, "text": "Since all NLP is based on discrete values like words, characters, or bytes, no one really knows how to apply GANs to NLP yet.”" }, { "code": null, "e": 2369, "s": 2031, "text": "Now GANs are being used to create all kinds of content including images, video, audio, and (yup) text. These outputs can be used as synthetic data for training other models or just for spawning interesting side projects like thispersondoesnotexist.com, thisairbnbdoesnotexist.com/, and This Machine Learning Medium post does not exist. 😎" }, { "code": null, "e": 2813, "s": 2369, "text": "A GAN is comprised of two neural networks — a generator that synthesizes new samples from scratch, and a discriminator that compares training samples with these generated samples from the generator. The discriminator’s goal is to distinguish between ‘real’ and ‘fake’ inputs (ie. classify if the samples came from the model distribution or the real distribution). As we described, these samples can be images, videos, audio snippets, and text." }, { "code": null, "e": 2975, "s": 2813, "text": "To synthesize these new samples, the generator is given random noise and attempts to generate realistic images from the learnt distribution of the training data." }, { "code": null, "e": 3326, "s": 2975, "text": "The gradient of the output of the discriminator network (a convolutional neural network) with respect to the synthetic data informs how to slightly change the synthetic data to make it more realistic. Eventually the generator converges on parameters that reproduce the real data distribution, and the discriminator is unable to detect the difference." }, { "code": null, "e": 3398, "s": 3326, "text": "You see and play with these converging data distributions with GAN Lab:" }, { "code": null, "e": 3417, "s": 3398, "text": "poloclub.github.io" }, { "code": null, "e": 3465, "s": 3417, "text": "Here’s a selection of the best guides on GANs :" }, { "code": null, "e": 3511, "s": 3465, "text": "Stanford CS231 Lecture 13 — Generative Models" }, { "code": null, "e": 3528, "s": 3511, "text": "Style-based GANs" }, { "code": null, "e": 3574, "s": 3528, "text": "Understanding Generative Adversarial Networks" }, { "code": null, "e": 3622, "s": 3574, "text": "Introduction to Generative Adversarial Networks" }, { "code": null, "e": 3653, "s": 3622, "text": "Lillian Weng: From Gan to WGAN" }, { "code": null, "e": 3732, "s": 3653, "text": "Dive head first into advanced GANs: exploring self-attention and spectral norm" }, { "code": null, "e": 3800, "s": 3732, "text": "Guim Perarnau: Fantastic GANs and where to find them (Parts I & II)" }, { "code": null, "e": 4081, "s": 3800, "text": "Quantifying the progress of a GAN can feel very subjective — “Does this generated face look realistic enough?” , “Are these generated images diverse enough?” — and GANs can feel like black boxes where it’s not clear which components of the model impact learning or result quality." }, { "code": null, "e": 4420, "s": 4081, "text": "To this end, a group from the MIT Computer Science and Artificial Intelligence (CSAIL) Lab, recently released a paper, ‘GAN Dissection: Visualizing and Understanding Generative Adversarial Networks’, that introduced a method for visualizing GANs and how GAN units relate to objects in an image as well as the relationship between objects." }, { "code": null, "e": 4854, "s": 4420, "text": "Using a segmentation-based network dissection method, the paper’s framework allow us to dissect and visualize the inner workings of a generator neural network. This occurs by looking for agreements between a set of GAN units, referred to as neurons, and concepts in the output image such as tree, sky, clouds, and more. As a result, we’re able to identify neurons that are responsible for certain objects such as buildings or clouds." }, { "code": null, "e": 5088, "s": 4854, "text": "Having this level of granularity into the neurons allows for edits to existing images (e.g. to add or remove trees as shown in the image) by forcefully activating and deactivating (ablating) the corresponding units for those objects." }, { "code": null, "e": 5550, "s": 5088, "text": "However, it’s not clear if the network is able to reason about objects in a scene or if it’s simply memorizing these objects. One way to get closer to an answer for this question was to try to distort the image in unrealistic ways. Perhaps the most impressive part of MIT CSAIL’s interactive web demo of GAN Paint was how the model is seemingly able to limit these edits to ‘photorealistic’ changes. If you try to impose grass onto the sky, here’s what happens:" }, { "code": null, "e": 5678, "s": 5550, "text": "Even though we’re activating the corresponding neurons, it appears as though the GAN has suppressed the signal in later layers." }, { "code": null, "e": 5941, "s": 5678, "text": "Another interesting way of visualizing GANs is to conduct latent space interpolation (remember, the GAN generate new instances by sampling from the learned latent space). This can be a useful way of seeing how smooth the transitions across generated samples are." }, { "code": null, "e": 6137, "s": 5941, "text": "These visualizations can help us understand the internal representations of a GAN, but finding quantifiable ways to understand GAN progress and output quality is still an active area of research." }, { "code": null, "e": 6463, "s": 6137, "text": "Two commonly used evaluation metrics for image quality and diversity are: the Inception Score and the Fréchet Inception Distance (FID). Most practitioners have shifted from the Inception Score to FID after Shane Barratt and Rishi Sharma released their paper ‘A Note on the Inception Score’ on key shortcomings of the former." }, { "code": null, "e": 6806, "s": 6463, "text": "Invented in Salimans et al. 2016 in ‘Improved Techniques for Training GANs’, the Inception Score is based on a heuristic that realistic samples should be able to be classified when passed through a pre-trained network, such as Inception on ImageNet. Technically, this means that the sample should have a low entropy softmax prediction vector." }, { "code": null, "e": 7073, "s": 6806, "text": "Besides high predictability (low entropy), the Inception Score also evaluates a GAN based on how diverse the generated samples are (e.g. high variance or entropy over the distribution of generated samples). This means that there should not be any dominating classes." }, { "code": null, "e": 7352, "s": 7073, "text": "If both these traits are satisfied, there should be a large Inception Score. The way that you combine the two criteria is by evaluating the Kullback-Leibler (KL) divergence between the conditional label distribution of samples and the marginal distribution from all the samples." }, { "code": null, "e": 7980, "s": 7352, "text": "Introduced by Heusel et al. 2017, FID estimates realism by measuring the distance between the generated distribution of images and the true distribution. FID embeds a set of generated samples into a feature space given by a specific layer of Inception Net. This embedding layer is viewed as as a continuous multivariate Gaussian, then the mean and covariance are estimated for both the generated data and the real data. The Fréchet distance between these two Gaussians (a.k.a Wasserstein-2 distance) is then used to quantify the quality of generated samples. A lower FID corresponds to more similar real and generated samples." }, { "code": null, "e": 8213, "s": 7980, "text": "An important note is that FID needs a decent sample size to give good results (suggested size = 50k samples ). If you use too few samples, you will end up over-estimating your actual FID and the estimates will have a large variance." }, { "code": null, "e": 8325, "s": 8213, "text": "For a comparison of how Inception Scores and FID scores have differed across papers, see Neal Jean’s post here." }, { "code": null, "e": 8472, "s": 8325, "text": "Aji Borji’s paper, ‘Pros and Cons of GAN Evaluation Measures’ includes an excellent table with more exhaustive coverage of GAN evaluation metrics:" }, { "code": null, "e": 8802, "s": 8472, "text": "Interestingly, other researchers are taking different approaches by using domain-specific evaluation metrics. For text GANs, Guy Tevet and his team proposed using traditional probability-based language model metrics to evaluate the distribution of text generated by a GAN in their paper ‘Evaluating Text GANs as Language Models’." }, { "code": null, "e": 9246, "s": 8802, "text": "In ‘How good is my GAN?’, Konstantin Shmelkov and his team use two measures based on image classification, GAN-train and GAN-test, which approximate the recall (diversity) and precision (quality of the image) of GANs respectively. You can see these evaluation metrics in action in the Google Brain research paper, ‘Are GANS created equal’, where they used a dataset of triangles to measure the precision and the recall of different GAN models." }, { "code": null, "e": 9393, "s": 9246, "text": "To illustrate GANs, we’ll be adapting this excellent tutorial from Wouter Bulten that uses Keras and the MNIST dataset to generate written digits." }, { "code": null, "e": 9430, "s": 9393, "text": "See the full tutorial notebook here." }, { "code": null, "e": 9560, "s": 9430, "text": "This GAN model takes in the MNIST training data and random noise as an input (specifically, random vectors of noise) to generate:" }, { "code": null, "e": 9705, "s": 9560, "text": "images (in this case, image of handwritten digits). Eventually, these generated images will resemble the data distribution of the MNIST dataset." }, { "code": null, "e": 9760, "s": 9705, "text": "the discriminator’s prediction on the generated images" }, { "code": null, "e": 9986, "s": 9760, "text": "The Generator and Discriminator models together form the adversarial model — for this example, the generator will perform well if the adversarial model serves an output classifying the generated images as real for all inputs." }, { "code": null, "e": 10057, "s": 9986, "text": "See the full code here and the full Comet Experiment with results here" }, { "code": null, "e": 10163, "s": 10057, "text": "We’re able to track the training progress for both our Generator and Discriminator models using Comet.ml." }, { "code": null, "e": 10298, "s": 10163, "text": "We’re plotting both the accuracy and loss for our discriminator and adversarial models — the most important metrics to track here are:" }, { "code": null, "e": 10368, "s": 10298, "text": "the discriminator’s loss (see blue line on the right chart)— dis_loss" }, { "code": null, "e": 10445, "s": 10368, "text": "the adversarial model’s accuracy (see blue line on the left chart) — acc_adv" }, { "code": null, "e": 10500, "s": 10445, "text": "See the training progression for this experiment here." }, { "code": null, "e": 10629, "s": 10500, "text": "You also want to confirm that your training process is actually using GPUs, which you can check in the Comet System Metrics tab." }, { "code": null, "e": 10720, "s": 10629, "text": "You notice that our training for-loop includes code to report images from the test vector:" }, { "code": null, "e": 11530, "s": 10720, "text": "if i % 500 == 0: # Visualize the performance of the generator by producing images from the test vector images = net_generator.predict(vis_noise) # Map back to original range #images = (images + 1 ) * 0.5 plt.figure(figsize=(10,10)) for im in range(images.shape[0]): plt.subplot(4, 4, im+1) image = images[im, :, :, :] image = np.reshape(image, [28, 28]) plt.imshow(image, cmap='gray') plt.axis('off') plt.tight_layout() # plt.savefig('/home/ubuntu/cecelia/deeplearning-resources/output/mnist-normal/{}.png'.format(i)) plt.savefig(r'output/mnist-normal/{}.png'.format(i)) experiment.log_image(r'output/mnist-normal/{}.png'.format(i)) plt.close('all')" }, { "code": null, "e": 11830, "s": 11530, "text": "Part of the reason why we want to report generated output every few steps is so that we can visually analyze how our generator and discriminator models are performing in terms of generating realistic handwritten digits and correctly classifying the generated digits as ‘real’ or ‘fake, respectively." }, { "code": null, "e": 11876, "s": 11830, "text": "Let’s take a look at these generated outputs!" }, { "code": null, "e": 11939, "s": 11876, "text": "See the generated outputs on your own in this Comet Experiment" }, { "code": null, "e": 12100, "s": 11939, "text": "You can see how the Generator models starts off with this fuzzy, grayish output (see 0.png below)that doesn’t really look like the handwritten digits we expect." }, { "code": null, "e": 12238, "s": 12100, "text": "As training progresses and our models’ losses decline, the generated digits become clearer and clear. Check out the generated outputs at:" }, { "code": null, "e": 12248, "s": 12238, "text": "Step 500:" }, { "code": null, "e": 12259, "s": 12248, "text": "Step 1000:" }, { "code": null, "e": 12270, "s": 12259, "text": "Step 1500:" }, { "code": null, "e": 12384, "s": 12270, "text": "And finally at Step 10,000 — you can see some samples of the GAN-generated digits in the red outlined boxes below" }, { "code": null, "e": 12527, "s": 12384, "text": "Once our GAN model is done training, we can even review our reported outputs as a movie in Comet’s Graphics tab (just press the play button!)." }, { "code": null, "e": 12653, "s": 12527, "text": "To complete the experiment, make you sure run experiment.end() to see some summary statistics around the model and GPU usage." }, { "code": null, "e": 12779, "s": 12653, "text": "We could train the model longer to see how that impacts performance, but let’s try iterating with a few different parameters." }, { "code": null, "e": 12827, "s": 12779, "text": "Some of the parameters we play around with are:" }, { "code": null, "e": 12857, "s": 12827, "text": "the discriminator’s optimizer" }, { "code": null, "e": 12875, "s": 12857, "text": "the learning rate" }, { "code": null, "e": 12895, "s": 12875, "text": "dropout probability" }, { "code": null, "e": 12906, "s": 12895, "text": "batch size" }, { "code": null, "e": 12993, "s": 12906, "text": "From Wouter’s original blog post, he mentions his own efforts with testing parameters:" }, { "code": null, "e": 13238, "s": 12993, "text": "I have tested both SGD, RMSprop and Adam for the optimizer of the discriminator but RMSprop performed best. RMSprop is used a low learning rate and I clip the values between -1 and 1. A small decay in the learning rate can help with stabilizing" }, { "code": null, "e": 13528, "s": 13238, "text": "We’ll try increasing the discriminator’s dropout probability from 0.4 to 0.5 and increasing both the discriminator’s learning rate (from 0.008 to 0.0009) and the generator’s learning rate (from 0.0004 to 0.0006). Easy to see how these changes can get out of hand and difficult to track...🤯" }, { "code": null, "e": 13751, "s": 13528, "text": "To create a different experiment, simply run the experiment definition cell again and Comet will issue you a new url for your new experiment! It’s nice to keep track of your experiments, so you can compare the differences:" }, { "code": null, "e": 13865, "s": 13751, "text": "Unfortunately, our adjustments did not improve the model’s performance! In fact, it generated some funky outputs:" } ]
7 Ways to Check CPU Clock Speed in Linux - GeeksforGeeks
20 Apr, 2021 In general, a higher clock speed means a faster CPU. However, many other factors come into play. Your CPU processes many instructions (low-level calculations like arithmetic) from different programs every second. The clock speed measures the number of cycles your CPU executes per second, measured in GHz (gigahertz). A “cycle” is technically a pulse synchronized by an internal oscillator, but for our purposes, they’re a basic unit that helps understand a CPU’s speed. During each cycle, billions of transistors within the processor open and close. On Linux, there are a number of commands that can be used to obtain the CPU speed of the processor. In this article, we’ll look at some of the most widely used commands for obtaining CPU speed about the CPU. Hardinfo is a graphical user interface (GUI) tool that produces reports on various hardware components. It is written in Gtk. However, if there is no GUI display available, it can also be run from the command line. $ hardinfo | less Using hardinfo The /proc/cpuinfo system file lists each CPU Core. System’s individual speed. $ cat /proc/cpuinfo | grep MHz From /proc/cpuinfo Inxi is a Linux script that allows you to print the system’s hardware details. To print processor-related details, use the inxi command with the ‘-C’ option: $ sudo inxi -C Using Inxi script In Linux, the hwinfo command prints detailed details about each hardware unit. $ sudo hwinfo --cpu Using hwinfo Lscpu is a Linux command that displays CPU architecture details. The util-linux package contains this instruction. $ sudo lscpu Using lscpu Dmesg displays messages from the kernel ring buffer and dumps them to /var/log/messages in Linux. $ sudo dmesg | grep MHz Using Dmesg The i7z is a dedicated tool for displaying processor states on Intel i3, i5, and i7 based CPUs. $ sudo i7z Using i7z On Linux-based systems such as Ubuntu, Fedora, Debian, CentOS, and others, those were some commands to check CPU speed. Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. scp command in Linux with Examples SED command in Linux | Set 2 Docker - COPY Instruction mv command in Linux with examples chown command in Linux with Examples nohup Command in Linux with Examples Named Pipe or FIFO with example C program Thread functions in C/C++ uniq Command in LINUX with examples Basic Operators in Shell Scripting
[ { "code": null, "e": 25761, "s": 25733, "text": "\n20 Apr, 2021" }, { "code": null, "e": 26312, "s": 25761, "text": "In general, a higher clock speed means a faster CPU. However, many other factors come into play. Your CPU processes many instructions (low-level calculations like arithmetic) from different programs every second. The clock speed measures the number of cycles your CPU executes per second, measured in GHz (gigahertz). A “cycle” is technically a pulse synchronized by an internal oscillator, but for our purposes, they’re a basic unit that helps understand a CPU’s speed. During each cycle, billions of transistors within the processor open and close." }, { "code": null, "e": 26520, "s": 26312, "text": "On Linux, there are a number of commands that can be used to obtain the CPU speed of the processor. In this article, we’ll look at some of the most widely used commands for obtaining CPU speed about the CPU." }, { "code": null, "e": 26735, "s": 26520, "text": "Hardinfo is a graphical user interface (GUI) tool that produces reports on various hardware components. It is written in Gtk. However, if there is no GUI display available, it can also be run from the command line." }, { "code": null, "e": 26753, "s": 26735, "text": "$ hardinfo | less" }, { "code": null, "e": 26768, "s": 26753, "text": "Using hardinfo" }, { "code": null, "e": 26846, "s": 26768, "text": "The /proc/cpuinfo system file lists each CPU Core. System’s individual speed." }, { "code": null, "e": 26877, "s": 26846, "text": "$ cat /proc/cpuinfo | grep MHz" }, { "code": null, "e": 26896, "s": 26877, "text": "From /proc/cpuinfo" }, { "code": null, "e": 27054, "s": 26896, "text": "Inxi is a Linux script that allows you to print the system’s hardware details. To print processor-related details, use the inxi command with the ‘-C’ option:" }, { "code": null, "e": 27070, "s": 27054, "text": "$ sudo inxi -C" }, { "code": null, "e": 27088, "s": 27070, "text": "Using Inxi script" }, { "code": null, "e": 27167, "s": 27088, "text": "In Linux, the hwinfo command prints detailed details about each hardware unit." }, { "code": null, "e": 27187, "s": 27167, "text": "$ sudo hwinfo --cpu" }, { "code": null, "e": 27200, "s": 27187, "text": "Using hwinfo" }, { "code": null, "e": 27315, "s": 27200, "text": "Lscpu is a Linux command that displays CPU architecture details. The util-linux package contains this instruction." }, { "code": null, "e": 27328, "s": 27315, "text": "$ sudo lscpu" }, { "code": null, "e": 27340, "s": 27328, "text": "Using lscpu" }, { "code": null, "e": 27438, "s": 27340, "text": "Dmesg displays messages from the kernel ring buffer and dumps them to /var/log/messages in Linux." }, { "code": null, "e": 27462, "s": 27438, "text": "$ sudo dmesg | grep MHz" }, { "code": null, "e": 27474, "s": 27462, "text": "Using Dmesg" }, { "code": null, "e": 27570, "s": 27474, "text": "The i7z is a dedicated tool for displaying processor states on Intel i3, i5, and i7 based CPUs." }, { "code": null, "e": 27581, "s": 27570, "text": "$ sudo i7z" }, { "code": null, "e": 27591, "s": 27581, "text": "Using i7z" }, { "code": null, "e": 27711, "s": 27591, "text": "On Linux-based systems such as Ubuntu, Fedora, Debian, CentOS, and others, those were some commands to check CPU speed." }, { "code": null, "e": 27718, "s": 27711, "text": "Picked" }, { "code": null, "e": 27729, "s": 27718, "text": "Linux-Unix" }, { "code": null, "e": 27827, "s": 27729, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27862, "s": 27827, "text": "scp command in Linux with Examples" }, { "code": null, "e": 27891, "s": 27862, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 27917, "s": 27891, "text": "Docker - COPY Instruction" }, { "code": null, "e": 27951, "s": 27917, "text": "mv command in Linux with examples" }, { "code": null, "e": 27988, "s": 27951, "text": "chown command in Linux with Examples" }, { "code": null, "e": 28025, "s": 27988, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 28067, "s": 28025, "text": "Named Pipe or FIFO with example C program" }, { "code": null, "e": 28093, "s": 28067, "text": "Thread functions in C/C++" }, { "code": null, "e": 28129, "s": 28093, "text": "uniq Command in LINUX with examples" } ]
Airflow Schedule Interval 101. The airflow schedule interval could be... | by Chengzhi Zhao | Towards Data Science
The airflow schedule interval could be a challenging concept to comprehend, even for developers work on Airflow for a while find difficult to grasp. A confusing question arises every once a while on StackOverflow is “Why my DAG is not running as expected?”. This problem usually indicates a misunderstanding among the Airflow schedule interval. In this article, we will talk about how to set up the Airflow schedule interval, what result you should expect for scheduling your Airflow DAGs, and how to debug the Airflow schedule interval issues with examples. First of all, Airflow is not a streaming solution. People usually use it as an ETL tool or replacement of cron. As Airflow has its scheduler and it adopts the schedule interval syntax from cron, the smallest data and time interval in the Airflow scheduler world is minute. Inside of the scheduler, the only thing that is continuously running is the scheduler itself. However, as a non-streaming solution to avoid hammering your system resources, Airflow won’t watch and trigger your DAGs all the time. It arranges the monitoring with some intervals, which is a configurable setting called scheduler_heartbeat_sec , it is suggested you provide a number more substantial than 60 seconds to avoid some unexpected results in production. The reason is Airflow still needs a backend database to keep track of all the progress in case of a crash. Setting up fewer heartbeat seconds means the Airflow scheduler has to check more frequently to see if it needs to trigger any new tasks, you place more pressure on the Airflow scheduler as well as its backend database. Finally, the Airflow scheduler follows the heartbeat interval and iterate through all DAGs and calculates their next schedule time and compare with wall clock time to examine whether a given DAG should be triggered or not. Every DAG has its schedule, start_date is simply the date a DAG should be included in the eyes of the Airflow scheduler. It also helps the developers to release a DAG before its production date. You could set up start_date more dynamically before Airflow 1.8. However, it is recommended you set a fixed date, and more detail can be referred to as “Less forgiving scheduler on dynamic start_date”. Airflow infrastructure initially starts only with UTC. Although you can configure Airflow to run on your local time now, most deployment is still under UTC. Setting up Airflow under UTC makes it easy for business across multiple time zones and make your life easier on occasional events such as daylight saving days. The schedule interval that you set up would be the same as your Airflow infrastructure setup. You probably familiar with the syntax of defining a DAG, and usually implement both start_date and scheduler_interval under the args in the DAG class. from airflow import DAGfrom datetime import datetime, timedeltadefault_args = { 'owner': 'XYZ', 'start_date': datetime(2020, 4, 1), 'schedule_interval': '@daily',}dag = DAG('tutorial', catchup=False, default_args=default_args) The Airflow Scheduler section provides more detail on what value you can provide. Necessarily, you’d need a crontab forscheduler_interval . If you found yourself lost in crontab’s definition, try to use crontab guru, and it will explain what you put there. Airflow also gives you some user-friendly names like @daily or @weekly . I found those names are less clean and expressible than crontab. It is also limited to a few intervals, and the underlying implementation is still a crontab, so you might even want to learn crontab and live with it. Moreover, if you just want to trigger your DAG, use manually schedule_interval:None . As a scheduler, date and time are very imperative components. In Airflow, there are two dates you’d need to put extra effort to digest: execution_date and start_date . Note thestart_date is not the same as the date you defined in the previous DAG. execution_date is the start date and time when you expect a DAG to be triggered. start_date is the data and time when a DAG has been triggered, and this time usually refers to the wall clock. A frequently asked question is, “why execution_date is not the same as start_date?” To get an answer for this, let’s take a look at one DAG execution and use 0 2 * * * , and this helps us understand the Airflow schedule interval better. Please refer to the following code as an example. 0 2 * * * means Airflow will start a new job at 2:00 a.m. every day. We can keep a DAG with this interval to run for multiple days. If you click Browse → Tasks Instances , you’d see both execution_date and start_date. I started this new DAG at 04–10 00:05:21 (UTC), the first thing usually happens to any new Airflow DAG is backfill, which is enabled by default. As you can see in the snapshot below, execution_date is perfectly incremented as expected by day, and the time is anticipated as well. On the other hand, start_date is when the Airflow scheduler started a task. After backfilling all the previous executions, you probably notice that 04–09 is not here, but it is 04–10 wall clock already. What went wrong here? The answer is: NOTHING IS WRONG. First, Airflow is built with an ETL mindset, which is usually a batch processing that runs 24 hours. Think about an ETL job, within that 24 hours window, and you’d trigger the job only after the 24 hours finished. The same rule applies here, and we don’t see the execution_date on 04–09 is because 24 hours window has not been closed yet. From execution_date, we know the last successful run was on 04–08T02:00:00 (remember the execution_date here is the start time of 24-hour window), and it ends at 04–09T02:00:00 (exclusive). So what would be our 24-hour window for 04–09 run? It is from 04–09T02:00:00 to 04–10T02:00:00, which has not been reached yet. When does the Airflow scheduler run the 04–09 execution? It waits until 04–10 02:00:00 (wall clock). Once the 04–09 execution has been triggered, you’d see execution_date as 04–09T02:00:00 and start_date would be something like 04–10T02:01:15 (this varies as Airflow decides when to trigger the task, and we’ll cover more in next section). Given the context above, you can easily see why execution_date is not the same as start_date. Understanding the difference between execution_date and start_date would be very helpful when you try to apply your code based on execution_date and use a macro like {{ds}} Another way to think this would be: the execution_date would be close to the previous start_date. Let’s use a more complex example: 0 2 * * 4,5,6 , and this crontab means run At 02:00 on Thursday, Friday, and Saturday. Below is the calendar for wall clock or start_date, and the red texts are the execution_date expected. If you have the schedule interval like this, you shouldn’t be shocked that Airflow would trigger 04–04 DAG execution on 04–09. From the example above, although we figured out the date is different but time is slightly different. For example, with daily interval, execution_date is 04–09T02:00:00 ,and start_date is on 04–10T02:01:15. What does the Airflow do with that 1.25-minute delay? An analogy for this would be a meeting scenario. You probably won’t start the meeting at the same time as it states on your calendar. For example, you have a virtual meeting invitation every Monday at 10:00:00 a.m (scheduler_interval). On this Monday at 10:00:00 a.m. (execution_date), you receive a notification from joining the meeting from your calendar reminder, then you click that meeting link and start your virtual meeting. By the time you entered, and the meeting starts, it is 10:01:15 a.m. (start_date). You probably already noticed the small delay between execution_date and start_date. Ideally, they should be the same, but the reality is not. The question is why Airflow won’t trigger the DAG on time and delay its actual run? As we discussed before, the Airflow scheduler won’t monitor the DAGs all the time. The scheduler waits for its next heartbeat to trigger new DAGs, and this process causes delays. Also, even when the scheduler is ready to trigger at the exact same time, you need to consider the code execution and DB update time too. All the above reasons cause a short delay in scheduling. I hope this article can demystify how the Airflow schedule interval works. Airflow is a complicated system internally but straightforward to work with for users. With its ETL mindset initially, it could take some time to understand how the Airflow scheduler handles time interval. Once you get a better understanding of the Airflow schedule interval, creating a DAG with the desired interval should be an unobstructed process. If you like this article, please click claps to support me.
[ { "code": null, "e": 731, "s": 172, "text": "The airflow schedule interval could be a challenging concept to comprehend, even for developers work on Airflow for a while find difficult to grasp. A confusing question arises every once a while on StackOverflow is “Why my DAG is not running as expected?”. This problem usually indicates a misunderstanding among the Airflow schedule interval. In this article, we will talk about how to set up the Airflow schedule interval, what result you should expect for scheduling your Airflow DAGs, and how to debug the Airflow schedule interval issues with examples." }, { "code": null, "e": 1098, "s": 731, "text": "First of all, Airflow is not a streaming solution. People usually use it as an ETL tool or replacement of cron. As Airflow has its scheduler and it adopts the schedule interval syntax from cron, the smallest data and time interval in the Airflow scheduler world is minute. Inside of the scheduler, the only thing that is continuously running is the scheduler itself." }, { "code": null, "e": 1790, "s": 1098, "text": "However, as a non-streaming solution to avoid hammering your system resources, Airflow won’t watch and trigger your DAGs all the time. It arranges the monitoring with some intervals, which is a configurable setting called scheduler_heartbeat_sec , it is suggested you provide a number more substantial than 60 seconds to avoid some unexpected results in production. The reason is Airflow still needs a backend database to keep track of all the progress in case of a crash. Setting up fewer heartbeat seconds means the Airflow scheduler has to check more frequently to see if it needs to trigger any new tasks, you place more pressure on the Airflow scheduler as well as its backend database." }, { "code": null, "e": 2013, "s": 1790, "text": "Finally, the Airflow scheduler follows the heartbeat interval and iterate through all DAGs and calculates their next schedule time and compare with wall clock time to examine whether a given DAG should be triggered or not." }, { "code": null, "e": 2410, "s": 2013, "text": "Every DAG has its schedule, start_date is simply the date a DAG should be included in the eyes of the Airflow scheduler. It also helps the developers to release a DAG before its production date. You could set up start_date more dynamically before Airflow 1.8. However, it is recommended you set a fixed date, and more detail can be referred to as “Less forgiving scheduler on dynamic start_date”." }, { "code": null, "e": 2821, "s": 2410, "text": "Airflow infrastructure initially starts only with UTC. Although you can configure Airflow to run on your local time now, most deployment is still under UTC. Setting up Airflow under UTC makes it easy for business across multiple time zones and make your life easier on occasional events such as daylight saving days. The schedule interval that you set up would be the same as your Airflow infrastructure setup." }, { "code": null, "e": 2972, "s": 2821, "text": "You probably familiar with the syntax of defining a DAG, and usually implement both start_date and scheduler_interval under the args in the DAG class." }, { "code": null, "e": 3208, "s": 2972, "text": "from airflow import DAGfrom datetime import datetime, timedeltadefault_args = { 'owner': 'XYZ', 'start_date': datetime(2020, 4, 1), 'schedule_interval': '@daily',}dag = DAG('tutorial', catchup=False, default_args=default_args)" }, { "code": null, "e": 3840, "s": 3208, "text": "The Airflow Scheduler section provides more detail on what value you can provide. Necessarily, you’d need a crontab forscheduler_interval . If you found yourself lost in crontab’s definition, try to use crontab guru, and it will explain what you put there. Airflow also gives you some user-friendly names like @daily or @weekly . I found those names are less clean and expressible than crontab. It is also limited to a few intervals, and the underlying implementation is still a crontab, so you might even want to learn crontab and live with it. Moreover, if you just want to trigger your DAG, use manually schedule_interval:None ." }, { "code": null, "e": 4088, "s": 3840, "text": "As a scheduler, date and time are very imperative components. In Airflow, there are two dates you’d need to put extra effort to digest: execution_date and start_date . Note thestart_date is not the same as the date you defined in the previous DAG." }, { "code": null, "e": 4169, "s": 4088, "text": "execution_date is the start date and time when you expect a DAG to be triggered." }, { "code": null, "e": 4280, "s": 4169, "text": "start_date is the data and time when a DAG has been triggered, and this time usually refers to the wall clock." }, { "code": null, "e": 4567, "s": 4280, "text": "A frequently asked question is, “why execution_date is not the same as start_date?” To get an answer for this, let’s take a look at one DAG execution and use 0 2 * * * , and this helps us understand the Airflow schedule interval better. Please refer to the following code as an example." }, { "code": null, "e": 4785, "s": 4567, "text": "0 2 * * * means Airflow will start a new job at 2:00 a.m. every day. We can keep a DAG with this interval to run for multiple days. If you click Browse → Tasks Instances , you’d see both execution_date and start_date." }, { "code": null, "e": 5141, "s": 4785, "text": "I started this new DAG at 04–10 00:05:21 (UTC), the first thing usually happens to any new Airflow DAG is backfill, which is enabled by default. As you can see in the snapshot below, execution_date is perfectly incremented as expected by day, and the time is anticipated as well. On the other hand, start_date is when the Airflow scheduler started a task." }, { "code": null, "e": 5290, "s": 5141, "text": "After backfilling all the previous executions, you probably notice that 04–09 is not here, but it is 04–10 wall clock already. What went wrong here?" }, { "code": null, "e": 5323, "s": 5290, "text": "The answer is: NOTHING IS WRONG." }, { "code": null, "e": 5980, "s": 5323, "text": "First, Airflow is built with an ETL mindset, which is usually a batch processing that runs 24 hours. Think about an ETL job, within that 24 hours window, and you’d trigger the job only after the 24 hours finished. The same rule applies here, and we don’t see the execution_date on 04–09 is because 24 hours window has not been closed yet. From execution_date, we know the last successful run was on 04–08T02:00:00 (remember the execution_date here is the start time of 24-hour window), and it ends at 04–09T02:00:00 (exclusive). So what would be our 24-hour window for 04–09 run? It is from 04–09T02:00:00 to 04–10T02:00:00, which has not been reached yet." }, { "code": null, "e": 6320, "s": 5980, "text": "When does the Airflow scheduler run the 04–09 execution? It waits until 04–10 02:00:00 (wall clock). Once the 04–09 execution has been triggered, you’d see execution_date as 04–09T02:00:00 and start_date would be something like 04–10T02:01:15 (this varies as Airflow decides when to trigger the task, and we’ll cover more in next section)." }, { "code": null, "e": 6587, "s": 6320, "text": "Given the context above, you can easily see why execution_date is not the same as start_date. Understanding the difference between execution_date and start_date would be very helpful when you try to apply your code based on execution_date and use a macro like {{ds}}" }, { "code": null, "e": 6806, "s": 6587, "text": "Another way to think this would be: the execution_date would be close to the previous start_date. Let’s use a more complex example: 0 2 * * 4,5,6 , and this crontab means run At 02:00 on Thursday, Friday, and Saturday." }, { "code": null, "e": 7036, "s": 6806, "text": "Below is the calendar for wall clock or start_date, and the red texts are the execution_date expected. If you have the schedule interval like this, you shouldn’t be shocked that Airflow would trigger 04–04 DAG execution on 04–09." }, { "code": null, "e": 7297, "s": 7036, "text": "From the example above, although we figured out the date is different but time is slightly different. For example, with daily interval, execution_date is 04–09T02:00:00 ,and start_date is on 04–10T02:01:15. What does the Airflow do with that 1.25-minute delay?" }, { "code": null, "e": 7812, "s": 7297, "text": "An analogy for this would be a meeting scenario. You probably won’t start the meeting at the same time as it states on your calendar. For example, you have a virtual meeting invitation every Monday at 10:00:00 a.m (scheduler_interval). On this Monday at 10:00:00 a.m. (execution_date), you receive a notification from joining the meeting from your calendar reminder, then you click that meeting link and start your virtual meeting. By the time you entered, and the meeting starts, it is 10:01:15 a.m. (start_date)." }, { "code": null, "e": 8412, "s": 7812, "text": "You probably already noticed the small delay between execution_date and start_date. Ideally, they should be the same, but the reality is not. The question is why Airflow won’t trigger the DAG on time and delay its actual run? As we discussed before, the Airflow scheduler won’t monitor the DAGs all the time. The scheduler waits for its next heartbeat to trigger new DAGs, and this process causes delays. Also, even when the scheduler is ready to trigger at the exact same time, you need to consider the code execution and DB update time too. All the above reasons cause a short delay in scheduling." }, { "code": null, "e": 8839, "s": 8412, "text": "I hope this article can demystify how the Airflow schedule interval works. Airflow is a complicated system internally but straightforward to work with for users. With its ETL mindset initially, it could take some time to understand how the Airflow scheduler handles time interval. Once you get a better understanding of the Airflow schedule interval, creating a DAG with the desired interval should be an unobstructed process." } ]
Python - Filter immutable rows representing Dictionary Keys from Matrix - GeeksforGeeks
01 Nov, 2020 Given Matrix, extract all the rows which has elements which have all elements which can be represented as dictionary key, i.e immutable. Input : test_list = [[4, 5, [2, 3, 2]], [“gfg”, 1, (4, 4)], [{5:4}, 3, “good”], [True, “best”]] Output : [[‘gfg’, 1, (4, 4)], [True, ‘best’]] Explanation : All elements in tuples are immutable. Input : test_list = [[4, 5, [2, 3, 2]], [“gfg”, 1, (4, 4), [3, 2]], [{5:4}, 3, “good”], [True, “best”]] Output : [[True, ‘best’]] Explanation : All elements in tuples are immutable. Method #1 : Using all() + isinstance() In this, we check for all elements to be of the instance of immutable data types, rows that return True for all elements, is filtered. Python3 # Python3 code to demonstrate working of# Filter Dictionary Key Possible Element rows# Using all() + isinstance() # initializing listtest_list = [[4, 5, [2, 3, 2]], ["gfg", 1, (4, 4)], [{5: 4}, 3, "good"], [ True, "best"]] # printing original listprint("The original list is : " + str(test_list)) # checking for each immutable data typeres = [row for row in test_list if all(isinstance(ele, int) or isinstance(ele, bool) or isinstance(ele, float) or isinstance(ele, tuple) or isinstance(ele, str) for ele in row)] # printing resultprint("Filtered rows : " + str(res)) Output: The original list is : [[4, 5, [2, 3, 2]], [‘gfg’, 1, (4, 4)], [{5: 4}, 3, ‘good’], [True, ‘best’]]Filtered rows : [[‘gfg’, 1, (4, 4)], [True, ‘best’]] Method #2 : Using filter() + lambda + isinstance() + all() In this, we perform task of filtering using filter() + lambda function, rest all functionalities are performed as above method. Python3 # Python3 code to demonstrate working of# Filter Dictionary Key Possible Element rows# Using filter() + lambda + isinstance() + all() # initializing listtest_list = [[4, 5, [2, 3, 2]], ["gfg", 1, (4, 4)], [{5: 4}, 3, "good"], [ True, "best"]] # printing original listprint("The original list is : " + str(test_list)) # checking for each immutable data type# filtering using filter()res = list(filter(lambda row: all(isinstance(ele, int) or isinstance(ele, bool) or isinstance(ele, float) or isinstance(ele, tuple) or isinstance(ele, str) for ele in row), test_list)) # printing resultprint("Filtered rows : " + str(res)) Output: The original list is : [[4, 5, [2, 3, 2]], [‘gfg’, 1, (4, 4)], [{5: 4}, 3, ‘good’], [True, ‘best’]]Filtered rows : [[‘gfg’, 1, (4, 4)], [True, ‘best’]] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25555, "s": 25527, "text": "\n01 Nov, 2020" }, { "code": null, "e": 25692, "s": 25555, "text": "Given Matrix, extract all the rows which has elements which have all elements which can be represented as dictionary key, i.e immutable." }, { "code": null, "e": 25887, "s": 25692, "text": "Input : test_list = [[4, 5, [2, 3, 2]], [“gfg”, 1, (4, 4)], [{5:4}, 3, “good”], [True, “best”]] Output : [[‘gfg’, 1, (4, 4)], [True, ‘best’]] Explanation : All elements in tuples are immutable. " }, { "code": null, "e": 26070, "s": 25887, "text": "Input : test_list = [[4, 5, [2, 3, 2]], [“gfg”, 1, (4, 4), [3, 2]], [{5:4}, 3, “good”], [True, “best”]] Output : [[True, ‘best’]] Explanation : All elements in tuples are immutable. " }, { "code": null, "e": 26109, "s": 26070, "text": "Method #1 : Using all() + isinstance()" }, { "code": null, "e": 26244, "s": 26109, "text": "In this, we check for all elements to be of the instance of immutable data types, rows that return True for all elements, is filtered." }, { "code": null, "e": 26252, "s": 26244, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Filter Dictionary Key Possible Element rows# Using all() + isinstance() # initializing listtest_list = [[4, 5, [2, 3, 2]], [\"gfg\", 1, (4, 4)], [{5: 4}, 3, \"good\"], [ True, \"best\"]] # printing original listprint(\"The original list is : \" + str(test_list)) # checking for each immutable data typeres = [row for row in test_list if all(isinstance(ele, int) or isinstance(ele, bool) or isinstance(ele, float) or isinstance(ele, tuple) or isinstance(ele, str) for ele in row)] # printing resultprint(\"Filtered rows : \" + str(res))", "e": 26903, "s": 26252, "text": null }, { "code": null, "e": 26911, "s": 26903, "text": "Output:" }, { "code": null, "e": 27063, "s": 26911, "text": "The original list is : [[4, 5, [2, 3, 2]], [‘gfg’, 1, (4, 4)], [{5: 4}, 3, ‘good’], [True, ‘best’]]Filtered rows : [[‘gfg’, 1, (4, 4)], [True, ‘best’]]" }, { "code": null, "e": 27122, "s": 27063, "text": "Method #2 : Using filter() + lambda + isinstance() + all()" }, { "code": null, "e": 27250, "s": 27122, "text": "In this, we perform task of filtering using filter() + lambda function, rest all functionalities are performed as above method." }, { "code": null, "e": 27258, "s": 27250, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Filter Dictionary Key Possible Element rows# Using filter() + lambda + isinstance() + all() # initializing listtest_list = [[4, 5, [2, 3, 2]], [\"gfg\", 1, (4, 4)], [{5: 4}, 3, \"good\"], [ True, \"best\"]] # printing original listprint(\"The original list is : \" + str(test_list)) # checking for each immutable data type# filtering using filter()res = list(filter(lambda row: all(isinstance(ele, int) or isinstance(ele, bool) or isinstance(ele, float) or isinstance(ele, tuple) or isinstance(ele, str) for ele in row), test_list)) # printing resultprint(\"Filtered rows : \" + str(res))", "e": 27952, "s": 27258, "text": null }, { "code": null, "e": 27960, "s": 27952, "text": "Output:" }, { "code": null, "e": 28112, "s": 27960, "text": "The original list is : [[4, 5, [2, 3, 2]], [‘gfg’, 1, (4, 4)], [{5: 4}, 3, ‘good’], [True, ‘best’]]Filtered rows : [[‘gfg’, 1, (4, 4)], [True, ‘best’]]" }, { "code": null, "e": 28133, "s": 28112, "text": "Python list-programs" }, { "code": null, "e": 28140, "s": 28133, "text": "Python" }, { "code": null, "e": 28156, "s": 28140, "text": "Python Programs" }, { "code": null, "e": 28254, "s": 28156, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28286, "s": 28254, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28328, "s": 28286, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28370, "s": 28328, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28426, "s": 28370, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28453, "s": 28426, "text": "Python Classes and Objects" }, { "code": null, "e": 28475, "s": 28453, "text": "Defaultdict in Python" }, { "code": null, "e": 28514, "s": 28475, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28560, "s": 28514, "text": "Python | Split string into list of characters" }, { "code": null, "e": 28598, "s": 28560, "text": "Python | Convert a list to dictionary" } ]
Go - Method
Go programming language supports special types of functions called methods. In method declaration syntax, a "receiver" is present to represent the container of the function. This receiver can be used to call a function using "." operator. For example − func (variable_name variable_data_type) function_name() [return_type]{ /* function body*/ } package main import ( "fmt" "math" ) /* define a circle */ type Circle struct { x,y,radius float64 } /* define a method for circle */ func(circle Circle) area() float64 { return math.Pi * circle.radius * circle.radius } func main(){ circle := Circle{x:0, y:0, radius:5} fmt.Printf("Circle area: %f", circle.area()) } When the above code is compiled and executed, it produces the following result − Circle area: 78.539816 64 Lectures 6.5 hours Ridhi Arora 20 Lectures 2.5 hours Asif Hussain 22 Lectures 4 hours Dilip Padmanabhan 48 Lectures 6 hours Arnab Chakraborty 7 Lectures 1 hours Aditya Kulkarni 44 Lectures 3 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2190, "s": 1937, "text": "Go programming language supports special types of functions called methods. In method declaration syntax, a \"receiver\" is present to represent the container of the function. This receiver can be used to call a function using \".\" operator. For example −" }, { "code": null, "e": 2286, "s": 2190, "text": "func (variable_name variable_data_type) function_name() [return_type]{\n /* function body*/\n}\n" }, { "code": null, "e": 2627, "s": 2286, "text": "package main\n\nimport (\n \"fmt\" \n \"math\" \n)\n\n/* define a circle */\ntype Circle struct {\n x,y,radius float64\n}\n\n/* define a method for circle */\nfunc(circle Circle) area() float64 {\n return math.Pi * circle.radius * circle.radius\n}\n\nfunc main(){\n circle := Circle{x:0, y:0, radius:5}\n fmt.Printf(\"Circle area: %f\", circle.area())\n}" }, { "code": null, "e": 2708, "s": 2627, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 2732, "s": 2708, "text": "Circle area: 78.539816\n" }, { "code": null, "e": 2767, "s": 2732, "text": "\n 64 Lectures \n 6.5 hours \n" }, { "code": null, "e": 2780, "s": 2767, "text": " Ridhi Arora" }, { "code": null, "e": 2815, "s": 2780, "text": "\n 20 Lectures \n 2.5 hours \n" }, { "code": null, "e": 2829, "s": 2815, "text": " Asif Hussain" }, { "code": null, "e": 2862, "s": 2829, "text": "\n 22 Lectures \n 4 hours \n" }, { "code": null, "e": 2881, "s": 2862, "text": " Dilip Padmanabhan" }, { "code": null, "e": 2914, "s": 2881, "text": "\n 48 Lectures \n 6 hours \n" }, { "code": null, "e": 2933, "s": 2914, "text": " Arnab Chakraborty" }, { "code": null, "e": 2965, "s": 2933, "text": "\n 7 Lectures \n 1 hours \n" }, { "code": null, "e": 2982, "s": 2965, "text": " Aditya Kulkarni" }, { "code": null, "e": 3015, "s": 2982, "text": "\n 44 Lectures \n 3 hours \n" }, { "code": null, "e": 3034, "s": 3015, "text": " Arnab Chakraborty" }, { "code": null, "e": 3041, "s": 3034, "text": " Print" }, { "code": null, "e": 3052, "s": 3041, "text": " Add Notes" } ]
Objects Counting by Estimating a Density Map With Convolutional Neural Networks | by Tomasz Bonus | Towards Data Science
Written by Tomasz Bonus and Tomasz Golan. Counting objects in images is one of the fundamental tasks in computer vision. It has a lot of applications, in particular in: microbiology (e.g. counting bacterial colonies in a Petri dish); surveillance (e.g. counting people); agriculture (e.g. counting fruits or vegetables); medicine (e.g. counting tumor cells in histopathological images); wildlife conservation (e.g. counting animals). The task of counting objects is relatively easy for us, people, but it can be challenging for a computer vision algorithm, especially when different instances of an object vary significantly in terms of shape, color, texture or size. If a problem is complex from an algorithmic point of view but simple from a human point of view, machine learning methods can be an answer. Currently, deep learning (DL) methods provide the state-of-the-art performance in digital image processing. However, they require collecting a lot of annotated data, which is usually time consuming and prone to labelling errors. The common way of count objects using DL is to first detect them using convolutional neural networks, like e.g. GCNet [1], and then count all found instances. It is effective but requires bounding box annotations, like presented in Fig. 1 (left), which are hard to obtain. To overcome this issue, alternative approaches leverage point-like annotations of objects positions (see Fig. 1 right), which are much cheaper to collect. In this article we describe our studies on counting objects in images with fully convolutional networks (FCN), trained on data with point-like annotations. In the next sections details on a model we used are presented together with the implementation, considered datasets, and results we obtained. We started with the approach described in [7]. The main idea is to count objects indirectly by estimating a density map. The first step is to prepare training samples, so that for every image there is a corresponding density map. Let’s consider an example shown in Fig. 2. The image presented in Fig. 2 (left) is annotated with points in the positions of pedestrians heads (Fig. 2 right). A density map is obtained by applying a convolution with a Gaussian kernel (and normalized so that integrating it gives the number of objects). The density map for the example above is presented in Fig. 3. Now, the goal is to train a fully convolutional network to map an image to a density map, which can be later integrated to get the number of objects. So far, we have considered two FCN architectures: U-Net [8] and Fully Convolutional Regression Network (FCRN) [7]. U-Net is a widely used FCN for image segmentation, very often applied to biomedical data. It has autoencoder-like structure (see Fig. 4). An input image is processed by a block of convolutional layers, followed by a pooling layer (downsampling). This procedure is repeated several times on subsequent blocks outputs, which is demonstrated on the left side of Fig. 4. This way the network encodes (and compresses) the key features of an input image. The second part of U-Net is symmetric, but pooling layers are replaced with upsampling, so that an output dimensions match the size of an input image. The information from higher resolution layers in the downsampling part is passed to corresponding layers in the upsampling part, which allows to reuse learned higher level features to decode contracted layers more precisely. Fully Convolutional Regression Network (FCRN) was proposed in [7]. The architecture is very similar to U-Net. The main difference is that the information from higher resolution layers from downsampling part is not passed directly to the corresponding layers in upsampling part. In the paper two networks are proposed: FCRN-A and FCRN-B, which differ in downsampling intensity. While FCRN-A perform pooling every convolutional layer, FCRN-B does that every second layer. Our implementation can be found here. It is based on the code from Weidi Xi’s GitHub, but PyTorch is used instead of Keras. Currently, U-Net and FCRN-A are implemented. They both use three downsampling and three upsampling convolutional blocks with fixed filter size 3×3. By default there are two convolutional layers in each block for U-Net, and one for FCRN-A. For U-Net we keep constant number of filters for all convolutional layers, and for FCRN-A we increase this number every subsequent layer to compensate for the loss of higher resolution information caused by pooling (which is not passed directly as in the case of U-Net). The basic piece to build both U-Net and FCRN is a convolutional block, consisting of a convolutional layer, batch normalization, and activation function: The conv_block function creates N convolutional layers with OUT number of filters with ReLU activation function and batch normalization applied in each layer. The FCRN-A architecture is obtained by stacking multiple such blocks followed by either downsampling (max pooling) or upsampling layers: U-Net also requires to concatenate the output from the downsampling path with the input to the corresponding layer in the upsampling part, which is performed by ConvCat class: The U-Net downsampling part is built in the same way as in the case of FCRN: However, as mentioned above, upsampling exploits ConvCat class: We considered three datasets in our study. They all are annotated with point-like objects positions, so we could use them directly to generate density maps for all images and test the method described above. We provide the get_data.py script to preprocess all considered datasets to a common format stored in HDF5 files. Each entry consists of an image and a corresponding label (a density map) generated with generate_labelfunction: Note, that we set a value of 100 for each object position before applying Gaussian filter, so the results must be properly normalized when integrating a density map to get the number of objects present on an image. For visualization purpose we used higher standard deviation value for density maps presented on images comparing to the one we actually apply for training dataset. Fluorescent cells (FC) dataset is generated by Visual Geometry Group (VGG) with a computational framework from [9]. It can be downloaded from VGG website. An example image along with generated density map is presented in Fig. 5. UCSD dataset [10] contains videos of pedestrians recorded on walkways in the University of California San Diego campus. It is widely used for various problems, such as counting, motion segmentation, and analysis of pedestrians behaviour. It can be downloaded from Statistical Visual Computing Lab website. An example image along with generated density map is presented in Fig. 6. Mall dataset [3–6] was created for crowd counting and profiling. It contains a video recorded by a publicly available webcam. Every frame is annotated with head positions of every pedestrian. It can be downloaded from here. An example image along with generated density map is presented in Fig. 3. The method of counting objects in images by integrating an estimated density map has been already applied to both fluorescent cells and UCSD datasets [11]. We chose mall dataset to be our test dataset for the method. As stated above, two models were tested, namely U-Net and FCRN. Using U-Net we were able to achieve more accurate results so below we present our findings obtained with this architecture. In the table below the summary of our results is presented for each dataset with minimum and maximum numbers of objects in validation sets and the mean absolute error (MAE) we obtained. We used standard definition for MAE: where ti is true and pi is predicted number of objects for i-th sample. Dataset | Min. #objects | Max. #objects | MAE -------------------|---------------|---------------|------ Fluorescent cells | 74 | 317 | 1.89 UCSD | 20 | 47 | 2.27 Mall | 20 | 48 | 2.86 The scatter plots for true (ti) vs predicted (pi) number of objects for each validation sample are presented in Figs. 7–9. As expected, the model handles well relatively simple fluorescent cells dataset despite high number of objects in single image. However, there is much higher deviation when counting pedestrians. This could be happening due to the fact that it is difficult even for human labeler to decide whether person standing behind a plant or just barely visible from behind corner should be counted. This is just the beginning of our research on object counting. We are looking forward to conduct more experiments including trying out different architectures and methods. [1] Cao, Y., Xu, J., Lin, S., Wei, F., & Hu, H. (2019). GCNet: Non-local Networks Meet Squeeze-Excitation Networks and Beyond. arXiv preprint arXiv:1904.11492. [2] Lin, T. Y., Maire, M., Belongie, S., Hays, J., Perona, P., Ramanan, D., ... & Zitnick, C. L. (2014, September). Microsoft coco: Common objects in context. In European conference on computer vision (pp. 740–755). Springer, Cham. [3] Change Loy, C., Gong, S., & Xiang, T. (2013). From semi-supervised to transfer counting of crowds. In Proceedings of the IEEE International Conference on Computer Vision (pp. 2256–2263). [4] Chen, K., Gong, S., Xiang, T., & Change Loy, C. (2013). Cumulative attribute space for age and crowd density estimation. In Proceedings of the IEEE conference on computer vision and pattern recognition (pp. 2467–2474). [5] Loy, C. C., Chen, K., Gong, S., & Xiang, T. (2013). Crowd counting and profiling: Methodology and evaluation. In Modeling, simulation and visual analysis of crowds (pp. 347–382). Springer, New York, NY. [6] Chen, K., Loy, C. C., Gong, S., & Xiang, T. (2012, September). Feature mining for localised crowd counting. In BMVC (Vol. 1, No2, p. 3). [7] Weidi, X., Noble, J. A., & Zisserman, A. (2015). Microscopy cell counting with fully convolutional regression networks. In 1st Deep Learning Workshop, Medical Image Computing and Computer-Assisted Intervention (MICCAI). [8] Ronneberger, O., Fischer, P., & Brox, T. (2015, October). U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image computing and computer-assisted intervention (pp. 234–241). Springer, Cham. [9] Lehmussola, A., Ruusuvuori, P., Selinummi, J., Huttunen, H., & Yli-Harja, O. (2007). Computational framework for simulating fluorescence microscope images with cell populations. IEEE transactions on medical imaging, 26(7), 1010–1016. [10] Chan, A. B., Liang, Z. S. J., & Vasconcelos, N. (2008, June). Privacy preserving crowd monitoring: Counting people without people models or tracking. In 2008 IEEE Conference on Computer Vision and Pattern Recognition (pp. 1–7). IEEE. [11] Lempitsky, V., & Zisserman, A. (2010). Learning to count objects in images. In Advances in neural information processing systems (pp. 1324–1332).
[ { "code": null, "e": 214, "s": 172, "text": "Written by Tomasz Bonus and Tomasz Golan." }, { "code": null, "e": 341, "s": 214, "text": "Counting objects in images is one of the fundamental tasks in computer vision. It has a lot of applications, in particular in:" }, { "code": null, "e": 406, "s": 341, "text": "microbiology (e.g. counting bacterial colonies in a Petri dish);" }, { "code": null, "e": 443, "s": 406, "text": "surveillance (e.g. counting people);" }, { "code": null, "e": 493, "s": 443, "text": "agriculture (e.g. counting fruits or vegetables);" }, { "code": null, "e": 559, "s": 493, "text": "medicine (e.g. counting tumor cells in histopathological images);" }, { "code": null, "e": 606, "s": 559, "text": "wildlife conservation (e.g. counting animals)." }, { "code": null, "e": 980, "s": 606, "text": "The task of counting objects is relatively easy for us, people, but it can be challenging for a computer vision algorithm, especially when different instances of an object vary significantly in terms of shape, color, texture or size. If a problem is complex from an algorithmic point of view but simple from a human point of view, machine learning methods can be an answer." }, { "code": null, "e": 1209, "s": 980, "text": "Currently, deep learning (DL) methods provide the state-of-the-art performance in digital image processing. However, they require collecting a lot of annotated data, which is usually time consuming and prone to labelling errors." }, { "code": null, "e": 1637, "s": 1209, "text": "The common way of count objects using DL is to first detect them using convolutional neural networks, like e.g. GCNet [1], and then count all found instances. It is effective but requires bounding box annotations, like presented in Fig. 1 (left), which are hard to obtain. To overcome this issue, alternative approaches leverage point-like annotations of objects positions (see Fig. 1 right), which are much cheaper to collect." }, { "code": null, "e": 1935, "s": 1637, "text": "In this article we describe our studies on counting objects in images with fully convolutional networks (FCN), trained on data with point-like annotations. In the next sections details on a model we used are presented together with the implementation, considered datasets, and results we obtained." }, { "code": null, "e": 2208, "s": 1935, "text": "We started with the approach described in [7]. The main idea is to count objects indirectly by estimating a density map. The first step is to prepare training samples, so that for every image there is a corresponding density map. Let’s consider an example shown in Fig. 2." }, { "code": null, "e": 2530, "s": 2208, "text": "The image presented in Fig. 2 (left) is annotated with points in the positions of pedestrians heads (Fig. 2 right). A density map is obtained by applying a convolution with a Gaussian kernel (and normalized so that integrating it gives the number of objects). The density map for the example above is presented in Fig. 3." }, { "code": null, "e": 2795, "s": 2530, "text": "Now, the goal is to train a fully convolutional network to map an image to a density map, which can be later integrated to get the number of objects. So far, we have considered two FCN architectures: U-Net [8] and Fully Convolutional Regression Network (FCRN) [7]." }, { "code": null, "e": 3620, "s": 2795, "text": "U-Net is a widely used FCN for image segmentation, very often applied to biomedical data. It has autoencoder-like structure (see Fig. 4). An input image is processed by a block of convolutional layers, followed by a pooling layer (downsampling). This procedure is repeated several times on subsequent blocks outputs, which is demonstrated on the left side of Fig. 4. This way the network encodes (and compresses) the key features of an input image. The second part of U-Net is symmetric, but pooling layers are replaced with upsampling, so that an output dimensions match the size of an input image. The information from higher resolution layers in the downsampling part is passed to corresponding layers in the upsampling part, which allows to reuse learned higher level features to decode contracted layers more precisely." }, { "code": null, "e": 4090, "s": 3620, "text": "Fully Convolutional Regression Network (FCRN) was proposed in [7]. The architecture is very similar to U-Net. The main difference is that the information from higher resolution layers from downsampling part is not passed directly to the corresponding layers in upsampling part. In the paper two networks are proposed: FCRN-A and FCRN-B, which differ in downsampling intensity. While FCRN-A perform pooling every convolutional layer, FCRN-B does that every second layer." }, { "code": null, "e": 4214, "s": 4090, "text": "Our implementation can be found here. It is based on the code from Weidi Xi’s GitHub, but PyTorch is used instead of Keras." }, { "code": null, "e": 4724, "s": 4214, "text": "Currently, U-Net and FCRN-A are implemented. They both use three downsampling and three upsampling convolutional blocks with fixed filter size 3×3. By default there are two convolutional layers in each block for U-Net, and one for FCRN-A. For U-Net we keep constant number of filters for all convolutional layers, and for FCRN-A we increase this number every subsequent layer to compensate for the loss of higher resolution information caused by pooling (which is not passed directly as in the case of U-Net)." }, { "code": null, "e": 4878, "s": 4724, "text": "The basic piece to build both U-Net and FCRN is a convolutional block, consisting of a convolutional layer, batch normalization, and activation function:" }, { "code": null, "e": 5037, "s": 4878, "text": "The conv_block function creates N convolutional layers with OUT number of filters with ReLU activation function and batch normalization applied in each layer." }, { "code": null, "e": 5174, "s": 5037, "text": "The FCRN-A architecture is obtained by stacking multiple such blocks followed by either downsampling (max pooling) or upsampling layers:" }, { "code": null, "e": 5350, "s": 5174, "text": "U-Net also requires to concatenate the output from the downsampling path with the input to the corresponding layer in the upsampling part, which is performed by ConvCat class:" }, { "code": null, "e": 5427, "s": 5350, "text": "The U-Net downsampling part is built in the same way as in the case of FCRN:" }, { "code": null, "e": 5491, "s": 5427, "text": "However, as mentioned above, upsampling exploits ConvCat class:" }, { "code": null, "e": 5699, "s": 5491, "text": "We considered three datasets in our study. They all are annotated with point-like objects positions, so we could use them directly to generate density maps for all images and test the method described above." }, { "code": null, "e": 5925, "s": 5699, "text": "We provide the get_data.py script to preprocess all considered datasets to a common format stored in HDF5 files. Each entry consists of an image and a corresponding label (a density map) generated with generate_labelfunction:" }, { "code": null, "e": 6140, "s": 5925, "text": "Note, that we set a value of 100 for each object position before applying Gaussian filter, so the results must be properly normalized when integrating a density map to get the number of objects present on an image." }, { "code": null, "e": 6304, "s": 6140, "text": "For visualization purpose we used higher standard deviation value for density maps presented on images comparing to the one we actually apply for training dataset." }, { "code": null, "e": 6533, "s": 6304, "text": "Fluorescent cells (FC) dataset is generated by Visual Geometry Group (VGG) with a computational framework from [9]. It can be downloaded from VGG website. An example image along with generated density map is presented in Fig. 5." }, { "code": null, "e": 6913, "s": 6533, "text": "UCSD dataset [10] contains videos of pedestrians recorded on walkways in the University of California San Diego campus. It is widely used for various problems, such as counting, motion segmentation, and analysis of pedestrians behaviour. It can be downloaded from Statistical Visual Computing Lab website. An example image along with generated density map is presented in Fig. 6." }, { "code": null, "e": 7211, "s": 6913, "text": "Mall dataset [3–6] was created for crowd counting and profiling. It contains a video recorded by a publicly available webcam. Every frame is annotated with head positions of every pedestrian. It can be downloaded from here. An example image along with generated density map is presented in Fig. 3." }, { "code": null, "e": 7428, "s": 7211, "text": "The method of counting objects in images by integrating an estimated density map has been already applied to both fluorescent cells and UCSD datasets [11]. We chose mall dataset to be our test dataset for the method." }, { "code": null, "e": 7616, "s": 7428, "text": "As stated above, two models were tested, namely U-Net and FCRN. Using U-Net we were able to achieve more accurate results so below we present our findings obtained with this architecture." }, { "code": null, "e": 7802, "s": 7616, "text": "In the table below the summary of our results is presented for each dataset with minimum and maximum numbers of objects in validation sets and the mean absolute error (MAE) we obtained." }, { "code": null, "e": 7839, "s": 7802, "text": "We used standard definition for MAE:" }, { "code": null, "e": 7911, "s": 7839, "text": "where ti is true and pi is predicted number of objects for i-th sample." }, { "code": null, "e": 8207, "s": 7911, "text": " Dataset | Min. #objects | Max. #objects | MAE -------------------|---------------|---------------|------ Fluorescent cells | 74 | 317 | 1.89 UCSD | 20 | 47 | 2.27 Mall | 20 | 48 | 2.86" }, { "code": null, "e": 8719, "s": 8207, "text": "The scatter plots for true (ti) vs predicted (pi) number of objects for each validation sample are presented in Figs. 7–9. As expected, the model handles well relatively simple fluorescent cells dataset despite high number of objects in single image. However, there is much higher deviation when counting pedestrians. This could be happening due to the fact that it is difficult even for human labeler to decide whether person standing behind a plant or just barely visible from behind corner should be counted." }, { "code": null, "e": 8891, "s": 8719, "text": "This is just the beginning of our research on object counting. We are looking forward to conduct more experiments including trying out different architectures and methods." }, { "code": null, "e": 9051, "s": 8891, "text": "[1] Cao, Y., Xu, J., Lin, S., Wei, F., & Hu, H. (2019). GCNet: Non-local Networks Meet Squeeze-Excitation Networks and Beyond. arXiv preprint arXiv:1904.11492." }, { "code": null, "e": 9283, "s": 9051, "text": "[2] Lin, T. Y., Maire, M., Belongie, S., Hays, J., Perona, P., Ramanan, D., ... & Zitnick, C. L. (2014, September). Microsoft coco: Common objects in context. In European conference on computer vision (pp. 740–755). Springer, Cham." }, { "code": null, "e": 9474, "s": 9283, "text": "[3] Change Loy, C., Gong, S., & Xiang, T. (2013). From semi-supervised to transfer counting of crowds. In Proceedings of the IEEE International Conference on Computer Vision (pp. 2256–2263)." }, { "code": null, "e": 9697, "s": 9474, "text": "[4] Chen, K., Gong, S., Xiang, T., & Change Loy, C. (2013). Cumulative attribute space for age and crowd density estimation. In Proceedings of the IEEE conference on computer vision and pattern recognition (pp. 2467–2474)." }, { "code": null, "e": 9904, "s": 9697, "text": "[5] Loy, C. C., Chen, K., Gong, S., & Xiang, T. (2013). Crowd counting and profiling: Methodology and evaluation. In Modeling, simulation and visual analysis of crowds (pp. 347–382). Springer, New York, NY." }, { "code": null, "e": 10045, "s": 9904, "text": "[6] Chen, K., Loy, C. C., Gong, S., & Xiang, T. (2012, September). Feature mining for localised crowd counting. In BMVC (Vol. 1, No2, p. 3)." }, { "code": null, "e": 10269, "s": 10045, "text": "[7] Weidi, X., Noble, J. A., & Zisserman, A. (2015). Microscopy cell counting with fully convolutional regression networks. In 1st Deep Learning Workshop, Medical Image Computing and Computer-Assisted Intervention (MICCAI)." }, { "code": null, "e": 10517, "s": 10269, "text": "[8] Ronneberger, O., Fischer, P., & Brox, T. (2015, October). U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image computing and computer-assisted intervention (pp. 234–241). Springer, Cham." }, { "code": null, "e": 10755, "s": 10517, "text": "[9] Lehmussola, A., Ruusuvuori, P., Selinummi, J., Huttunen, H., & Yli-Harja, O. (2007). Computational framework for simulating fluorescence microscope images with cell populations. IEEE transactions on medical imaging, 26(7), 1010–1016." }, { "code": null, "e": 10994, "s": 10755, "text": "[10] Chan, A. B., Liang, Z. S. J., & Vasconcelos, N. (2008, June). Privacy preserving crowd monitoring: Counting people without people models or tracking. In 2008 IEEE Conference on Computer Vision and Pattern Recognition (pp. 1–7). IEEE." } ]
How to display an image with rounded corners on iOS App using Swift?
To make an image with round corners or to make any view or button or any UI element with round corners in swift, we need to access the corner radius property of its layer. Every UI element in iOS is based on a layer. First of all, let’s add an UIImageView Object in our storyboard. Or let’s create one programmatically. Below is a function that will programmatically create an image view and add an image to it. func addImage(imageName img: String) { let imageView = UIImageView() imageView.frame = CGRect(x: 10, y: 20, width: 200, height: 200) imageView.contentMode = . scaleAspectFill if let newImage = UIImage(named: img) { imageView.image = newImage } self.view.addSubview(imageView) } Let’s suppose the original image that we want to add in our application is − in our viewDidLoad, let’s call the code below to add this image to our application. Below is how it looks without any change to its corner property. Now, let’s add the corner radius property to our existing code and see how it looks. imageView.layer.cornerRadius = 10 imageView.clipsToBounds = true Add these two lines in the addImage function, right above the addSubview method. When we run the application this is how it looks now − We can also create an extension of UIImageView and use the same like as shown below, which again produces the same result. extension UIImageView { func makeRoundCorners(byRadius rad: CGFloat) { self.layer.cornerRadius = rad self.clipsToBounds = true } } imageView.makeRoundCorners(byRadius: 20)
[ { "code": null, "e": 1279, "s": 1062, "text": "To make an image with round corners or to make any view or button or any UI element with round corners in swift, we need to access the corner radius property of its layer. Every UI element in iOS is based on a layer." }, { "code": null, "e": 1382, "s": 1279, "text": "First of all, let’s add an UIImageView Object in our storyboard. Or let’s create one programmatically." }, { "code": null, "e": 1474, "s": 1382, "text": "Below is a function that will programmatically create an image view and add an image to it." }, { "code": null, "e": 1776, "s": 1474, "text": "func addImage(imageName img: String) {\n let imageView = UIImageView()\n imageView.frame = CGRect(x: 10, y: 20, width: 200, height: 200)\n imageView.contentMode = . scaleAspectFill\n if let newImage = UIImage(named: img) {\n imageView.image = newImage\n }\n self.view.addSubview(imageView)\n}" }, { "code": null, "e": 1853, "s": 1776, "text": "Let’s suppose the original image that we want to add in our application is −" }, { "code": null, "e": 1937, "s": 1853, "text": "in our viewDidLoad, let’s call the code below to add this image to our application." }, { "code": null, "e": 2002, "s": 1937, "text": "Below is how it looks without any change to its corner property." }, { "code": null, "e": 2087, "s": 2002, "text": "Now, let’s add the corner radius property to our existing code and see how it looks." }, { "code": null, "e": 2152, "s": 2087, "text": "imageView.layer.cornerRadius = 10\nimageView.clipsToBounds = true" }, { "code": null, "e": 2288, "s": 2152, "text": "Add these two lines in the addImage function, right above the addSubview method. When we run the application this is how it looks now −" }, { "code": null, "e": 2411, "s": 2288, "text": "We can also create an extension of UIImageView and use the same like as shown below, which again produces the same result." }, { "code": null, "e": 2560, "s": 2411, "text": "extension UIImageView {\n func makeRoundCorners(byRadius rad: CGFloat) {\n self.layer.cornerRadius = rad\n self.clipsToBounds = true\n }\n}" }, { "code": null, "e": 2601, "s": 2560, "text": "imageView.makeRoundCorners(byRadius: 20)" } ]
Count Triplets | Practice | GeeksforGeeks
Given a sorted linked list of distinct nodes (no two nodes have the same data) and an integer X. Count distinct triplets in the list that sum up to given integer X. Note: The Linked List can be sorted in any order. Example 1: Input: LinkedList: 1->2->4->5->6->8->9, X = 17 Output: 2 Explanation: Distinct triplets are (2, 6, 9) and (4, 5, 8) which have sum equal to X i.e 17. Example 2: Input: LinkedList: 1->2->4->5->6->8->9, X = 15 Output: 5 Explanation: (1, 5, 9), (1, 6, 8), (2, 4, 9), (2, 5, 8), (4, 5, 6) are the distinct triplets Your Task: You don't need to read input or print anything. Complete the function countTriplets() which takes a head reference and X as input parameters and returns the triplet count Expected Time Complexity: O(N2) Expected Auxiliary Space: O(N) Constraints: 1 ≤ Number of Nodes ≤ 103 1 ≤ Node value ≤ 104 0 vikasrajpoot4794 days ago //Using two pointer approach int solve(vector<int>arr,int x){ sort(arr.begin(),arr.end()); int count=0; for(int i=0;i<arr.size();i++) { int check=arr[i]; int j=i+1; int k=arr.size()-1; while(j<k) { if(check+arr[j]+arr[k]==x) { count++; j++; k--; } else if(check+arr[j]+arr[k]<x) { j++; } else{ k--; } } } return count;}int countTriplets(struct Node* head, int x) { Node*temp=head;vector<int>a;while(temp!=NULL){ a.push_back(temp->data); temp=temp->next;}int ans=solve(a,x);return ans;} +1 hr061 month ago int total(struct Node* head) { int counter = 0; Node* curr = head; while(curr != NULL) { counter++; curr = curr->next; } return counter; } int countTriplets(struct Node* head, int K) { // code here. // push all the elements in an array int n = total(head); int arr[n]; // dynamically allocating an array Node* curr = head; int itr = 0; while(curr != NULL) { arr[itr++] = curr->data; curr = curr->next; } sort(arr,arr+n); vector<vector<int>> ans; for(int i = 0; i<n; i++) { int target = K - arr[i]; int start = i + 1; int end = n - 1; while(start < end) { int sum = arr[start] + arr[end]; if(sum < target) { start++; } else if(sum > target) { end--; } else { int x = arr[start]; int y = arr[end]; ans.push_back({arr[i], arr[start], arr[end]}); //for getting different value of triplet while(start < end && arr[start] == x) { start++; } while(start < end && arr[end] == y) { end--; } } } while(i+1 < n && arr[i] == arr[i+1] ) { i++; } } return ans.size(); } 0 gupta2411sumit1 month ago // Easy Solution C++ int countTriplets(struct Node* head, int x) { // code here. struct Node *p = head ; vector<int>v ; while(p!=NULL) { v.push_back(p->data) ; p = p->next ; } int count = 0 ; int n = v.size() ; for( int i = 0 ; i<n-3 ; i++) { int l = i+1 ; int r = n-1 ; while(l<r) { int sum = v[i] + v[l] + v[r] ; if(sum<x) { l++ ; } else if(sum>x) { r-- ; } else{ count++ ; l++ ; r-- ; } } } return count ;} 0 mridulbhaskarabc2 months ago #Time taken: 2.5/14.6 def countTriplets(head,x): # code here new_node = head node_ref = head count = 1 counter = 0 while(new_node.nxt!=None): count +=1 new_node = new_node.nxt new_list = [0]*count for i in range(count): new_list[i]= node_ref.val node_ref = node_ref.nxt new_list.sort() for i in range(count): low = i+1 high = count-1 while (low<high): sum = new_list[i]+new_list[low]+new_list[high] if(sum == x): counter+=1 low+=1 high-=1 elif(sum>x): high-=1 else: low+=1 return counter #Contributed By: Mridul Bhaskar -1 imranwahid4 months ago Easy C++ solution using two pointer approach +1 shyamprakash8075 months ago def countTriplets(head,x): # code here d = dict() d1 = dict() curr = head while curr != None: d[curr.val] = True curr = curr.nxt curr = head c = 0 while curr != None: d[curr.val] -= 1 temp = curr.nxt while temp != None: d[temp.val] -= 1 if d.get(x - curr.val - temp.val,False): l = [curr.val,temp.val,x-curr.val-temp.val] l.sort() l = tuple(l) if d1.get(l,0)==0: c += 1 d1[l] = 1 d[temp.val] += 1 temp = temp.nxt d[curr.val] += 1 curr = curr.nxt return c +1 vijayvargiyarishabh5 months ago //very easy to understand solution using maps with the time complexity of O(n2) and space O(n). int countTriplets(struct Node* head, int x) { // code here. int ans=0; unordered_map<int, bool> m; struct Node* temp1=head; struct Node* temp2=head; while(temp1!=NULL) { m[temp1->data]=true; temp1=temp1->next; } temp1=head; while(temp1!=NULL) { int a=temp1->data; temp2=temp1->next; while(temp2!=NULL) { int b=temp2->data; int t=x-(a+b); // This if statement is important because it will avoid repeating cases if(m[t] and t!=a and t!=b and t>a and t>b) ans++; temp2=temp2->next; } temp1=temp1->next; } return ans;} 0 dflag445 months ago int countTriplets(struct Node* head, int x) { if(!head)return 0; stack<int>st; int count=0; Node*n1=head; while(n1) { st.push(n1->data); n1=n1->next; } Node*rev=new Node(st.top()); st.pop(); Node*tmp=rev; while(!st.empty()) { tmp->next=new Node(st.top()); st.pop(); tmp=tmp->next; } n1=head; while(n1->next->next) { Node*n2=n1->next; Node*n3=rev; while(n2->data<n3->data){ int sum=n1->data+n2->data+n3->data; if(sum==x) { count++; n2=n2->next; //break; } else if(sum>x)n3=n3->next; else if(sum<x)n2=n2->next; } n1=n1->next; } return count; } 0 sunil gudivada 15 months ago Java Solution with clear explanation class Solve { static int countTriplets(Node head, int x) { // Convert linkedList to arraylist ArrayList<Integer> list = new ArrayList<>(); while(head!= null){ list.add(head.data); head = head.next; } int res = 0; // Sort the elements Collections.sort(list); for(int i=0;i<list.size()-2;i++){ // HashSet to maintain if the required sum exist in the HashSet<Integer> set = new HashSet<>(); // From this problem reduced to 2 Sum Problem int sum = x - list.get(i); // Check the two sum problem from the 1 element next to i for(int j=i+1;j<list.size();j++){ int current = list.get(j); // If set contains our required sum, increment the result. if(set.contains(sum-current)){ res++; } // Add the current element to the set set.add(current); } // additional step to clear the set after the iteration set.clear(); } return res; } } +2 tushargupta19995 months ago int countTriplets(struct Node* head, int x) { unordered_set<int> seen; int ans = 0; for(auto a=head; a; a = a->next) { for(auto b=a->next; b; b = b->next) { if(seen.find(x - a->data - b->data) != seen.end()) ans++; } seen.insert(a->data); } return ans; } 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": 441, "s": 226, "text": "Given a sorted linked list of distinct nodes (no two nodes have the same data) and an integer X. Count distinct triplets in the list that sum up to given integer X.\nNote: The Linked List can be sorted in any order." }, { "code": null, "e": 452, "s": 441, "text": "Example 1:" }, { "code": null, "e": 603, "s": 452, "text": "Input: LinkedList: 1->2->4->5->6->8->9, X = 17\nOutput: 2\nExplanation: Distinct triplets are (2, 6, 9) \nand (4, 5, 8) which have sum equal to X i.e 17." }, { "code": null, "e": 615, "s": 603, "text": "\nExample 2:" }, { "code": null, "e": 767, "s": 615, "text": "Input: LinkedList: 1->2->4->5->6->8->9, X = 15\nOutput: 5\nExplanation: (1, 5, 9), (1, 6, 8), (2, 4, 9), \n(2, 5, 8), (4, 5, 6) are the distinct triplets\n" }, { "code": null, "e": 951, "s": 767, "text": "Your Task: \nYou don't need to read input or print anything. Complete the function countTriplets() which takes a head reference and X as input parameters and returns the triplet count" }, { "code": null, "e": 1014, "s": 951, "text": "Expected Time Complexity: O(N2)\nExpected Auxiliary Space: O(N)" }, { "code": null, "e": 1075, "s": 1014, "text": "Constraints:\n1 ≤ Number of Nodes ≤ 103 \n1 ≤ Node value ≤ 104" }, { "code": null, "e": 1077, "s": 1075, "text": "0" }, { "code": null, "e": 1103, "s": 1077, "text": "vikasrajpoot4794 days ago" }, { "code": null, "e": 1132, "s": 1103, "text": "//Using two pointer approach" }, { "code": null, "e": 1796, "s": 1132, "text": "int solve(vector<int>arr,int x){ sort(arr.begin(),arr.end()); int count=0; for(int i=0;i<arr.size();i++) { int check=arr[i]; int j=i+1; int k=arr.size()-1; while(j<k) { if(check+arr[j]+arr[k]==x) { count++; j++; k--; } else if(check+arr[j]+arr[k]<x) { j++; } else{ k--; } } } return count;}int countTriplets(struct Node* head, int x) { Node*temp=head;vector<int>a;while(temp!=NULL){ a.push_back(temp->data); temp=temp->next;}int ans=solve(a,x);return ans;}" }, { "code": null, "e": 1799, "s": 1796, "text": "+1" }, { "code": null, "e": 1815, "s": 1799, "text": "hr061 month ago" }, { "code": null, "e": 3412, "s": 1815, "text": "int total(struct Node* head)\n{\n int counter = 0;\n Node* curr = head;\n \n while(curr != NULL)\n {\n counter++;\n curr = curr->next;\n }\n \n return counter;\n}\nint countTriplets(struct Node* head, int K) \n{ \n // code here.\n // push all the elements in an array\n int n = total(head);\n int arr[n]; // dynamically allocating an array\n \n Node* curr = head;\n \n int itr = 0;\n while(curr != NULL)\n {\n arr[itr++] = curr->data;\n curr = curr->next;\n }\n \n sort(arr,arr+n);\n \n vector<vector<int>> ans;\n \n for(int i = 0; i<n; i++)\n {\n \n int target = K - arr[i];\n int start = i + 1;\n int end = n - 1;\n \n while(start < end)\n {\n int sum = arr[start] + arr[end];\n \n if(sum < target)\n {\n start++;\n }\n else if(sum > target)\n {\n end--;\n }\n else\n {\n int x = arr[start];\n int y = arr[end];\n \n ans.push_back({arr[i], arr[start], arr[end]});\n \n //for getting different value of triplet \n \n while(start < end && arr[start] == x)\n {\n start++;\n }\n \n while(start < end && arr[end] == y)\n {\n end--;\n }\n }\n }\n \n while(i+1 < n && arr[i] == arr[i+1] )\n {\n i++;\n }\n \n }\n \n return ans.size();\n \n}" }, { "code": null, "e": 3414, "s": 3412, "text": "0" }, { "code": null, "e": 3440, "s": 3414, "text": "gupta2411sumit1 month ago" }, { "code": null, "e": 3462, "s": 3440, "text": "// Easy Solution C++ " }, { "code": null, "e": 4077, "s": 3462, "text": "int countTriplets(struct Node* head, int x) { // code here. struct Node *p = head ; vector<int>v ; while(p!=NULL) { v.push_back(p->data) ; p = p->next ; } int count = 0 ; int n = v.size() ; for( int i = 0 ; i<n-3 ; i++) { int l = i+1 ; int r = n-1 ; while(l<r) { int sum = v[i] + v[l] + v[r] ; if(sum<x) { l++ ; } else if(sum>x) { r-- ; } else{ count++ ; l++ ; r-- ; } } } return count ;} " }, { "code": null, "e": 4079, "s": 4077, "text": "0" }, { "code": null, "e": 4108, "s": 4079, "text": "mridulbhaskarabc2 months ago" }, { "code": null, "e": 4130, "s": 4108, "text": "#Time taken: 2.5/14.6" }, { "code": null, "e": 4856, "s": 4130, "text": "def countTriplets(head,x):\n # code here\n new_node = head\n node_ref = head\n count = 1\n counter = 0\n \n while(new_node.nxt!=None):\n count +=1\n new_node = new_node.nxt\n new_list = [0]*count\n \n \n for i in range(count):\n new_list[i]= node_ref.val\n node_ref = node_ref.nxt\n new_list.sort()\n for i in range(count):\n low = i+1\n high = count-1\n while (low<high):\n sum = new_list[i]+new_list[low]+new_list[high]\n if(sum == x):\n counter+=1\n low+=1\n high-=1\n elif(sum>x):\n high-=1\n else:\n low+=1\n \n return counter" }, { "code": null, "e": 4888, "s": 4856, "text": "#Contributed By: Mridul Bhaskar" }, { "code": null, "e": 4891, "s": 4888, "text": "-1" }, { "code": null, "e": 4914, "s": 4891, "text": "imranwahid4 months ago" }, { "code": null, "e": 4959, "s": 4914, "text": "Easy C++ solution using two pointer approach" }, { "code": null, "e": 4964, "s": 4961, "text": "+1" }, { "code": null, "e": 4992, "s": 4964, "text": "shyamprakash8075 months ago" }, { "code": null, "e": 5639, "s": 4992, "text": "def countTriplets(head,x): # code here d = dict() d1 = dict() curr = head while curr != None: d[curr.val] = True curr = curr.nxt curr = head c = 0 while curr != None: d[curr.val] -= 1 temp = curr.nxt while temp != None: d[temp.val] -= 1 if d.get(x - curr.val - temp.val,False): l = [curr.val,temp.val,x-curr.val-temp.val] l.sort() l = tuple(l) if d1.get(l,0)==0: c += 1 d1[l] = 1 d[temp.val] += 1 temp = temp.nxt d[curr.val] += 1 curr = curr.nxt return c" }, { "code": null, "e": 5642, "s": 5639, "text": "+1" }, { "code": null, "e": 5674, "s": 5642, "text": "vijayvargiyarishabh5 months ago" }, { "code": null, "e": 5771, "s": 5674, "text": "//very easy to understand solution using maps with the time complexity of O(n2) and space O(n). " }, { "code": null, "e": 6190, "s": 5773, "text": "int countTriplets(struct Node* head, int x) { // code here. int ans=0; unordered_map<int, bool> m; struct Node* temp1=head; struct Node* temp2=head; while(temp1!=NULL) { m[temp1->data]=true; temp1=temp1->next; } temp1=head; while(temp1!=NULL) { int a=temp1->data; temp2=temp1->next; while(temp2!=NULL) { int b=temp2->data; int t=x-(a+b);" }, { "code": null, "e": 6412, "s": 6192, "text": " // This if statement is important because it will avoid repeating cases if(m[t] and t!=a and t!=b and t>a and t>b) ans++; temp2=temp2->next; } temp1=temp1->next; } return ans;} " }, { "code": null, "e": 6414, "s": 6412, "text": "0" }, { "code": null, "e": 6434, "s": 6414, "text": "dflag445 months ago" }, { "code": null, "e": 7187, "s": 6434, "text": "int countTriplets(struct Node* head, int x) { if(!head)return 0; stack<int>st; int count=0; Node*n1=head; while(n1) { st.push(n1->data); n1=n1->next; } Node*rev=new Node(st.top()); st.pop(); Node*tmp=rev; while(!st.empty()) { tmp->next=new Node(st.top()); st.pop(); tmp=tmp->next; } n1=head; while(n1->next->next) { Node*n2=n1->next; Node*n3=rev; while(n2->data<n3->data){ int sum=n1->data+n2->data+n3->data; if(sum==x) { count++; n2=n2->next; //break; } else if(sum>x)n3=n3->next; else if(sum<x)n2=n2->next; } n1=n1->next; } return count; } " }, { "code": null, "e": 7189, "s": 7187, "text": "0" }, { "code": null, "e": 7218, "s": 7189, "text": "sunil gudivada 15 months ago" }, { "code": null, "e": 7255, "s": 7218, "text": "Java Solution with clear explanation" }, { "code": null, "e": 8557, "s": 7259, "text": "class Solve\n{\n static int countTriplets(Node head, int x) \n { \n // Convert linkedList to arraylist\n ArrayList<Integer> list = new ArrayList<>();\n while(head!= null){\n list.add(head.data);\n head = head.next;\n }\n \n int res = 0;\n \n // Sort the elements\n Collections.sort(list);\n \n for(int i=0;i<list.size()-2;i++){\n \n // HashSet to maintain if the required sum exist in the \n HashSet<Integer> set = new HashSet<>();\n \n // From this problem reduced to 2 Sum Problem\n int sum = x - list.get(i);\n \n // Check the two sum problem from the 1 element next to i\n for(int j=i+1;j<list.size();j++){\n int current = list.get(j);\n \n // If set contains our required sum, increment the result.\n if(set.contains(sum-current)){\n res++;\n }\n \n // Add the current element to the set\n set.add(current);\n }\n \n // additional step to clear the set after the iteration\n set.clear();\n }\n \n return res;\n } \n}" }, { "code": null, "e": 8562, "s": 8559, "text": "+2" }, { "code": null, "e": 8590, "s": 8562, "text": "tushargupta19995 months ago" }, { "code": null, "e": 8903, "s": 8590, "text": "int countTriplets(struct Node* head, int x) { \n unordered_set<int> seen;\n int ans = 0;\n for(auto a=head; a; a = a->next) {\n for(auto b=a->next; b; b = b->next) {\n if(seen.find(x - a->data - b->data) != seen.end()) ans++;\n }\n seen.insert(a->data);\n }\n return ans;\n} " }, { "code": null, "e": 9049, "s": 8903, "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": 9085, "s": 9049, "text": " Login to access your submissions. " }, { "code": null, "e": 9095, "s": 9085, "text": "\nProblem\n" }, { "code": null, "e": 9105, "s": 9095, "text": "\nContest\n" }, { "code": null, "e": 9168, "s": 9105, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 9316, "s": 9168, "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": 9524, "s": 9316, "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": 9630, "s": 9524, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
WML - Environment
To develop WAP applications, you will need the following: A WAP enabled Web Server: You can enable your Apache or Microsoft IIS to serve all the WAP client request. A WAP enabled Web Server: You can enable your Apache or Microsoft IIS to serve all the WAP client request. A WAP Gateway Simulator: This is required to interact to your WAP server. A WAP Gateway Simulator: This is required to interact to your WAP server. A WAP Phone Simulator: This is required to test your WAP Pages and to show all the WAP pages. A WAP Phone Simulator: This is required to test your WAP Pages and to show all the WAP pages. You can write your WAP pages using the following languages: Wireless Markup Language(WML) to develop WAP application. WML Script to enhance the functionality of WAP application. In normal web applications, MIME type is set to text/html, designating normal HTML code. Images, on the other hand, could be specified as image/gif or image/jpeg, for instance. With this content type specification, the web browser knows the data type that the web server returns. To make your Apache WAP compatible, you have nothing to do very much. You simply need to add support for the MIME types and extensions listed below. Assuming you have Apache Web server installed on your machine. So now we will tell you how to enable WAP functionality in your Apache web server. So locate Apache's file httpd.conf which is usually in /etc/httpd/conf, and add the following lines to the file and restart the server: AddType text/vnd.wap.wml .wml AddType text/vnd.wap.wmlscript .wmls AddType application/vnd.wap.wmlc .wmlc AddType application/vnd.wap.wmlscriptc .wmlsc AddType image/vnd.wap.wbmp .wbmp In dynamic applications, the MIME type must be set on the fly, whereas in static WAP applications the web server must be configured appropriately. To configure a Microsoft IIS server to deliver WAP content, you need to perform the following: Open the Internet Service Manager console and expand the tree to view your Web site entry. You can add the WAP MIME types to a whole server or individual directories. Open the Properties dialog box by right-clicking the appropriate server or directory, then choose Properties from the menu. From the Properties dialog, choose the HTTP Headers tab, then select the File Types button at the bottom right. For each MIME type listed earlier in the above table, supply the extension with or without the dot (it will be automatically added for you), then click OK in the Properties dialog box to accept your changes. There are many WAP Gateway Simulator available on the Internet so download any of them and install on your PC. You would need to run this gateway before starting WAP Mobile simulator. WAP Gateway will take your request and will pass it to the Web Server and whatever response will be received from the Web server that will be passed to the Mobile Simulator. You can download it from Nokia web site: Nokia WAP Gateway simulator - Download Nokia WAP Gateway simulator. Nokia WAP Gateway simulator - Download Nokia WAP Gateway simulator. There are many WAP Simulator available on the Internet so download any of them and install on your PC which you will use as a WAP client. Here are popular links to download simulator: Nokia WAP simulator - Download Nokia WAP simulator. Nokia WAP simulator - Download Nokia WAP simulator. WinWAP simulator - Download WinWAP browser from their official website. WinWAP simulator - Download WinWAP browser from their official website. NOTE: If you have WAP enabled phone then you do not need to install this simulator. But while doing development it is more convenient and economic to use a simulator. I am giving this section just for your reference, if you are not interested then you can skip this section. The figure below shows the WAP programming model. Note the similarities with the Internet model. Without the WAP Gateway/Proxy the two models would have been practically identical. WAP Gateway/Proxy is the entity that connects the wireless domain with the Internet. You should make a note that the request that is sent from the wireless client to the WAP Gateway/Proxy uses the Wireless Session Protocol (WSP). In its essence, WSP is a binary version of HTTP. A markup language - the Wireless Markup Language (WML) has been adapted to develop optimized WAP applications. In order to save valuable bandwidth in the wireless network, WML can be encoded into a compact binary format. Encoding WML is one of the tasks performed by the WAP Gateway/Proxy. When it comes to actual use, WAP works like this: The user selects an option on their mobile device that has a URL with Wireless Markup language (WML) content assigned to it. The user selects an option on their mobile device that has a URL with Wireless Markup language (WML) content assigned to it. The phone sends the URL request via the phone network to a WAP gateway, using the binary encoded WAP protocol. The phone sends the URL request via the phone network to a WAP gateway, using the binary encoded WAP protocol. The gateway translates this WAP request into a conventional HTTP request for the specified URL, and sends it on to the Internet. The gateway translates this WAP request into a conventional HTTP request for the specified URL, and sends it on to the Internet. The appropriate Web server picks up the HTTP request. The appropriate Web server picks up the HTTP request. The server processes the request, just as it would any other request. If the URL refers to a static WML file, the server delivers it. If a CGI script is requested, it is processed and the content returned as usual. The server processes the request, just as it would any other request. If the URL refers to a static WML file, the server delivers it. If a CGI script is requested, it is processed and the content returned as usual. The Web server adds the HTTP header to the WML content and returns it to the gateway. The Web server adds the HTTP header to the WML content and returns it to the gateway. The WAP gateway compiles the WML into binary form. The WAP gateway compiles the WML into binary form. The gateway then sends the WML response back to the phone. The gateway then sends the WML response back to the phone. The phone receives the WML via the WAP protocol. The phone receives the WML via the WAP protocol. The micro-browser processes the WML and displays the content on the screen. The micro-browser processes the WML and displays the content on the screen. Print Add Notes Bookmark this page
[ { "code": null, "e": 1997, "s": 1939, "text": "To develop WAP applications, you will need the following:" }, { "code": null, "e": 2104, "s": 1997, "text": "A WAP enabled Web Server: You can enable your Apache or Microsoft IIS to serve all the WAP client request." }, { "code": null, "e": 2211, "s": 2104, "text": "A WAP enabled Web Server: You can enable your Apache or Microsoft IIS to serve all the WAP client request." }, { "code": null, "e": 2285, "s": 2211, "text": "A WAP Gateway Simulator: This is required to interact to your WAP server." }, { "code": null, "e": 2359, "s": 2285, "text": "A WAP Gateway Simulator: This is required to interact to your WAP server." }, { "code": null, "e": 2453, "s": 2359, "text": "A WAP Phone Simulator: This is required to test your WAP Pages and to show all the WAP pages." }, { "code": null, "e": 2547, "s": 2453, "text": "A WAP Phone Simulator: This is required to test your WAP Pages and to show all the WAP pages." }, { "code": null, "e": 2607, "s": 2547, "text": "You can write your WAP pages using the following languages:" }, { "code": null, "e": 2665, "s": 2607, "text": "Wireless Markup Language(WML) to develop WAP application." }, { "code": null, "e": 2725, "s": 2665, "text": "WML Script to enhance the functionality of WAP application." }, { "code": null, "e": 3005, "s": 2725, "text": "In normal web applications, MIME type is set to text/html, designating normal HTML code. Images, on the other hand, could be specified as image/gif or image/jpeg, for instance. With this content type specification, the web browser knows the data type that the web server returns." }, { "code": null, "e": 3154, "s": 3005, "text": "To make your Apache WAP compatible, you have nothing to do very much. You simply need to add support for the MIME types and extensions listed below." }, { "code": null, "e": 3301, "s": 3154, "text": "Assuming you have Apache Web server installed on your machine. So now we will tell you how to enable WAP functionality in your Apache web server." }, { "code": null, "e": 3437, "s": 3301, "text": "So locate Apache's file httpd.conf which is usually in /etc/httpd/conf, and add the following lines to the file and restart the server:" }, { "code": null, "e": 3622, "s": 3437, "text": "AddType text/vnd.wap.wml .wml\nAddType text/vnd.wap.wmlscript .wmls\nAddType application/vnd.wap.wmlc .wmlc\nAddType application/vnd.wap.wmlscriptc .wmlsc\nAddType image/vnd.wap.wbmp .wbmp" }, { "code": null, "e": 3769, "s": 3622, "text": "In dynamic applications, the MIME type must be set on the fly, whereas in static WAP applications the web server must be configured appropriately." }, { "code": null, "e": 3864, "s": 3769, "text": "To configure a Microsoft IIS server to deliver WAP content, you need to perform the following:" }, { "code": null, "e": 4031, "s": 3864, "text": "Open the Internet Service Manager console and expand the tree to view your Web site entry. You can add the WAP MIME types to a whole server or individual directories." }, { "code": null, "e": 4155, "s": 4031, "text": "Open the Properties dialog box by right-clicking the appropriate server or directory, then choose Properties from the menu." }, { "code": null, "e": 4267, "s": 4155, "text": "From the Properties dialog, choose the HTTP Headers tab, then select the File Types button at the bottom right." }, { "code": null, "e": 4475, "s": 4267, "text": "For each MIME type listed earlier in the above table, supply the extension with or without the dot (it will be automatically added for you), then click OK in the Properties dialog box to accept your changes." }, { "code": null, "e": 4659, "s": 4475, "text": "There are many WAP Gateway Simulator available on the Internet so download any of them and install on your PC. You would need to run this gateway before starting WAP Mobile simulator." }, { "code": null, "e": 4833, "s": 4659, "text": "WAP Gateway will take your request and will pass it to the Web Server and whatever response will be received from the Web server that will be passed to the Mobile Simulator." }, { "code": null, "e": 4874, "s": 4833, "text": "You can download it from Nokia web site:" }, { "code": null, "e": 4943, "s": 4874, "text": "Nokia WAP Gateway simulator - Download Nokia WAP Gateway simulator." }, { "code": null, "e": 5012, "s": 4943, "text": "Nokia WAP Gateway simulator - Download Nokia WAP Gateway simulator." }, { "code": null, "e": 5196, "s": 5012, "text": "There are many WAP Simulator available on the Internet so download any of them and install on your PC which you will use as a WAP client. Here are popular links to download simulator:" }, { "code": null, "e": 5249, "s": 5196, "text": "Nokia WAP simulator - Download Nokia WAP simulator." }, { "code": null, "e": 5302, "s": 5249, "text": "Nokia WAP simulator - Download Nokia WAP simulator." }, { "code": null, "e": 5375, "s": 5302, "text": "WinWAP simulator - Download WinWAP browser from their official website." }, { "code": null, "e": 5448, "s": 5375, "text": "WinWAP simulator - Download WinWAP browser from their official website." }, { "code": null, "e": 5616, "s": 5448, "text": "NOTE: If you have WAP enabled phone then you do not need to install this simulator. But while doing development it is more convenient and economic to use a simulator." }, { "code": null, "e": 5724, "s": 5616, "text": "I am giving this section just for your reference, if you are not interested then you can skip this section." }, { "code": null, "e": 5905, "s": 5724, "text": "The figure below shows the WAP programming model. Note the similarities with the Internet model. Without the WAP Gateway/Proxy the two models would have been practically identical." }, { "code": null, "e": 6184, "s": 5905, "text": "WAP Gateway/Proxy is the entity that connects the wireless domain with the Internet. You should make a note that the request that is sent from the wireless client to the WAP Gateway/Proxy uses the Wireless Session Protocol (WSP). In its essence, WSP is a binary version of HTTP." }, { "code": null, "e": 6474, "s": 6184, "text": "A markup language - the Wireless Markup Language (WML) has been adapted to develop optimized WAP applications. In order to save valuable bandwidth in the wireless network, WML can be encoded into a compact binary format. Encoding WML is one of the tasks performed by the WAP Gateway/Proxy." }, { "code": null, "e": 6524, "s": 6474, "text": "When it comes to actual use, WAP works like this:" }, { "code": null, "e": 6649, "s": 6524, "text": "The user selects an option on their mobile device that has a URL with Wireless Markup language (WML) content assigned to it." }, { "code": null, "e": 6774, "s": 6649, "text": "The user selects an option on their mobile device that has a URL with Wireless Markup language (WML) content assigned to it." }, { "code": null, "e": 6885, "s": 6774, "text": "The phone sends the URL request via the phone network to a WAP gateway, using the binary encoded WAP protocol." }, { "code": null, "e": 6996, "s": 6885, "text": "The phone sends the URL request via the phone network to a WAP gateway, using the binary encoded WAP protocol." }, { "code": null, "e": 7125, "s": 6996, "text": "The gateway translates this WAP request into a conventional HTTP request for the specified URL, and sends it on to the Internet." }, { "code": null, "e": 7254, "s": 7125, "text": "The gateway translates this WAP request into a conventional HTTP request for the specified URL, and sends it on to the Internet." }, { "code": null, "e": 7308, "s": 7254, "text": "The appropriate Web server picks up the HTTP request." }, { "code": null, "e": 7362, "s": 7308, "text": "The appropriate Web server picks up the HTTP request." }, { "code": null, "e": 7577, "s": 7362, "text": "The server processes the request, just as it would any other request. If the URL refers to a static WML file, the server delivers it. If a CGI script is requested, it is processed and the content returned as usual." }, { "code": null, "e": 7792, "s": 7577, "text": "The server processes the request, just as it would any other request. If the URL refers to a static WML file, the server delivers it. If a CGI script is requested, it is processed and the content returned as usual." }, { "code": null, "e": 7878, "s": 7792, "text": "The Web server adds the HTTP header to the WML content and returns it to the gateway." }, { "code": null, "e": 7964, "s": 7878, "text": "The Web server adds the HTTP header to the WML content and returns it to the gateway." }, { "code": null, "e": 8015, "s": 7964, "text": "The WAP gateway compiles the WML into binary form." }, { "code": null, "e": 8066, "s": 8015, "text": "The WAP gateway compiles the WML into binary form." }, { "code": null, "e": 8125, "s": 8066, "text": "The gateway then sends the WML response back to the phone." }, { "code": null, "e": 8184, "s": 8125, "text": "The gateway then sends the WML response back to the phone." }, { "code": null, "e": 8233, "s": 8184, "text": "The phone receives the WML via the WAP protocol." }, { "code": null, "e": 8282, "s": 8233, "text": "The phone receives the WML via the WAP protocol." }, { "code": null, "e": 8358, "s": 8282, "text": "The micro-browser processes the WML and displays the content on the screen." }, { "code": null, "e": 8434, "s": 8358, "text": "The micro-browser processes the WML and displays the content on the screen." }, { "code": null, "e": 8441, "s": 8434, "text": " Print" }, { "code": null, "e": 8452, "s": 8441, "text": " Add Notes" } ]
Scala and Java Interoperability - GeeksforGeeks
30 Jun, 2020 Java is one of the top programming languages and the JVM (Java Virtual Machine) facility makes it easier to develop in it. But there are small tweaks and features in Java, so developers search for different options like Scala. Scala and Java interoperability means that a code written in one can be easily executed in another with some changes. Considering the benefits of Scala like the functional feature (Write less, Work More), built-in data structures, powerful inheritance, and most importantly, JVM support, it has proved to be an effective programming language. An example of converting Java code into a Scala readable code has been shown below. An example of working with ArrayList is as follows: // Java program to create and print ArrayList.import java.util.ArrayList;import java.util.List; public class CreateArrayList{ public static void main(String[] args) { List<String> students = new ArrayList<>(); students.add("Raam"); students.add("Shyaam"); students.add("Raju"); students.add("Rajat"); students.add("Shiv"); students.add("Priti"); //Printing an ArrayList. for (String student : students) { System.out.println(student); } }} Output: Raam Shyaam Raju Rajat Shiv Priti As soon as the Scala REPL starts, the Java standard libraries are made available. Sometimes it is required to add Java collections in Scala code. The same code can be written in Scala as follows: // Scala conversion of the above program.import java.util.ArrayList;import scala.collection.JavaConversions._ // Creating objectobject geeks{ // Main method def main(args: Array[String]) { val students = new ArrayList[String] students.add("Raam"); students.add("Shyaam"); students.add("Raju"); students.add("Rajat"); students.add("Shiv"); students.add("Priti"); // Printing the ArrayList for (student <- students) { println(student) } }} Output: Raam Shyaam Raju Rajat Shiv Priti However, there are some Scala features and collections that lack Java equivalency. The major difference between the Java and Scala collections is generally put forward as A Scala Traversable is not Java Iterable and vice versa. However, the conversions are possible using some commands. Sometimes, one needs to pass one’s collections to the other’s code. To make it possible, the following commands are added in Scala code: scala> import collection.JavaConverters._ import collection.JavaConverters._ The following example shows the conversion of Java collections into Scala and vice versa. The .asJava and .asScala are extension functions that enable the aforementioned conversions. To convert the Scala collections to Java:import scala.collection.JavaConverters._ val listInScala = List(10, 20, 30) JavaLibrary.process(listInScala.asJava) import scala.collection.JavaConverters._ val listInScala = List(10, 20, 30) JavaLibrary.process(listInScala.asJava) To convert the Java collections to Scala:import scala.collection.JavaConverters._ val JavaCol= JavaLibrary.getList val ScalaCol= JavaCol.asScalaA Scala Collection can be incorporated using scala.collection and the sub collections can be incorporated using scala.collection.mutable and scala.collection.immutable. A Mutable collection can be changed but an immutable collection can not be changed. However, one can still run operations such as addition on the collections but it would only give a new collection and leave the old one unchanged.An example showing the same is as follows:// Java Program to return a HashMap.import java.util.HashMap;import scala.collection.JavaConverters;import scala.Predef;import scala.Tuple2;import scala.collection.immutable.Map; public class ConvertToScala { public static <A, B> Map<A, B> MapInScala(HashMap<A, B> exampleMap) { return JavaConverters.mapAsScalaMapConverter(exampleMap). asScala().toMap(Predef.<Tuple2<A, B> >conforms()); } public static HashMap<String, String> Example() { HashMap<String, String> exampleMap = new HashMap<String, String>(); exampleMap.put("Ayush", "Boy"); exampleMap.put("Ridhi", "Girl"); exampleMap.put("Soumya", "Girl"); return exampleMap; }}The above code can be converted in Scala as follows:Scala version of the above program.scala> val javamap: java.util.HashMap[String, String] = ConvertToScala.Examplejavamap: java.util.HashMap[String, String] = {Ridhi=Girl, Soumya=Girl, Ayush=Boy}scala> val scalamap: Map[String, String] = ConvertToScala.MapInScala(javamap)scalamap: Map[String, String] = Map(Ridhi -> Girl, Soumya -> Girl, Ayush -> Boy)In conclusion, Java and Scala Interoperability require some collections of Scala to be assigned to Java code and vice versa. Although, programming in Scala is not tedious and better than in Java considering the fewer number of characters to write the code. Also, the conversions of the two codes make it easier for the developers to get the support of Scala pretty often.________________________________________________________________________________________My Personal Notes arrow_drop_upSave import scala.collection.JavaConverters._ val JavaCol= JavaLibrary.getList val ScalaCol= JavaCol.asScala A Scala Collection can be incorporated using scala.collection and the sub collections can be incorporated using scala.collection.mutable and scala.collection.immutable. A Mutable collection can be changed but an immutable collection can not be changed. However, one can still run operations such as addition on the collections but it would only give a new collection and leave the old one unchanged. An example showing the same is as follows: // Java Program to return a HashMap.import java.util.HashMap;import scala.collection.JavaConverters;import scala.Predef;import scala.Tuple2;import scala.collection.immutable.Map; public class ConvertToScala { public static <A, B> Map<A, B> MapInScala(HashMap<A, B> exampleMap) { return JavaConverters.mapAsScalaMapConverter(exampleMap). asScala().toMap(Predef.<Tuple2<A, B> >conforms()); } public static HashMap<String, String> Example() { HashMap<String, String> exampleMap = new HashMap<String, String>(); exampleMap.put("Ayush", "Boy"); exampleMap.put("Ridhi", "Girl"); exampleMap.put("Soumya", "Girl"); return exampleMap; }} Scala version of the above program. scala> val javamap: java.util.HashMap[String, String] = ConvertToScala.Examplejavamap: java.util.HashMap[String, String] = {Ridhi=Girl, Soumya=Girl, Ayush=Boy} scala> val scalamap: Map[String, String] = ConvertToScala.MapInScala(javamap)scalamap: Map[String, String] = Map(Ridhi -> Girl, Soumya -> Girl, Ayush -> Boy) In conclusion, Java and Scala Interoperability require some collections of Scala to be assigned to Java code and vice versa. Although, programming in Scala is not tedious and better than in Java considering the fewer number of characters to write the code. Also, the conversions of the two codes make it easier for the developers to get the support of Scala pretty often. ________________________________________________________________________________________ Akanksha_Rai Picked Scala Scala-Basics Scala Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Scala ListBuffer Inheritance in Scala Scala | Case Class and Case Object Scala | Traits Hello World in Scala Scala List map() method with example Scala | Try-Catch Exceptions How to install Scala on Windows? Scala | Decision Making (if, if-else, Nested if-else, if-else if) Comments In Scala
[ { "code": null, "e": 25411, "s": 25383, "text": "\n30 Jun, 2020" }, { "code": null, "e": 25756, "s": 25411, "text": "Java is one of the top programming languages and the JVM (Java Virtual Machine) facility makes it easier to develop in it. But there are small tweaks and features in Java, so developers search for different options like Scala. Scala and Java interoperability means that a code written in one can be easily executed in another with some changes." }, { "code": null, "e": 25981, "s": 25756, "text": "Considering the benefits of Scala like the functional feature (Write less, Work More), built-in data structures, powerful inheritance, and most importantly, JVM support, it has proved to be an effective programming language." }, { "code": null, "e": 26117, "s": 25981, "text": "An example of converting Java code into a Scala readable code has been shown below. An example of working with ArrayList is as follows:" }, { "code": "// Java program to create and print ArrayList.import java.util.ArrayList;import java.util.List; public class CreateArrayList{ public static void main(String[] args) { List<String> students = new ArrayList<>(); students.add(\"Raam\"); students.add(\"Shyaam\"); students.add(\"Raju\"); students.add(\"Rajat\"); students.add(\"Shiv\"); students.add(\"Priti\"); //Printing an ArrayList. for (String student : students) { System.out.println(student); } }}", "e": 26657, "s": 26117, "text": null }, { "code": null, "e": 26665, "s": 26657, "text": "Output:" }, { "code": null, "e": 26700, "s": 26665, "text": "Raam\nShyaam\nRaju\nRajat\nShiv\nPriti\n" }, { "code": null, "e": 26896, "s": 26700, "text": "As soon as the Scala REPL starts, the Java standard libraries are made available. Sometimes it is required to add Java collections in Scala code. The same code can be written in Scala as follows:" }, { "code": "// Scala conversion of the above program.import java.util.ArrayList;import scala.collection.JavaConversions._ // Creating objectobject geeks{ // Main method def main(args: Array[String]) { val students = new ArrayList[String] students.add(\"Raam\"); students.add(\"Shyaam\"); students.add(\"Raju\"); students.add(\"Rajat\"); students.add(\"Shiv\"); students.add(\"Priti\"); // Printing the ArrayList for (student <- students) { println(student) } }}", "e": 27444, "s": 26896, "text": null }, { "code": null, "e": 27452, "s": 27444, "text": "Output:" }, { "code": null, "e": 27487, "s": 27452, "text": "Raam\nShyaam\nRaju\nRajat\nShiv\nPriti\n" }, { "code": null, "e": 27911, "s": 27487, "text": "However, there are some Scala features and collections that lack Java equivalency. The major difference between the Java and Scala collections is generally put forward as A Scala Traversable is not Java Iterable and vice versa. However, the conversions are possible using some commands. Sometimes, one needs to pass one’s collections to the other’s code. To make it possible, the following commands are added in Scala code:" }, { "code": null, "e": 27989, "s": 27911, "text": "scala> import collection.JavaConverters._\nimport collection.JavaConverters._\n" }, { "code": null, "e": 28172, "s": 27989, "text": "The following example shows the conversion of Java collections into Scala and vice versa. The .asJava and .asScala are extension functions that enable the aforementioned conversions." }, { "code": null, "e": 28330, "s": 28172, "text": "To convert the Scala collections to Java:import scala.collection.JavaConverters._\n\nval listInScala = List(10, 20, 30)\nJavaLibrary.process(listInScala.asJava)" }, { "code": null, "e": 28447, "s": 28330, "text": "import scala.collection.JavaConverters._\n\nval listInScala = List(10, 20, 30)\nJavaLibrary.process(listInScala.asJava)" }, { "code": null, "e": 30639, "s": 28447, "text": "To convert the Java collections to Scala:import scala.collection.JavaConverters._\n\nval JavaCol= JavaLibrary.getList\nval ScalaCol= JavaCol.asScalaA Scala Collection can be incorporated using scala.collection and the sub collections can be incorporated using scala.collection.mutable and scala.collection.immutable. A Mutable collection can be changed but an immutable collection can not be changed. However, one can still run operations such as addition on the collections but it would only give a new collection and leave the old one unchanged.An example showing the same is as follows:// Java Program to return a HashMap.import java.util.HashMap;import scala.collection.JavaConverters;import scala.Predef;import scala.Tuple2;import scala.collection.immutable.Map; public class ConvertToScala { public static <A, B> Map<A, B> MapInScala(HashMap<A, B> exampleMap) { return JavaConverters.mapAsScalaMapConverter(exampleMap). asScala().toMap(Predef.<Tuple2<A, B> >conforms()); } public static HashMap<String, String> Example() { HashMap<String, String> exampleMap = new HashMap<String, String>(); exampleMap.put(\"Ayush\", \"Boy\"); exampleMap.put(\"Ridhi\", \"Girl\"); exampleMap.put(\"Soumya\", \"Girl\"); return exampleMap; }}The above code can be converted in Scala as follows:Scala version of the above program.scala> val javamap: java.util.HashMap[String, String] = ConvertToScala.Examplejavamap: java.util.HashMap[String, String] = {Ridhi=Girl, Soumya=Girl, Ayush=Boy}scala> val scalamap: Map[String, String] = ConvertToScala.MapInScala(javamap)scalamap: Map[String, String] = Map(Ridhi -> Girl, Soumya -> Girl, Ayush -> Boy)In conclusion, Java and Scala Interoperability require some collections of Scala to be assigned to Java code and vice versa. Although, programming in Scala is not tedious and better than in Java considering the fewer number of characters to write the code. Also, the conversions of the two codes make it easier for the developers to get the support of Scala pretty often.________________________________________________________________________________________My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 30744, "s": 30639, "text": "import scala.collection.JavaConverters._\n\nval JavaCol= JavaLibrary.getList\nval ScalaCol= JavaCol.asScala" }, { "code": null, "e": 31144, "s": 30744, "text": "A Scala Collection can be incorporated using scala.collection and the sub collections can be incorporated using scala.collection.mutable and scala.collection.immutable. A Mutable collection can be changed but an immutable collection can not be changed. However, one can still run operations such as addition on the collections but it would only give a new collection and leave the old one unchanged." }, { "code": null, "e": 31187, "s": 31144, "text": "An example showing the same is as follows:" }, { "code": "// Java Program to return a HashMap.import java.util.HashMap;import scala.collection.JavaConverters;import scala.Predef;import scala.Tuple2;import scala.collection.immutable.Map; public class ConvertToScala { public static <A, B> Map<A, B> MapInScala(HashMap<A, B> exampleMap) { return JavaConverters.mapAsScalaMapConverter(exampleMap). asScala().toMap(Predef.<Tuple2<A, B> >conforms()); } public static HashMap<String, String> Example() { HashMap<String, String> exampleMap = new HashMap<String, String>(); exampleMap.put(\"Ayush\", \"Boy\"); exampleMap.put(\"Ridhi\", \"Girl\"); exampleMap.put(\"Soumya\", \"Girl\"); return exampleMap; }}", "e": 31896, "s": 31187, "text": null }, { "code": null, "e": 31932, "s": 31896, "text": "Scala version of the above program." }, { "code": null, "e": 32092, "s": 31932, "text": "scala> val javamap: java.util.HashMap[String, String] = ConvertToScala.Examplejavamap: java.util.HashMap[String, String] = {Ridhi=Girl, Soumya=Girl, Ayush=Boy}" }, { "code": null, "e": 32250, "s": 32092, "text": "scala> val scalamap: Map[String, String] = ConvertToScala.MapInScala(javamap)scalamap: Map[String, String] = Map(Ridhi -> Girl, Soumya -> Girl, Ayush -> Boy)" }, { "code": null, "e": 32622, "s": 32250, "text": "In conclusion, Java and Scala Interoperability require some collections of Scala to be assigned to Java code and vice versa. Although, programming in Scala is not tedious and better than in Java considering the fewer number of characters to write the code. Also, the conversions of the two codes make it easier for the developers to get the support of Scala pretty often." }, { "code": null, "e": 32711, "s": 32622, "text": "________________________________________________________________________________________" }, { "code": null, "e": 32724, "s": 32711, "text": "Akanksha_Rai" }, { "code": null, "e": 32731, "s": 32724, "text": "Picked" }, { "code": null, "e": 32737, "s": 32731, "text": "Scala" }, { "code": null, "e": 32750, "s": 32737, "text": "Scala-Basics" }, { "code": null, "e": 32756, "s": 32750, "text": "Scala" }, { "code": null, "e": 32775, "s": 32756, "text": "Technical Scripter" }, { "code": null, "e": 32873, "s": 32775, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32890, "s": 32873, "text": "Scala ListBuffer" }, { "code": null, "e": 32911, "s": 32890, "text": "Inheritance in Scala" }, { "code": null, "e": 32946, "s": 32911, "text": "Scala | Case Class and Case Object" }, { "code": null, "e": 32961, "s": 32946, "text": "Scala | Traits" }, { "code": null, "e": 32982, "s": 32961, "text": "Hello World in Scala" }, { "code": null, "e": 33019, "s": 32982, "text": "Scala List map() method with example" }, { "code": null, "e": 33048, "s": 33019, "text": "Scala | Try-Catch Exceptions" }, { "code": null, "e": 33081, "s": 33048, "text": "How to install Scala on Windows?" }, { "code": null, "e": 33147, "s": 33081, "text": "Scala | Decision Making (if, if-else, Nested if-else, if-else if)" } ]
Tryit Editor v3.7
Tryit: bigger emojis
[]
How to Get Last Modified Date of File in Linux? - GeeksforGeeks
28 Mar, 2021 Here we are going to see how to get the last modified date of the file in Linux, sometimes we may require timestamps of the file and apart from this it also ensures that we have the latest version of that file. It can be done in four ways: Using Stat command. Using date command. Using ls -l command. Using httpie Example 1: Using Stat command. Apart from this if you only want to see the modified date then use the below command $ stat -c ‘%y’ filename -c displays the date and %y displays the modification time. Example 2: Using date command. You can use the below command to display the last modification date of the file $ date -r filename Example 3: Using ls -l command: The below command is used. $ ls -lt filename Example 4: Using httpie: You can check the last modified date of the file which is residing on the webserver and the command is also used for interacting with HTTP servers and APIs. Below syntax is used to check the last modified date of the file which is on the webserver. $ http -h [url] | grep 'Last-Modified' Picked How To Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install FFmpeg on Windows? How to Add External JAR File to an IntelliJ IDEA Project? How to Set Git Username and Password in GitBash? How to create a nested RecyclerView in Android How to Create and Setup Spring Boot Project in Eclipse IDE? Sed Command in Linux/Unix with examples AWK command in Unix/Linux with examples grep command in Unix/Linux cut command in Linux with examples cp command in Linux with examples
[ { "code": null, "e": 26197, "s": 26169, "text": "\n28 Mar, 2021" }, { "code": null, "e": 26408, "s": 26197, "text": "Here we are going to see how to get the last modified date of the file in Linux, sometimes we may require timestamps of the file and apart from this it also ensures that we have the latest version of that file." }, { "code": null, "e": 26437, "s": 26408, "text": "It can be done in four ways:" }, { "code": null, "e": 26457, "s": 26437, "text": "Using Stat command." }, { "code": null, "e": 26477, "s": 26457, "text": "Using date command." }, { "code": null, "e": 26498, "s": 26477, "text": "Using ls -l command." }, { "code": null, "e": 26511, "s": 26498, "text": "Using httpie" }, { "code": null, "e": 26542, "s": 26511, "text": "Example 1: Using Stat command." }, { "code": null, "e": 26627, "s": 26542, "text": "Apart from this if you only want to see the modified date then use the below command" }, { "code": null, "e": 26651, "s": 26627, "text": "$ stat -c ‘%y’ filename" }, { "code": null, "e": 26711, "s": 26651, "text": "-c displays the date and %y displays the modification time." }, { "code": null, "e": 26742, "s": 26711, "text": "Example 2: Using date command." }, { "code": null, "e": 26822, "s": 26742, "text": "You can use the below command to display the last modification date of the file" }, { "code": null, "e": 26841, "s": 26822, "text": "$ date -r filename" }, { "code": null, "e": 26873, "s": 26841, "text": "Example 3: Using ls -l command:" }, { "code": null, "e": 26900, "s": 26873, "text": "The below command is used." }, { "code": null, "e": 26918, "s": 26900, "text": "$ ls -lt filename" }, { "code": null, "e": 26943, "s": 26918, "text": "Example 4: Using httpie:" }, { "code": null, "e": 27100, "s": 26943, "text": "You can check the last modified date of the file which is residing on the webserver and the command is also used for interacting with HTTP servers and APIs." }, { "code": null, "e": 27192, "s": 27100, "text": "Below syntax is used to check the last modified date of the file which is on the webserver." }, { "code": null, "e": 27232, "s": 27192, "text": "$ http -h [url] | grep 'Last-Modified'" }, { "code": null, "e": 27239, "s": 27232, "text": "Picked" }, { "code": null, "e": 27246, "s": 27239, "text": "How To" }, { "code": null, "e": 27257, "s": 27246, "text": "Linux-Unix" }, { "code": null, "e": 27355, "s": 27257, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27389, "s": 27355, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 27447, "s": 27389, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" }, { "code": null, "e": 27496, "s": 27447, "text": "How to Set Git Username and Password in GitBash?" }, { "code": null, "e": 27543, "s": 27496, "text": "How to create a nested RecyclerView in Android" }, { "code": null, "e": 27603, "s": 27543, "text": "How to Create and Setup Spring Boot Project in Eclipse IDE?" }, { "code": null, "e": 27643, "s": 27603, "text": "Sed Command in Linux/Unix with examples" }, { "code": null, "e": 27683, "s": 27643, "text": "AWK command in Unix/Linux with examples" }, { "code": null, "e": 27710, "s": 27683, "text": "grep command in Unix/Linux" }, { "code": null, "e": 27745, "s": 27710, "text": "cut command in Linux with examples" } ]
Python | Generate test datasets for Machine learning - GeeksforGeeks
21 Jan, 2021 Whenever we think of Machine Learning, the first thing that comes to our mind is a dataset. While there are many datasets that you can find on websites such as Kaggle, sometimes it is useful to extract data on your own and generate your own dataset. Generating your own dataset gives you more control over the data and allows you to train your machine learning model. In this article, we will generate random datasets using the Numpy library in Python. Libraries needed: -> Numpy: pip3 install numpy -> Pandas: pip3 install pandas -> Matplotlib: pip3 install matplotlib In probability theory, normal or Gaussian distribution is a very common continuous probability distribution that is symmetric about the mean, showing that data near the mean are more frequent in occurrence than data far from the mean. Normal distributions used in statistics and are often used to represent real-valued random variables. The normal distribution is the most common type of distribution in statistical analyses. The standard normal distribution has two parameters: the mean and the standard deviation. The mean is the central tendency of the distribution. The standard deviation is a measure of variability. It defines the width of the normal distribution. The standard deviation determines how far away from the mean the values tend to fall. It represents the typical distance between the observations and the average. it fits many natural phenomena, For example, heights, blood pressure, measurement error, and IQ scores follow the normal distribution. Graph of the normal distribution: Example: PYTHON3 # importing librariesimport pandas as pdimport numpy as npimport matplotlib.pyplot as plt # initialize the parameters for the normal# distribution, namely mean and std.# deviation # defining the meanmu = 0.5# defining the standard deviationsigma = 0.1 # The random module uses the seed value as a base# to generate a random number. If seed value is not# present, it takes the system’s current time.np.random.seed(0) # define the x co-ordinatesX = np.random.normal(mu, sigma, (395, 1)) # define the y co-ordinatesY = np.random.normal(mu * 2, sigma * 3, (395, 1)) # plot a graphplt.scatter(X, Y, color = 'g')plt.show() Output : Let us look at a better example.We will generate a dataset with 4 columns. Each column in the dataset represents a feature. The 5th column of the dataset is the output label. It varies between 0-3. This dataset can be used for training a classifier such as a logistic regression classifier, neural network classifier, Support vector machines, etc. PYTHON3 # importing librariesimport numpy as npimport pandas as pdimport mathimport randomimport matplotlib.pyplot as plt # defining the columns using normal distribution # column 1point1 = abs(np.random.normal(1, 12, 100))# column 2point2 = abs(np.random.normal(2, 8, 100))# column 3point3 = abs(np.random.normal(3, 2, 100))# column 4point4 = abs(np.random.normal(10, 15, 100)) # x contains the features of our dataset# the points are concatenated horizontally# using numpy to form a feature vector.x = np.c_[point1, point2, point3, point4] # the output labels vary from 0-3y = [int(np.random.randint(0, 4)) for i in range(100)] # defining a pandas data frame to save# the data for later usedata = pd.DataFrame() # defining the columns of the datasetdata['col1'] = point1data['col2'] = point2data['col3'] = point3data['col4'] = point4 # plotting the various features (x)# against the labels (y).plt.subplot(2, 2, 1)plt.title('col1')plt.scatter(y, point1, color ='r', label ='col1') plt.subplot(2, 2, 2)plt.title('Col2')plt.scatter(y, point2, color = 'g', label ='col2') plt.subplot(2, 2, 3)plt.title('Col3')plt.scatter(y, point3, color ='b', label ='col3') plt.subplot(2, 2, 4)plt.title('Col4')plt.scatter(y, point4, color ='y', label ='col4') # saving the graphplt.savefig('data_visualization.jpg') # displaying the graphplt.show() Output : nunemunthalashiva 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 Decision Tree Introduction with example Reinforcement learning Python | Decision tree implementation Support Vector Machine Algorithm Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 26231, "s": 26203, "text": "\n21 Jan, 2021" }, { "code": null, "e": 26601, "s": 26231, "text": "Whenever we think of Machine Learning, the first thing that comes to our mind is a dataset. While there are many datasets that you can find on websites such as Kaggle, sometimes it is useful to extract data on your own and generate your own dataset. Generating your own dataset gives you more control over the data and allows you to train your machine learning model. " }, { "code": null, "e": 26687, "s": 26601, "text": "In this article, we will generate random datasets using the Numpy library in Python. " }, { "code": null, "e": 26705, "s": 26687, "text": "Libraries needed:" }, { "code": null, "e": 26804, "s": 26705, "text": "-> Numpy: pip3 install numpy\n-> Pandas: pip3 install pandas\n-> Matplotlib: pip3 install matplotlib" }, { "code": null, "e": 27776, "s": 26806, "text": "In probability theory, normal or Gaussian distribution is a very common continuous probability distribution that is symmetric about the mean, showing that data near the mean are more frequent in occurrence than data far from the mean. Normal distributions used in statistics and are often used to represent real-valued random variables. The normal distribution is the most common type of distribution in statistical analyses. The standard normal distribution has two parameters: the mean and the standard deviation. The mean is the central tendency of the distribution. The standard deviation is a measure of variability. It defines the width of the normal distribution. The standard deviation determines how far away from the mean the values tend to fall. It represents the typical distance between the observations and the average. it fits many natural phenomena, For example, heights, blood pressure, measurement error, and IQ scores follow the normal distribution. " }, { "code": null, "e": 27812, "s": 27776, "text": "Graph of the normal distribution: " }, { "code": null, "e": 27823, "s": 27812, "text": "Example: " }, { "code": null, "e": 27831, "s": 27823, "text": "PYTHON3" }, { "code": "# importing librariesimport pandas as pdimport numpy as npimport matplotlib.pyplot as plt # initialize the parameters for the normal# distribution, namely mean and std.# deviation # defining the meanmu = 0.5# defining the standard deviationsigma = 0.1 # The random module uses the seed value as a base# to generate a random number. If seed value is not# present, it takes the system’s current time.np.random.seed(0) # define the x co-ordinatesX = np.random.normal(mu, sigma, (395, 1)) # define the y co-ordinatesY = np.random.normal(mu * 2, sigma * 3, (395, 1)) # plot a graphplt.scatter(X, Y, color = 'g')plt.show()", "e": 28448, "s": 27831, "text": null }, { "code": null, "e": 28459, "s": 28448, "text": "Output : " }, { "code": null, "e": 28808, "s": 28459, "text": "Let us look at a better example.We will generate a dataset with 4 columns. Each column in the dataset represents a feature. The 5th column of the dataset is the output label. It varies between 0-3. This dataset can be used for training a classifier such as a logistic regression classifier, neural network classifier, Support vector machines, etc. " }, { "code": null, "e": 28816, "s": 28808, "text": "PYTHON3" }, { "code": "# importing librariesimport numpy as npimport pandas as pdimport mathimport randomimport matplotlib.pyplot as plt # defining the columns using normal distribution # column 1point1 = abs(np.random.normal(1, 12, 100))# column 2point2 = abs(np.random.normal(2, 8, 100))# column 3point3 = abs(np.random.normal(3, 2, 100))# column 4point4 = abs(np.random.normal(10, 15, 100)) # x contains the features of our dataset# the points are concatenated horizontally# using numpy to form a feature vector.x = np.c_[point1, point2, point3, point4] # the output labels vary from 0-3y = [int(np.random.randint(0, 4)) for i in range(100)] # defining a pandas data frame to save# the data for later usedata = pd.DataFrame() # defining the columns of the datasetdata['col1'] = point1data['col2'] = point2data['col3'] = point3data['col4'] = point4 # plotting the various features (x)# against the labels (y).plt.subplot(2, 2, 1)plt.title('col1')plt.scatter(y, point1, color ='r', label ='col1') plt.subplot(2, 2, 2)plt.title('Col2')plt.scatter(y, point2, color = 'g', label ='col2') plt.subplot(2, 2, 3)plt.title('Col3')plt.scatter(y, point3, color ='b', label ='col3') plt.subplot(2, 2, 4)plt.title('Col4')plt.scatter(y, point4, color ='y', label ='col4') # saving the graphplt.savefig('data_visualization.jpg') # displaying the graphplt.show()", "e": 30169, "s": 28816, "text": null }, { "code": null, "e": 30180, "s": 30169, "text": "Output : " }, { "code": null, "e": 30200, "s": 30182, "text": "nunemunthalashiva" }, { "code": null, "e": 30213, "s": 30200, "text": "data-science" }, { "code": null, "e": 30230, "s": 30213, "text": "Machine Learning" }, { "code": null, "e": 30237, "s": 30230, "text": "Python" }, { "code": null, "e": 30254, "s": 30237, "text": "Machine Learning" }, { "code": null, "e": 30352, "s": 30254, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30375, "s": 30352, "text": "ML | Linear Regression" }, { "code": null, "e": 30415, "s": 30375, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 30438, "s": 30415, "text": "Reinforcement learning" }, { "code": null, "e": 30476, "s": 30438, "text": "Python | Decision tree implementation" }, { "code": null, "e": 30509, "s": 30476, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 30537, "s": 30509, "text": "Read JSON file using Python" }, { "code": null, "e": 30587, "s": 30537, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 30609, "s": 30587, "text": "Python map() function" } ]
Ambiguities in Java - GeeksforGeeks
10 Sep, 2021 The ambiguities are those issues that are not defined clearly in the Java language specification. The different results produced by different compilers on several example programs support our observations. Here we will be discussing in the following order. Ambiguity method in method overloadingMethods with only Varargs parametersMethods with Varargs along with other parameters Methods with only Varargs parameters Methods with Varargs along with other parameters Ambiguity in multiple inheritancesDiamond Problem Diamond Problem Type 1: Ambiguity method in method overloading When you overload methods, you risk creating an ambiguous situation of which one is in which the compiler cannot determine which method to use. For example, consider the following overloaded computeBalance() method declarations: public static void computeBalance(double deposit) public static void computeBalance(double withdrawal) If you declare a double variable named myDeposit and make a method call such as computeBalance(myDeposit);, you will have created an ambiguous situation. Both methods are exact matches for your call. You might argue that a call using a variable named myDeposit “seems” like it should go to the version of the method with the parameter named deposit, but Java makes no assumptions based on variable names. Each version of computeBalance() could accept a double, and Java does not presume which one you intend to use. Ambiguity Errors The inclusion of generics gives rise to a new type of error that you must guard against ambiguity. Ambiguity errors occur when erasure causes two seemingly distinct generic declarations to resolve to the same erased type, causing a conflict. Here is an example that involves method overloading. Now we are good to go with type 1 as shown above to describe that is. method overloading in varargs Overloading allows different methods to have the same name, but different signatures where the signature can differ by the number of input parameters or type of input parameters, or both. We can overload a method that takes a variable-length argument by following ways: Case 1: Methods with only Varargs parameters In this case, Java uses the type difference to determine which overloaded method to call. If one method signature is strictly more specific than the other, then Java chooses it without an error. Example Java // Java program to illustrate method overloading in varargs // Main class demonstrating varargsDemopublic class GFG { // Method 1 // varargs method with float datatype static void fun(float... x) { // Print statement // whenever this method is called System.out.println("float varargs"); } // Method 2 // varargs method with int datatype static void fun(int... x) { // Print statement // whenever this method is called System.out.println("int varargs"); } // Method 3 // varargs method with double datatype static void fun(double... x) { // Print statement // whenever this method is called System.out.println("double varargs"); } // Method 4 // Main driver method public static void main(String[] args) { // Calling the above methods fun(); }} int varargs Output Explanation: This output is due to the fact that int is more specific than double. As specified in the JLS section 15.12.2.5, If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen according to type promotion. The following rules define the direct supertype relation among the primitive types in this case: double > float float > long long > int int > char int > short short > byte Case 2: Methods with Varargs along with other parameters. In this case, Java uses both the number of arguments and the type of arguments to determine which method to call. Example 1: Java // Java program to demonstrate Varargs and Overloading // Main classclass GFG { // Method 1 // It takes varargs(here integers). static void fun(int... a) { // Print statement whenever this method is called System.out.print("fun(int ...): " + "Number of args: " + a.length + " Contents: "); // For each loop is used to // display contents for (int x : a) // Print statement System.out.print(x + " "); // New line System.out.println(); } // Method 2 // It takes varargs(here booleans). static void fun(boolean... a) { // Print statement to display the content // whenever this method is called System.out.print("fun(boolean ...) " + "Number of args: " + a.length + " Contents: "); // Iterating using for-each loop to // display contents for (boolean x : a) // Print statement to display the content // whenever this method is called System.out.print(x + " "); // New line for better readability System.out.println(); } // Method 3 // It takes string as a argument // followed by varargs(here integers). static void fun(String msg, int... a) { // Print statement to display the content // whenever this method is called System.out.print("fun(String, int ...): " + msg + a.length + " Contents: "); // Iterating using for-each loop to // display contents for (int x : a) System.out.print(x + " "); // New line for better readability System.out.println(); } // Method 4 // Main driver method public static void main(String args[]) { // Calling the above methods to // check for overloaded fun() // with different parameter // Custom inputs as parameters fun(1, 2, 3); fun("Testing: ", 10, 20); fun(true, false, false); }} fun(int ...): Number of args: 3 Contents: 1 2 3 fun(String, int ...): Testing: 2 Contents: 10 20 fun(boolean ...) Number of args: 3 Contents: true false false Here the fun() method is overloaded three times. Note: Sometimes unexpected errors can result when overloading a method that takes a variable-length argument. These errors involve ambiguity because both the methods are valid candidates for invocation. The compiler cannot decide on which method to bind the method call. Example 2: Java // Java program to illustrate Varargs and Ambiguity // Main classclass GFG { // Method 1 // It takes varargs(here integers). static void fun(int... a) { // Print and display contents // whenever this method is called System.out.print("fun(int ...): " + "Number of args: " + a.length + " Contents: "); // Iterating using for-each loop to // display contents for (int x : a) // Print statement System.out.print(x + " "); // New line for better readability of output System.out.println(); } // Method 2 // It takes varargs(here booleans). static void fun(boolean... a) { // Print and display contents // whenever this method is called System.out.print("fun(boolean ...) " + "Number of args: " + a.length + " Contents: "); // Iterating using for-each loop to // display contents for (boolean x : a) System.out.print(x + " "); // New line is needed for // better readability in output System.out.println(); } // Method 3 // Main driver method public static void main(String args[]) { // Calling overloaded fun() above created // with different parameter // Custom inputs are passed as parameters // Case1: ok fun(1, 2, 3); // Case 2: ok fun(true, false, false); // Case 3: Error: Ambiguous! fun(); }} Output: Output explanation: The overloading of the desired method here named ‘fun()‘ is perfectly correct. However, this program will not compile because of the last call made to ‘fun()’ which can also be interpreted in the code. Type 2: Ambiguity in multiple inheritances. Inheritance is a relation between two classes where one class inherits the properties of the other class. This relation can be defined using the extends keyword as follows: public class A extends B {} The class which inherits the properties is known as a subclass or, child class and the class whose properties are inherited is a superclass or, parent class. In inheritance, a copy of superclass members is created in the sub-class object. Therefore, using the sub-class object you can access the members of both classes. There are various types of inheritance available namely single, multilevel, hierarchical, multiple and, hybrid. In multiple inheritances, one class inherits the properties of multiple classes. In other words, in multiple inheritances, we can have one child class and n number of parent classes. Java does not support multiple inheritances (with classes). Implementation: Diamond problem is one of the major ambiguities that arise here in the case of multiple inheritances. For instance, let us assume that Java does support multiple inheritances. Consider the example below with the following assumptions. Here we have an abstract class named ‘Sample‘ with an abstract method as Example Java // Java Program to illustrate Diamond Problem Ambiquity // Class 1// Abstract class// Parent classpublic class abstract Sample { // Abstract method public abstract demo();} // Then in the same package/folder,// we have two classes extending this class and// trying to implement its abstract method, demo(). // Class 2// helper class extending Class 1public class Super1 extends Sample { // Method of this base class public void demo() { // Print statement whenever this method is called System.out.println("demo method of super1"); }} // Class 3// Helper class extending Class 1public class Super2 extends Sample { // Method of this base class public void demo() { // Print statement whenever this method is called System.out.println("demo method of super2"); }} // According to our assumption of Java supports multiple// inheritance we are trying to inherit both classes Super1// and Super2. // Class 4// Helper class// Deriving above two classes: Class2 and Class3public class SubClass extends Super1, Super2 { // Method of this class // Also, it is main driver method public static void main(String args[]) { // Creating object SubClass obj = new SubClass(); // Trying to access the demo() method // with the help of this class object obj.demo(); }} Output: Output Explanation: Then, as per the basic rule of inheritance, a copy of both demo() methods should be created in the subclass object which leaves the subclass with two methods with the same prototype (name and arguments). Then, if you call the demo() method using the object of the subclass compiler faces an ambiguous situation not knowing which method to call. This issue is known as the diamond problem in Java. surinderdawra388 simmytarika5 Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Exceptions in Java Constructors in Java Different ways of Reading a text file in Java Functional Interfaces in Java Generics in Java Comparator Interface in Java with Examples Introduction to Java PriorityQueue in Java How to remove an element from ArrayList in Java?
[ { "code": null, "e": 25814, "s": 25786, "text": "\n10 Sep, 2021" }, { "code": null, "e": 26071, "s": 25814, "text": "The ambiguities are those issues that are not defined clearly in the Java language specification. The different results produced by different compilers on several example programs support our observations. Here we will be discussing in the following order." }, { "code": null, "e": 26194, "s": 26071, "text": "Ambiguity method in method overloadingMethods with only Varargs parametersMethods with Varargs along with other parameters" }, { "code": null, "e": 26231, "s": 26194, "text": "Methods with only Varargs parameters" }, { "code": null, "e": 26280, "s": 26231, "text": "Methods with Varargs along with other parameters" }, { "code": null, "e": 26330, "s": 26280, "text": "Ambiguity in multiple inheritancesDiamond Problem" }, { "code": null, "e": 26346, "s": 26330, "text": "Diamond Problem" }, { "code": null, "e": 26394, "s": 26346, "text": "Type 1: Ambiguity method in method overloading " }, { "code": null, "e": 26623, "s": 26394, "text": "When you overload methods, you risk creating an ambiguous situation of which one is in which the compiler cannot determine which method to use. For example, consider the following overloaded computeBalance() method declarations:" }, { "code": null, "e": 26673, "s": 26623, "text": "public static void computeBalance(double deposit)" }, { "code": null, "e": 26726, "s": 26673, "text": "public static void computeBalance(double withdrawal)" }, { "code": null, "e": 27242, "s": 26726, "text": "If you declare a double variable named myDeposit and make a method call such as computeBalance(myDeposit);, you will have created an ambiguous situation. Both methods are exact matches for your call. You might argue that a call using a variable named myDeposit “seems” like it should go to the version of the method with the parameter named deposit, but Java makes no assumptions based on variable names. Each version of computeBalance() could accept a double, and Java does not presume which one you intend to use." }, { "code": null, "e": 27259, "s": 27242, "text": "Ambiguity Errors" }, { "code": null, "e": 27555, "s": 27259, "text": "The inclusion of generics gives rise to a new type of error that you must guard against ambiguity. Ambiguity errors occur when erasure causes two seemingly distinct generic declarations to resolve to the same erased type, causing a conflict. Here is an example that involves method overloading. " }, { "code": null, "e": 27655, "s": 27555, "text": "Now we are good to go with type 1 as shown above to describe that is. method overloading in varargs" }, { "code": null, "e": 27925, "s": 27655, "text": "Overloading allows different methods to have the same name, but different signatures where the signature can differ by the number of input parameters or type of input parameters, or both. We can overload a method that takes a variable-length argument by following ways:" }, { "code": null, "e": 27970, "s": 27925, "text": "Case 1: Methods with only Varargs parameters" }, { "code": null, "e": 28165, "s": 27970, "text": "In this case, Java uses the type difference to determine which overloaded method to call. If one method signature is strictly more specific than the other, then Java chooses it without an error." }, { "code": null, "e": 28174, "s": 28165, "text": "Example " }, { "code": null, "e": 28179, "s": 28174, "text": "Java" }, { "code": "// Java program to illustrate method overloading in varargs // Main class demonstrating varargsDemopublic class GFG { // Method 1 // varargs method with float datatype static void fun(float... x) { // Print statement // whenever this method is called System.out.println(\"float varargs\"); } // Method 2 // varargs method with int datatype static void fun(int... x) { // Print statement // whenever this method is called System.out.println(\"int varargs\"); } // Method 3 // varargs method with double datatype static void fun(double... x) { // Print statement // whenever this method is called System.out.println(\"double varargs\"); } // Method 4 // Main driver method public static void main(String[] args) { // Calling the above methods fun(); }}", "e": 29069, "s": 28179, "text": null }, { "code": null, "e": 29081, "s": 29069, "text": "int varargs" }, { "code": null, "e": 29101, "s": 29081, "text": "Output Explanation:" }, { "code": null, "e": 29604, "s": 29101, "text": "This output is due to the fact that int is more specific than double. As specified in the JLS section 15.12.2.5, If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen according to type promotion. The following rules define the direct supertype relation among the primitive types in this case: " }, { "code": null, "e": 29689, "s": 29604, "text": "double > float\nfloat > long\nlong > int\nint > char\nint > short\nshort > byte" }, { "code": null, "e": 29862, "s": 29689, "text": "Case 2: Methods with Varargs along with other parameters. In this case, Java uses both the number of arguments and the type of arguments to determine which method to call. " }, { "code": null, "e": 29873, "s": 29862, "text": "Example 1:" }, { "code": null, "e": 29878, "s": 29873, "text": "Java" }, { "code": "// Java program to demonstrate Varargs and Overloading // Main classclass GFG { // Method 1 // It takes varargs(here integers). static void fun(int... a) { // Print statement whenever this method is called System.out.print(\"fun(int ...): \" + \"Number of args: \" + a.length + \" Contents: \"); // For each loop is used to // display contents for (int x : a) // Print statement System.out.print(x + \" \"); // New line System.out.println(); } // Method 2 // It takes varargs(here booleans). static void fun(boolean... a) { // Print statement to display the content // whenever this method is called System.out.print(\"fun(boolean ...) \" + \"Number of args: \" + a.length + \" Contents: \"); // Iterating using for-each loop to // display contents for (boolean x : a) // Print statement to display the content // whenever this method is called System.out.print(x + \" \"); // New line for better readability System.out.println(); } // Method 3 // It takes string as a argument // followed by varargs(here integers). static void fun(String msg, int... a) { // Print statement to display the content // whenever this method is called System.out.print(\"fun(String, int ...): \" + msg + a.length + \" Contents: \"); // Iterating using for-each loop to // display contents for (int x : a) System.out.print(x + \" \"); // New line for better readability System.out.println(); } // Method 4 // Main driver method public static void main(String args[]) { // Calling the above methods to // check for overloaded fun() // with different parameter // Custom inputs as parameters fun(1, 2, 3); fun(\"Testing: \", 10, 20); fun(true, false, false); }}", "e": 31973, "s": 29878, "text": null }, { "code": null, "e": 32135, "s": 31973, "text": "fun(int ...): Number of args: 3 Contents: 1 2 3 \nfun(String, int ...): Testing: 2 Contents: 10 20 \nfun(boolean ...) Number of args: 3 Contents: true false false " }, { "code": null, "e": 32184, "s": 32135, "text": "Here the fun() method is overloaded three times." }, { "code": null, "e": 32455, "s": 32184, "text": "Note: Sometimes unexpected errors can result when overloading a method that takes a variable-length argument. These errors involve ambiguity because both the methods are valid candidates for invocation. The compiler cannot decide on which method to bind the method call." }, { "code": null, "e": 32466, "s": 32455, "text": "Example 2:" }, { "code": null, "e": 32471, "s": 32466, "text": "Java" }, { "code": "// Java program to illustrate Varargs and Ambiguity // Main classclass GFG { // Method 1 // It takes varargs(here integers). static void fun(int... a) { // Print and display contents // whenever this method is called System.out.print(\"fun(int ...): \" + \"Number of args: \" + a.length + \" Contents: \"); // Iterating using for-each loop to // display contents for (int x : a) // Print statement System.out.print(x + \" \"); // New line for better readability of output System.out.println(); } // Method 2 // It takes varargs(here booleans). static void fun(boolean... a) { // Print and display contents // whenever this method is called System.out.print(\"fun(boolean ...) \" + \"Number of args: \" + a.length + \" Contents: \"); // Iterating using for-each loop to // display contents for (boolean x : a) System.out.print(x + \" \"); // New line is needed for // better readability in output System.out.println(); } // Method 3 // Main driver method public static void main(String args[]) { // Calling overloaded fun() above created // with different parameter // Custom inputs are passed as parameters // Case1: ok fun(1, 2, 3); // Case 2: ok fun(true, false, false); // Case 3: Error: Ambiguous! fun(); }}", "e": 34040, "s": 32471, "text": null }, { "code": null, "e": 34049, "s": 34040, "text": "Output: " }, { "code": null, "e": 34271, "s": 34049, "text": "Output explanation: The overloading of the desired method here named ‘fun()‘ is perfectly correct. However, this program will not compile because of the last call made to ‘fun()’ which can also be interpreted in the code." }, { "code": null, "e": 34489, "s": 34271, "text": "Type 2: Ambiguity in multiple inheritances. Inheritance is a relation between two classes where one class inherits the properties of the other class. This relation can be defined using the extends keyword as follows: " }, { "code": null, "e": 34517, "s": 34489, "text": "public class A extends B {}" }, { "code": null, "e": 34838, "s": 34517, "text": "The class which inherits the properties is known as a subclass or, child class and the class whose properties are inherited is a superclass or, parent class. In inheritance, a copy of superclass members is created in the sub-class object. Therefore, using the sub-class object you can access the members of both classes." }, { "code": null, "e": 35194, "s": 34838, "text": "There are various types of inheritance available namely single, multilevel, hierarchical, multiple and, hybrid. In multiple inheritances, one class inherits the properties of multiple classes. In other words, in multiple inheritances, we can have one child class and n number of parent classes. Java does not support multiple inheritances (with classes). " }, { "code": null, "e": 35211, "s": 35194, "text": "Implementation: " }, { "code": null, "e": 35520, "s": 35211, "text": "Diamond problem is one of the major ambiguities that arise here in the case of multiple inheritances. For instance, let us assume that Java does support multiple inheritances. Consider the example below with the following assumptions. Here we have an abstract class named ‘Sample‘ with an abstract method as " }, { "code": null, "e": 35528, "s": 35520, "text": "Example" }, { "code": null, "e": 35533, "s": 35528, "text": "Java" }, { "code": "// Java Program to illustrate Diamond Problem Ambiquity // Class 1// Abstract class// Parent classpublic class abstract Sample { // Abstract method public abstract demo();} // Then in the same package/folder,// we have two classes extending this class and// trying to implement its abstract method, demo(). // Class 2// helper class extending Class 1public class Super1 extends Sample { // Method of this base class public void demo() { // Print statement whenever this method is called System.out.println(\"demo method of super1\"); }} // Class 3// Helper class extending Class 1public class Super2 extends Sample { // Method of this base class public void demo() { // Print statement whenever this method is called System.out.println(\"demo method of super2\"); }} // According to our assumption of Java supports multiple// inheritance we are trying to inherit both classes Super1// and Super2. // Class 4// Helper class// Deriving above two classes: Class2 and Class3public class SubClass extends Super1, Super2 { // Method of this class // Also, it is main driver method public static void main(String args[]) { // Creating object SubClass obj = new SubClass(); // Trying to access the demo() method // with the help of this class object obj.demo(); }}", "e": 36902, "s": 35533, "text": null }, { "code": null, "e": 36911, "s": 36902, "text": "Output: " }, { "code": null, "e": 37328, "s": 36911, "text": "Output Explanation: Then, as per the basic rule of inheritance, a copy of both demo() methods should be created in the subclass object which leaves the subclass with two methods with the same prototype (name and arguments). Then, if you call the demo() method using the object of the subclass compiler faces an ambiguous situation not knowing which method to call. This issue is known as the diamond problem in Java." }, { "code": null, "e": 37347, "s": 37330, "text": "surinderdawra388" }, { "code": null, "e": 37360, "s": 37347, "text": "simmytarika5" }, { "code": null, "e": 37365, "s": 37360, "text": "Java" }, { "code": null, "e": 37370, "s": 37365, "text": "Java" }, { "code": null, "e": 37468, "s": 37370, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37483, "s": 37468, "text": "Stream In Java" }, { "code": null, "e": 37502, "s": 37483, "text": "Exceptions in Java" }, { "code": null, "e": 37523, "s": 37502, "text": "Constructors in Java" }, { "code": null, "e": 37569, "s": 37523, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 37599, "s": 37569, "text": "Functional Interfaces in Java" }, { "code": null, "e": 37616, "s": 37599, "text": "Generics in Java" }, { "code": null, "e": 37659, "s": 37616, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 37680, "s": 37659, "text": "Introduction to Java" }, { "code": null, "e": 37702, "s": 37680, "text": "PriorityQueue in Java" } ]
Is it possible to override a Java method of one class in same?
When we have two classes where one extends another and if, these two classes have the same method including parameters and return type (say, sample) the method in the subclass overrides the method in the superclass. i.e. Since it is an inheritance. If we instantiate the subclass a copy of superclass’s members is created in the subclass object and, thus both methods are available to the object of the subclass. But if you call the method (sample), the sampling method of the subclass will be executed overriding the super class’s method. Live Demo class Super{ public static void sample(){ System.out.println("Method of the superclass"); } } public class OverridingExample extends Super { public static void sample(){ System.out.println("Method of the subclass"); } public static void main(String args[]){ Super obj1 = (Super) new OverridingExample(); OverridingExample obj2 = new OverridingExample(); obj1.sample(); obj2.sample(); } } Method of the superclass Method of the subclass While overriding − Both methods should be in two different classes and, these classes must be in an inheritance relation. Both methods should be in two different classes and, these classes must be in an inheritance relation. Both methods must have the same name, same parameters and, same return type else they both will be treated as different methods. Both methods must have the same name, same parameters and, same return type else they both will be treated as different methods. The method in the child class must not have higher access restrictions than the one in the superclass. If you try to do so it raises a compile-time exception. The method in the child class must not have higher access restrictions than the one in the superclass. If you try to do so it raises a compile-time exception. If the super-class method throws certain exceptions, the method in the sub-class should throw the same exception or its subtype (can leave without throwing any exception). If the super-class method throws certain exceptions, the method in the sub-class should throw the same exception or its subtype (can leave without throwing any exception). Therefore, you cannot override two methods that exist in the same class, you can just overload them.
[ { "code": null, "e": 1278, "s": 1062, "text": "When we have two classes where one extends another and if, these two classes have the same method including parameters and return type (say, sample) the method in the subclass overrides the method in the superclass." }, { "code": null, "e": 1475, "s": 1278, "text": "i.e. Since it is an inheritance. If we instantiate the subclass a copy of superclass’s members is created in the subclass object and, thus both methods are available to the object of the subclass." }, { "code": null, "e": 1602, "s": 1475, "text": "But if you call the method (sample), the sampling method of the subclass will be executed overriding the super class’s method." }, { "code": null, "e": 1613, "s": 1602, "text": " Live Demo" }, { "code": null, "e": 2057, "s": 1613, "text": "class Super{\n public static void sample(){\n System.out.println(\"Method of the superclass\");\n }\n}\npublic class OverridingExample extends Super {\n public static void sample(){\n System.out.println(\"Method of the subclass\");\n } \n public static void main(String args[]){\n Super obj1 = (Super) new OverridingExample();\n OverridingExample obj2 = new OverridingExample();\n obj1.sample();\n obj2.sample();\n }\n}" }, { "code": null, "e": 2105, "s": 2057, "text": "Method of the superclass\nMethod of the subclass" }, { "code": null, "e": 2124, "s": 2105, "text": "While overriding −" }, { "code": null, "e": 2227, "s": 2124, "text": "Both methods should be in two different classes and, these classes must be in an inheritance relation." }, { "code": null, "e": 2330, "s": 2227, "text": "Both methods should be in two different classes and, these classes must be in an inheritance relation." }, { "code": null, "e": 2459, "s": 2330, "text": "Both methods must have the same name, same parameters and, same return type else they both will be treated as different methods." }, { "code": null, "e": 2588, "s": 2459, "text": "Both methods must have the same name, same parameters and, same return type else they both will be treated as different methods." }, { "code": null, "e": 2747, "s": 2588, "text": "The method in the child class must not have higher access restrictions than the one in the superclass. If you try to do so it raises a compile-time exception." }, { "code": null, "e": 2906, "s": 2747, "text": "The method in the child class must not have higher access restrictions than the one in the superclass. If you try to do so it raises a compile-time exception." }, { "code": null, "e": 3078, "s": 2906, "text": "If the super-class method throws certain exceptions, the method in the sub-class should throw the same exception or its subtype (can leave without throwing any exception)." }, { "code": null, "e": 3250, "s": 3078, "text": "If the super-class method throws certain exceptions, the method in the sub-class should throw the same exception or its subtype (can leave without throwing any exception)." }, { "code": null, "e": 3351, "s": 3250, "text": "Therefore, you cannot override two methods that exist in the same class, you can just overload them." } ]
C# | StringCollection Class - GeeksforGeeks
24 Jan, 2019 StringCollection class is a new addition to the .NET Framework class library that represents a collection of strings. StringCollection class is defined in the System.Collections.Specialized namespace. Characteristics: StringCollection class accepts null as a valid value and allows duplicate elements. String comparisons are case-sensitive. Elements in this collection can be accessed using an integer index. Indexes in this collection are zero-based. Example: // C# code to create a StringCollectionusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver code public static void Main() { // creating a StringCollection named myCol StringCollection myCol = new StringCollection(); // Adding elements in StringCollection myCol.Add("A"); myCol.Add("B"); myCol.Add("C"); myCol.Add("D"); myCol.Add("E"); // Displaying objects in myCol foreach(Object obj in myCol) { Console.WriteLine(obj); } }} Output: A B C D E Example: // C# code to illustrate the StringCollection// Class Propertiesusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver code public static void Main() { // creating a StringCollection named myCol StringCollection myCol = new StringCollection(); // creating a string array named myArr String[] myArr = new String[] { "A", "B", "C", "D", "E" }; // Copying the elements of a string // array to the end of the StringCollection. myCol.AddRange(myArr); // --------- Using IsReadOnly Property --------- // checking if StringCollection is // read-only Console.WriteLine(myCol.IsReadOnly); // --------- Using Count Property --------- // To get number of Strings contained // in the StringCollection Console.WriteLine("Number of strings in myCol are : " + myCol.Count); }} Output: False Number of strings in myCol are : 5 Example: // C# code to copy StringCollection to array,// starting at the specified index of// the target arrayusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver code public static void Main() { // creating a StringCollection named myCol StringCollection myCol = new StringCollection(); // creating a string array named myArr1 String[] myArr1 = new String[] { "A", "B", "C", "D", "E" }; // Copying the elements of a string // array to the end of the StringCollection. myCol.AddRange(myArr1); // creating a String array named myArr2 String[] myArr2 = new String[myCol.Count]; // Copying StringCollection to array myArr2 // starting from index 0 myCol.CopyTo(myArr2, 0); // Displaying elements in array myArr2 for (int i = 0; i < myArr2.Length; i++) { Console.WriteLine(myArr2[i]); } }} Output: A B C D E Example: // C# code to insert a string into// the StringCollection at the// specified indexusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver code public static void Main() { // creating a StringCollection named myCol StringCollection myCol = new StringCollection(); // creating a string array named myArr String[] myArr = new String[] { "Hello", "Geeks", "for", "GeeksforGeeks" }; // Copying the elements of a string // array to the end of the StringCollection. myCol.AddRange(myArr); Console.WriteLine("Initially elements in StringCollection are: "); // Displaying elements in StringCollection // named myCol foreach(Object obj in myCol) Console.WriteLine(obj); // Removing all the elements from StringCollection myCol.Clear(); Console.WriteLine("After Removing: "); // Displaying elements in StringCollection // named myCol foreach(Object obj in myCol) Console.WriteLine(obj); }} Output: Initially elements in StringCollection are: Hello Geeks for GeeksforGeeks After Removing: Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.specialized.stringcollection?view=netframework-4.7.2 CSharp-Collections-Namespace CSharp-Specialized-Namespace CSharp-Specialized-StringCollection C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Introduction to .NET Framework C# | Constructors Partial Classes in C# Difference between Ref and Out keywords in C# C# | Delegates C# | Class and Object Extension Method in C# Basic CRUD (Create, Read, Update, Delete) in ASP.NET MVC Using C# and Entity Framework Top 50 C# Interview Questions & Answers C# | Encapsulation
[ { "code": null, "e": 24025, "s": 23997, "text": "\n24 Jan, 2019" }, { "code": null, "e": 24226, "s": 24025, "text": "StringCollection class is a new addition to the .NET Framework class library that represents a collection of strings. StringCollection class is defined in the System.Collections.Specialized namespace." }, { "code": null, "e": 24243, "s": 24226, "text": "Characteristics:" }, { "code": null, "e": 24327, "s": 24243, "text": "StringCollection class accepts null as a valid value and allows duplicate elements." }, { "code": null, "e": 24366, "s": 24327, "text": "String comparisons are case-sensitive." }, { "code": null, "e": 24434, "s": 24366, "text": "Elements in this collection can be accessed using an integer index." }, { "code": null, "e": 24477, "s": 24434, "text": "Indexes in this collection are zero-based." }, { "code": null, "e": 24486, "s": 24477, "text": "Example:" }, { "code": "// C# code to create a StringCollectionusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver code public static void Main() { // creating a StringCollection named myCol StringCollection myCol = new StringCollection(); // Adding elements in StringCollection myCol.Add(\"A\"); myCol.Add(\"B\"); myCol.Add(\"C\"); myCol.Add(\"D\"); myCol.Add(\"E\"); // Displaying objects in myCol foreach(Object obj in myCol) { Console.WriteLine(obj); } }}", "e": 25074, "s": 24486, "text": null }, { "code": null, "e": 25082, "s": 25074, "text": "Output:" }, { "code": null, "e": 25093, "s": 25082, "text": "A\nB\nC\nD\nE\n" }, { "code": null, "e": 25102, "s": 25093, "text": "Example:" }, { "code": "// C# code to illustrate the StringCollection// Class Propertiesusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver code public static void Main() { // creating a StringCollection named myCol StringCollection myCol = new StringCollection(); // creating a string array named myArr String[] myArr = new String[] { \"A\", \"B\", \"C\", \"D\", \"E\" }; // Copying the elements of a string // array to the end of the StringCollection. myCol.AddRange(myArr); // --------- Using IsReadOnly Property --------- // checking if StringCollection is // read-only Console.WriteLine(myCol.IsReadOnly); // --------- Using Count Property --------- // To get number of Strings contained // in the StringCollection Console.WriteLine(\"Number of strings in myCol are : \" + myCol.Count); }}", "e": 26111, "s": 25102, "text": null }, { "code": null, "e": 26119, "s": 26111, "text": "Output:" }, { "code": null, "e": 26161, "s": 26119, "text": "False\nNumber of strings in myCol are : 5\n" }, { "code": null, "e": 26170, "s": 26161, "text": "Example:" }, { "code": "// C# code to copy StringCollection to array,// starting at the specified index of// the target arrayusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver code public static void Main() { // creating a StringCollection named myCol StringCollection myCol = new StringCollection(); // creating a string array named myArr1 String[] myArr1 = new String[] { \"A\", \"B\", \"C\", \"D\", \"E\" }; // Copying the elements of a string // array to the end of the StringCollection. myCol.AddRange(myArr1); // creating a String array named myArr2 String[] myArr2 = new String[myCol.Count]; // Copying StringCollection to array myArr2 // starting from index 0 myCol.CopyTo(myArr2, 0); // Displaying elements in array myArr2 for (int i = 0; i < myArr2.Length; i++) { Console.WriteLine(myArr2[i]); } }}", "e": 27135, "s": 26170, "text": null }, { "code": null, "e": 27143, "s": 27135, "text": "Output:" }, { "code": null, "e": 27154, "s": 27143, "text": "A\nB\nC\nD\nE\n" }, { "code": null, "e": 27163, "s": 27154, "text": "Example:" }, { "code": "// C# code to insert a string into// the StringCollection at the// specified indexusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver code public static void Main() { // creating a StringCollection named myCol StringCollection myCol = new StringCollection(); // creating a string array named myArr String[] myArr = new String[] { \"Hello\", \"Geeks\", \"for\", \"GeeksforGeeks\" }; // Copying the elements of a string // array to the end of the StringCollection. myCol.AddRange(myArr); Console.WriteLine(\"Initially elements in StringCollection are: \"); // Displaying elements in StringCollection // named myCol foreach(Object obj in myCol) Console.WriteLine(obj); // Removing all the elements from StringCollection myCol.Clear(); Console.WriteLine(\"After Removing: \"); // Displaying elements in StringCollection // named myCol foreach(Object obj in myCol) Console.WriteLine(obj); }}", "e": 28295, "s": 27163, "text": null }, { "code": null, "e": 28303, "s": 28295, "text": "Output:" }, { "code": null, "e": 28395, "s": 28303, "text": "Initially elements in StringCollection are: \nHello\nGeeks\nfor\nGeeksforGeeks\nAfter Removing:\n" }, { "code": null, "e": 28406, "s": 28395, "text": "Reference:" }, { "code": null, "e": 28522, "s": 28406, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.specialized.stringcollection?view=netframework-4.7.2" }, { "code": null, "e": 28551, "s": 28522, "text": "CSharp-Collections-Namespace" }, { "code": null, "e": 28580, "s": 28551, "text": "CSharp-Specialized-Namespace" }, { "code": null, "e": 28616, "s": 28580, "text": "CSharp-Specialized-StringCollection" }, { "code": null, "e": 28619, "s": 28616, "text": "C#" }, { "code": null, "e": 28717, "s": 28619, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28726, "s": 28717, "text": "Comments" }, { "code": null, "e": 28739, "s": 28726, "text": "Old Comments" }, { "code": null, "e": 28770, "s": 28739, "text": "Introduction to .NET Framework" }, { "code": null, "e": 28788, "s": 28770, "text": "C# | Constructors" }, { "code": null, "e": 28810, "s": 28788, "text": "Partial Classes in C#" }, { "code": null, "e": 28856, "s": 28810, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 28871, "s": 28856, "text": "C# | Delegates" }, { "code": null, "e": 28893, "s": 28871, "text": "C# | Class and Object" }, { "code": null, "e": 28916, "s": 28893, "text": "Extension Method in C#" }, { "code": null, "e": 29003, "s": 28916, "text": "Basic CRUD (Create, Read, Update, Delete) in ASP.NET MVC Using C# and Entity Framework" }, { "code": null, "e": 29043, "s": 29003, "text": "Top 50 C# Interview Questions & Answers" } ]
Minimum Moves to Equal Array Elements II in Python
Suppose we have a non-empty integer array, we have to find the minimum number of moves that are required to make all array elements equal, where a move is incrementing or decrementing a selected element by 1. So when the array is like [1, 2, 3], then the output will be 2, as 1 will be incremented to 2, and 3 will be decremented to 2. To solve this, we will follow these steps − sort the array nums set counter as 0 for i in nums, docounter := counter + absolute of (i – nums[length of nums / 2]) counter := counter + absolute of (i – nums[length of nums / 2]) return counter Let us see the following implementation to get a better understanding − Live Demo class Solution: def minMoves2(self, nums): nums.sort() counter = 0 for i in nums: counter += abs(i-nums[len(nums)//2]) return counter ob1 = Solution() print(ob1.minMoves2([2,5,3,4])) [2,5,3,4] 4
[ { "code": null, "e": 1398, "s": 1062, "text": "Suppose we have a non-empty integer array, we have to find the minimum number of moves that are required to make all array elements equal, where a move is incrementing or decrementing a selected element by 1. So when the array is like [1, 2, 3], then the output will be 2, as 1 will be incremented to 2, and 3 will be decremented to 2." }, { "code": null, "e": 1442, "s": 1398, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1462, "s": 1442, "text": "sort the array nums" }, { "code": null, "e": 1479, "s": 1462, "text": "set counter as 0" }, { "code": null, "e": 1560, "s": 1479, "text": "for i in nums, docounter := counter + absolute of (i – nums[length of nums / 2])" }, { "code": null, "e": 1624, "s": 1560, "text": "counter := counter + absolute of (i – nums[length of nums / 2])" }, { "code": null, "e": 1639, "s": 1624, "text": "return counter" }, { "code": null, "e": 1711, "s": 1639, "text": "Let us see the following implementation to get a better understanding −" }, { "code": null, "e": 1722, "s": 1711, "text": " Live Demo" }, { "code": null, "e": 1941, "s": 1722, "text": "class Solution:\n def minMoves2(self, nums):\n nums.sort()\n counter = 0\n for i in nums:\n counter += abs(i-nums[len(nums)//2])\n return counter\nob1 = Solution()\nprint(ob1.minMoves2([2,5,3,4]))" }, { "code": null, "e": 1951, "s": 1941, "text": "[2,5,3,4]" }, { "code": null, "e": 1953, "s": 1951, "text": "4" } ]
Beginner’s Introduction to NLP — Building a Spam Classifier | by Jason Chong | Towards Data Science
Words, sentences, paragraphs and essays. We use them almost every day of our adult lives. Whether you are sending out a tweet, composing an email to your colleague, or writing an article like what I am doing now, as humans, we all use words to communicate our thoughts and our ideas. Now, imagine a world where we could teach computers to interact with words the same way that we would with another human being. Imagine a world where computers are capable of not only detecting human speech but more importantly, capable of learning the nuances of that speech and as a result, derive the underlying meaning or intent of a given message. That is precisely what natural language processing (NLP) is all about. NLP refers to the field within artificial intelligence that deals with the interaction between computers and humans via the natural language. This includes enabling computers to manipulate, analyse, interpret as well as generate human language. I recently had some time to dabble into some basics of NLP and I wanted to use this article as means of not only sharing what I have learned but also further reinforce my understanding of the topic. Specifically, this article was inspired by NLP with Python for Machine Learning Essential Training, a LinkedIn course given by Derek Jedamski. I would like to hereby give full credits and reference to Derek for his work and I highly recommend checking out his other courses on machine learning in Python. My goal with this article is to recreate the main project that was introduced in the course, a spam (binary) classifier built using the SMS spam collection dataset which contains a set of 5,572 SMS messages in English. Once ready, the classifier will be able to read a given string of text and subsequently classify the text as either ham or spam. In this article, I will walk through the steps of building out the spam classifier and along the way, highlight some key concepts in natural language processing. If you would like to follow along, the code for this particular project can be found on my GitHub here. Without further ado, here we go! Like any professional data scientist, let’s begin by first exploring the dataset. Exploratory data analysis is the process of performing an initial investigation on data to discover patterns, spot anomalies, test hypothesis and check assumptions with the help of summary statistics and graphical representations (definition credits to Prasad Patil on “What is Exploratory Data Analysis”). data = pd.read_csv("spam.csv", encoding = "latin-1")data = data.dropna(how = "any", axis = 1)data.columns = ['label', 'body_text']data.head() The input data has 5,572 rows (each row represents a unique text message) and 2 columns: label and body_text. Out of 5,572 rows, 747 of them are spam and the remaining 4,825 are ham. We also have no missing data, yay! Let’s use seaborn for a more visual representation of our input data. total = len(data)plt.figure(figsize = (5, 5))plt.title("Number of spam vs ham messages")ax = sns.countplot(x = 'label', data = data)for p in ax.patches: percentage = '{0:.0f}%'.format(p.get_height() / total * 100) x = p.get_x() + p.get_width() / 2 y = p.get_height() + 20 ax.annotate(percentage, (x, y), ha = 'center')plt.show() As we can see, there are significantly more ham messages (87%) than there are spam messages (13%). Technically speaking, at this stage, we should be concerned about issues related to an unbalanced dataset. However, for the purpose of keeping things simple, let’s just ignore this for now. Feature engineering is the process of creating new features and/or transforming existing features to get the most out of our data. In this section, we will look to create two new features: body_len: length of body text excluding spaces punct%: percentage of punctuation in the body text # body_lendata['body_len'] = data.body_text.apply(lambda x: len(x) - x.count(" "))# punct%def count_punct(text): count = sum([1 for char in text if char in string.punctuation]) return round(count/(len(text) - text.count(" ")), 3) * 100 data[‘punct%’] = data.body_text.apply(lambda x: count_punct(x)) Now, we can proceed to use the newly created features to explore the distribution of our input data. bins = np.linspace(0, 200, 40)data.loc[data.label == 'spam', 'body_len'].plot(kind = 'hist', bins = bins, alpha = 0.5, density = True, label = 'spam')data.loc[data.label == 'ham', 'body_len'].plot(kind = 'hist', bins = bins, alpha = 0.5, density = True, label = 'ham')plt.legend(loc = 'best')plt.xlabel("body_len")plt.title("Body length ham vs spam")plt.show() As we can see, spam messages have a longer body length i.e. contain more words compared to ham messages. Now, what about punctuation percentage? bins = np.linspace(0, 50, 40)data.loc[data.label == 'spam', 'punct%'].plot(kind = 'hist', bins = bins, alpha = 0.5, density = True, label = 'spam')data.loc[data.label == 'ham', 'punct%'].plot(kind = 'hist', bins = bins, alpha = 0.5, density = True, label = 'ham')plt.legend(loc = 'best')plt.xlabel("punct%")plt.title("Punctuation percentage ham vs spam")plt.show() Here, the two distributions look pretty similar although ham messages do appear to have a longer tail i.e. ham messages tend to have a higher punctuation percentage. If you have any experience working with real-world data, you would know that real-world data are oftentimes extremely messy and not so straightforward to process. This one is no exception. There is a lot of work to be done before we can move on to actually modelling and predicting the data. More specifically, in order for us to better manage the messy text messages, we will need to perform the following pre-processing steps (these steps are very specific to the NLP pipeline): Convert words into lowercase letters Remove punctuation and stopwords Tokenisation Stemming vs lemmatisation (text normalisation) Let’s investigate each step one by one. Python does not see all characters as equal. For consistency, we will need to convert all words into lowercase letters. For example, Python will return False to the first statement below but will return True to the second statement. # False statement "NLP" == "nlp"# True statement "NLP".lower() == "nlp" Similar to the argument made above, the rationale for removing punctuation is because punctuation does not hold any meaning in a text. Thus, we want Python to only focus on the words in a given text and not worry about the punctuations that are involved. Let’s take the following as an example. # False statement"I love NLP" == "I love NLP." As humans, we can immediately see that the two texts above are almost exactly identical, except the second one has a period at the end of the sentence. However, Python will fail to distinguish between the two texts. For that reason, it is important that we remove all punctuation in a sentence in order to allow Python to interpret the text more clearly. You can find a list of punctuations that are stored in the string library in Python by typing: string.punctuation And to remove punctuation in a sentence, we can deploy list comprehension as follows: # Original text text = 'OMG! Did you see what happened to her? I was so shocked when I heard the news. :('# List comprehension to remove punctuation text = "".join([word for word in text if word not in string.punctuation]) In the context of NLP, tokenisation means to a string or a sentence into a list of characters and we can accomplish this by utilising the regular expression (re) library in Python. The two most straightforward commands in the library include: re.split re.findall If you are interested to know how they work, I encourage checking out my notebook for more details. Stopwords are commonly used words in the English language like but, if and the that don’t contribute much to the overall meaning of a sentence. Therefore, stopwords are usually removed in order to reduce the number of tokens Python needs to store and process when building our machine learning model. Stopwords are stored in nltk.corpus.stopwords which can be accessed as follows: stopwords = nltk.corpus.stopwords.words('english')stopwords To remove stopwords in a given string, we can again apply list comprehension. # Original text text = 'OMG Did you see what happened to her I was so shocked when I heard the news'print(text)# Convert text into list of words in lowercase lettersprint(text.lower().split())# List comprehension to remove stopwords print([word for word in text.lower().split() if word not in stopwords] After running the code snippet above, the following stopwords will be removed. did you what to her i was so when the Notice that we first turned the original text into a list of lowercase words before running our list comprehension. This is because words are stored in lowercase letters in the nltk library. Stemming: the process of reducing inflection or derived words to their word stem or root by crudely chopping off the ends of a word to leave only the base.Lemmatising: the process of grouping together inflected forms of a word so they can be analyzed as a single term. Broadly speaking, both stemming and lemmatising serve the purpose of condensing the variations of the same word down to their root form. This is to prevent the computer from storing every single unique word it sees in a corpus of words but instead only take note of a word in its most basic form and correlate other words with similar meanings. For example, grew, grown, growing and growth are all simply variations to the word grow. In this case, the computer only needs to remember the word grow and not the rest. To access stemmer and lemmatiser: ps = nltk.PorterStemmer()wn = nltk.WordNetLemmatizer() Stemmer takes a more crude approach than lemmatiser by simply chopping off the end of a word using heuristics, without any knowledge of the context in which a word is used. As a result, stemmer can sometimes not return an actual word in the dictionary. Lemmatiser, on the other hand, will always return a dictionary word. Lemmatiser considers multiple factors before simplifying a given word and is generally more accurate. However, this comes at the cost of being slower and more computationally expensive than stemmer. Awesome, now that we understand all the pre-processing steps that go into text cleaning, we want to summarise everything into a single function called clean_text that we can then apply to our input data. # Create function for text cleaning def clean_text(text): text = "".join([word.lower() for word in text if word not in string.punctuation]) tokens = re.findall('\S+', text) text = [wn.lemmatize(word) for word in tokens if word not in stopwords] return text# Apply function to body_text data['cleaned_text'] = data['body_text'].apply(lambda x: clean_text(x))data[['body_text', 'cleaned_text']].head(10) From there, we can compute the most common words that are observed in ham versus spam messages. Vectorisation is the process of encoding text as integers to create feature vectors. In this section, we will look at three different functions for vectorising text in scikit-learn: CountVectorizer TfidfTransformer TfidfVectorizer CountVectorizer creates a document-term matrix where the entry of each cell will be a count of the number of times that word occurred in that document. TfidfTransformer is similar to that of a CountVectorizer but instead of the cells representing the count, the cells represent a weighting that is meant to identify how important a word is to an individual text message. The formula to compute the weighting for each cell is as follows: To demonstrate this, let’s look at an example. # CountVectorizercorpus = ['I love bananas', 'Bananas are so amazing!', 'Bananas go so well with pancakes']count_vect = CountVectorizer()corpus = count_vect.fit_transform(corpus)pd.DataFrame(corpus.toarray(), columns = count_vect.get_feature_names()) Each row in the dataframe represents a sentence (document) and each column represents a unique word, excluding stopwords, in the entire corpus. For instance, “Bananas are so amazing” have values of 1 (0 in the others) in the amazing, are, bananas and so columns because each one of those words shows up once in that particular sentence. TfidfTransformer, on the other hand, works as follows: # TfidfTransformertfidf_transformer = TfidfTransformer()corpus = tfidf_transformer.fit_transform(corpus)pd.DataFrame(corpus.toarray(), columns = count_vect.get_feature_names()) Recall, the cells in TF-IDF represent a weighting of how important a word is to an individual text message. Let’s take the bananas column as an example. While the word bananas show up only once in each of the three sentences, a higher weighting is assigned to the first sentence compared to the second and third because the first sentence has the shortest length. In other words, the word bananas is more important in the first sentence than it is in the second and the third. The rarer (more infrequent) a word is in a document or corpus, the higher the weighting under TF-IDF. TfidfVectorizer is equivalent to CountVectorizer followed by TfidfTransformer. # TfidfVectorizercorpus = ['I love bananas', 'Bananas are so amazing!', 'Bananas go so well with pancakes']tfidf_vect = TfidfVectorizer()corpus = tfidf_vect.fit_transform(corpus)pd.DataFrame(corpus.toarray(), columns = tfidf_vect.get_feature_names()) As we can see, the result is exactly the same. Therefore, for convenience, we will use TfidfVectorizer for our project. Finally, time for some fun! Now that our data is ready, we can finally move on to modelling, that is actually building our spam filter to classify a given text as ham or spam. Here, we will consider two approaches to modelling: train-test-split and pipeline as well as two types of machine learning models or more specifically, ensemble methods: random forest and gradient boosting. If you are new to machine learning, an ensemble method is essentially a technique whereby multiple models are created and combined with the goal of producing better prediction accuracy than any of the single models individually. # Train test splitX_train, X_test, Y_train, Y_test = train_test_split(data[['body_text', 'body_len', 'punct%']], data.label, random_state = 42, test_size = 0.2)# Instantiate and fit TfidfVectorizertfidf_vect = TfidfVectorizer(analyzer = clean_text)tfidf_vect_fit = tfidf_vect.fit(X_train['body_text'])# Use fitted TfidfVectorizer to transform body text in X_train and X_testtfidf_train = tfidf_vect.transform(X_train['body_text'])tfidf_test = tfidf_vect.transform(X_test['body_text'])# Recombine transformed body text with body_len and punct% featuresX_train = pd.concat([X_train[['body_len', 'punct%']].reset_index(drop = True), pd.DataFrame(tfidf_train.toarray())], axis = 1)X_test = pd.concat([X_test[['body_len', 'punct%']].reset_index(drop = True), pd.DataFrame(tfidf_test.toarray())], axis = 1) RandomForestClassifier is an ensemble learning method that utilises bagging to construct a collection of decision trees and then aggregates the predictions of each tree to determine the final prediction. The key hyperparameters for RandomForestClassifier include: max_depth: maximum depth of each decision tree n_estimators: how many parallel decision trees to build random_state: for reproducibility purpose n_jobs: number of jobs to run in parallel Before we begin training our random forest model on the data, let’s first build a manual grid search, using nested for loops, to find the most optimal set of hyperparameters. def explore_rf_params(n_est, depth): rf = RandomForestClassifier(n_estimators = n_est, max_depth = depth, n_jobs = -1, random_state = 42) rf_model = rf.fit(X_train, Y_train) Y_pred = rf_model.predict(X_test) precision, recall, fscore, support = score(Y_test, Y_pred, pos_label = 'spam', average = 'binary') print(f"Est: {n_est} / Depth: {depth} ---- Precision: {round(precision, 3)} / Recall: {round(recall, 3)} / Accuracy: {round((Y_pred==Y_test).sum() / len(Y_pred), 3)}") for n_est in [50, 100, 150]: for depth in [10, 20, 30, None]: explore_rf_params(n_est, depth) From the output above, we can conclude that: Precision is constant at 1 for all cases Recall and accuracy both improve as max_depth increases with None giving the best results There is very little improvement adding more trees after the 100th tree so we will set n_estimators = 100. Now that we have our hyperparameters, we can proceed to fit our model to the data. # Instantiate RandomForestClassifier with optimal set of hyperparameters rf = RandomForestClassifier(n_estimators = 100, max_depth = None, random_state = 42, n_jobs = -1)# Fit modelstart = time.time()rf_model = rf.fit(X_train, Y_train)end = time.time()fit_time = end - start# Predict start = time.time()Y_pred = rf_model.predict(X_test)end = time.time()pred_time = end - start# Time and prediction resultsprecision, recall, fscore, support = score(Y_test, Y_pred, pos_label = 'spam', average = 'binary')print(f"Fit time: {round(fit_time, 3)} / Predict time: {round(pred_time, 3)}")print(f"Precision: {round(precision, 3)} / Recall: {round(recall, 3)} / Accuracy: {round((Y_pred==Y_test).sum() / len(Y_pred), 3)}") Fit time: 15.684 Predict time: 0.312 Precision: 1.0 Recall: 0.833 Accuracy: 0.978 Alternatively, we can also use a confusion matrix to visualise the result of a binary classification. # Confusion matrix for RandomForestClassifiermatrix = confusion_matrix(Y_test, Y_pred)sns.heatmap(matrix, annot = True, fmt = 'd') GradientBoostingClassifier, on the other hand, is also an ensemble learning method that takes an iterative approach, known as bagging, to combine weak learners to create a strong learner by focusing on mistakes of prior iterations. The key hyperparameters for GradientBoostingClassifier include: learning_rate: weight of each sequential tree on the final prediction max_depth: maximum depth of each decision tree n_estimators: number of sequential trees random_state: for reproducibility purpose Unfortunately, grid search for gradient boosting will take a long time so I have decided to stick with the default hyperparameters for now. # Instantiate GradientBoostingClassifiergb = GradientBoostingClassifier(random_state = 42)# Fit modelstart = time.time()gb_model = gb.fit(X_train, Y_train)end = time.time()fit_time = end - start# Predict start = time.time()Y_pred = gb_model.predict(X_test)end = time.time()pred_time = end - start# Time and prediction resultsprecision, recall, fscore, support = score(Y_test, Y_pred, pos_label = 'spam', average = 'binary')print(f"Fit time: {round(fit_time, 3)} / Predict time: {round(pred_time, 3)}")print(f"Precision: {round(precision, 3)} / Recall: {round(recall, 3)} / Accuracy: {round((Y_pred==Y_test).sum() / len(Y_pred), 3)}") Fit time: 262.863 Predict time: 0.622 Precision: 0.953 Recall: 0.813 Accuracy: 0.97 A pipeline chains together multiple steps in the machine learning workflow where the output of each step is used as input to the next step. # Instantiate TfidfVectorizer, RandomForestClassifier and GradientBoostingClassifier tfidf_vect = TfidfVectorizer(analyzer = clean_text)rf = RandomForestClassifier(random_state = 42, n_jobs = -1)gb = GradientBoostingClassifier(random_state = 42)# Make columns transformertransformer = make_column_transformer((tfidf_vect, 'body_text'), remainder = 'passthrough')# Build two separate pipelines for RandomForestClassifier and GradientBoostingClassifier rf_pipeline = make_pipeline(transformer, rf)gb_pipeline = make_pipeline(transformer, gb)# Perform 5-fold cross validation and compute mean score rf_score = cross_val_score(rf_pipeline, data[['body_text', 'body_len', 'punct%']], data.label, cv = 5, scoring = 'accuracy', n_jobs = -1)gb_score = cross_val_score(gb_pipeline, data[['body_text', 'body_len', 'punct%']], data.label, cv = 5, scoring = 'accuracy', n_jobs = -1)print(f"Random forest score: {round(mean(rf_score), 3)}")print(f"Gradient boosting score: {round(mean(gb_score), 3)}") Random forest score: 0.973 Gradient boosting score: 0.962 While both models, in this particular example, have returned very similar prediction results, it is important to bear in mind the trade-offs that may occur in other scenarios where this is not the case. More specifically, it is worth considering the business context and the overall purpose for which the model is built. For example, in spam classification, it is better to optimise for precision as we can probably deal with some spam messages in our inbox here and there but we definitely don’t want our model to classify an important message as spam. In contrast, in fraud detection, it is much better to optimise for recall as it is more costly if our model fails to identify a real threat (false negative) than it is if it identifies a false threat (false positive). To wrap up, in this article, we have looked at an end-to-end natural language processing (NLP) project which involves building a binary classifier capable of classifying a given text message as spam or ham. We started off by exploring the dataset, followed by feature engineering where we created two new features: body_len and punct%. We then moved on to several preprocessing steps that are specific to the NLP workflow such as: Convert words into lowercase letters Remove punctuation and stopwords Tokenisation Stemming vs lemmatisation (text normalisation) After that, we performed vectorisation using in order to encode text and turn them into feature vectors for machine learning. Finally, we finished off by building two separate prediction models, random forest and gradient boosting, as well as compare their respective accuracy and overall model performance. With that said, thank you so much for reading and I look forward to seeing you in my next article!
[ { "code": null, "e": 456, "s": 172, "text": "Words, sentences, paragraphs and essays. We use them almost every day of our adult lives. Whether you are sending out a tweet, composing an email to your colleague, or writing an article like what I am doing now, as humans, we all use words to communicate our thoughts and our ideas." }, { "code": null, "e": 809, "s": 456, "text": "Now, imagine a world where we could teach computers to interact with words the same way that we would with another human being. Imagine a world where computers are capable of not only detecting human speech but more importantly, capable of learning the nuances of that speech and as a result, derive the underlying meaning or intent of a given message." }, { "code": null, "e": 880, "s": 809, "text": "That is precisely what natural language processing (NLP) is all about." }, { "code": null, "e": 1125, "s": 880, "text": "NLP refers to the field within artificial intelligence that deals with the interaction between computers and humans via the natural language. This includes enabling computers to manipulate, analyse, interpret as well as generate human language." }, { "code": null, "e": 1467, "s": 1125, "text": "I recently had some time to dabble into some basics of NLP and I wanted to use this article as means of not only sharing what I have learned but also further reinforce my understanding of the topic. Specifically, this article was inspired by NLP with Python for Machine Learning Essential Training, a LinkedIn course given by Derek Jedamski." }, { "code": null, "e": 1629, "s": 1467, "text": "I would like to hereby give full credits and reference to Derek for his work and I highly recommend checking out his other courses on machine learning in Python." }, { "code": null, "e": 1977, "s": 1629, "text": "My goal with this article is to recreate the main project that was introduced in the course, a spam (binary) classifier built using the SMS spam collection dataset which contains a set of 5,572 SMS messages in English. Once ready, the classifier will be able to read a given string of text and subsequently classify the text as either ham or spam." }, { "code": null, "e": 2243, "s": 1977, "text": "In this article, I will walk through the steps of building out the spam classifier and along the way, highlight some key concepts in natural language processing. If you would like to follow along, the code for this particular project can be found on my GitHub here." }, { "code": null, "e": 2276, "s": 2243, "text": "Without further ado, here we go!" }, { "code": null, "e": 2358, "s": 2276, "text": "Like any professional data scientist, let’s begin by first exploring the dataset." }, { "code": null, "e": 2665, "s": 2358, "text": "Exploratory data analysis is the process of performing an initial investigation on data to discover patterns, spot anomalies, test hypothesis and check assumptions with the help of summary statistics and graphical representations (definition credits to Prasad Patil on “What is Exploratory Data Analysis”)." }, { "code": null, "e": 2807, "s": 2665, "text": "data = pd.read_csv(\"spam.csv\", encoding = \"latin-1\")data = data.dropna(how = \"any\", axis = 1)data.columns = ['label', 'body_text']data.head()" }, { "code": null, "e": 3025, "s": 2807, "text": "The input data has 5,572 rows (each row represents a unique text message) and 2 columns: label and body_text. Out of 5,572 rows, 747 of them are spam and the remaining 4,825 are ham. We also have no missing data, yay!" }, { "code": null, "e": 3095, "s": 3025, "text": "Let’s use seaborn for a more visual representation of our input data." }, { "code": null, "e": 3436, "s": 3095, "text": "total = len(data)plt.figure(figsize = (5, 5))plt.title(\"Number of spam vs ham messages\")ax = sns.countplot(x = 'label', data = data)for p in ax.patches: percentage = '{0:.0f}%'.format(p.get_height() / total * 100) x = p.get_x() + p.get_width() / 2 y = p.get_height() + 20 ax.annotate(percentage, (x, y), ha = 'center')plt.show()" }, { "code": null, "e": 3535, "s": 3436, "text": "As we can see, there are significantly more ham messages (87%) than there are spam messages (13%)." }, { "code": null, "e": 3725, "s": 3535, "text": "Technically speaking, at this stage, we should be concerned about issues related to an unbalanced dataset. However, for the purpose of keeping things simple, let’s just ignore this for now." }, { "code": null, "e": 3856, "s": 3725, "text": "Feature engineering is the process of creating new features and/or transforming existing features to get the most out of our data." }, { "code": null, "e": 3914, "s": 3856, "text": "In this section, we will look to create two new features:" }, { "code": null, "e": 3961, "s": 3914, "text": "body_len: length of body text excluding spaces" }, { "code": null, "e": 4012, "s": 3961, "text": "punct%: percentage of punctuation in the body text" }, { "code": null, "e": 4318, "s": 4012, "text": "# body_lendata['body_len'] = data.body_text.apply(lambda x: len(x) - x.count(\" \"))# punct%def count_punct(text): count = sum([1 for char in text if char in string.punctuation]) return round(count/(len(text) - text.count(\" \")), 3) * 100 data[‘punct%’] = data.body_text.apply(lambda x: count_punct(x))" }, { "code": null, "e": 4419, "s": 4318, "text": "Now, we can proceed to use the newly created features to explore the distribution of our input data." }, { "code": null, "e": 4780, "s": 4419, "text": "bins = np.linspace(0, 200, 40)data.loc[data.label == 'spam', 'body_len'].plot(kind = 'hist', bins = bins, alpha = 0.5, density = True, label = 'spam')data.loc[data.label == 'ham', 'body_len'].plot(kind = 'hist', bins = bins, alpha = 0.5, density = True, label = 'ham')plt.legend(loc = 'best')plt.xlabel(\"body_len\")plt.title(\"Body length ham vs spam\")plt.show()" }, { "code": null, "e": 4885, "s": 4780, "text": "As we can see, spam messages have a longer body length i.e. contain more words compared to ham messages." }, { "code": null, "e": 4925, "s": 4885, "text": "Now, what about punctuation percentage?" }, { "code": null, "e": 5290, "s": 4925, "text": "bins = np.linspace(0, 50, 40)data.loc[data.label == 'spam', 'punct%'].plot(kind = 'hist', bins = bins, alpha = 0.5, density = True, label = 'spam')data.loc[data.label == 'ham', 'punct%'].plot(kind = 'hist', bins = bins, alpha = 0.5, density = True, label = 'ham')plt.legend(loc = 'best')plt.xlabel(\"punct%\")plt.title(\"Punctuation percentage ham vs spam\")plt.show()" }, { "code": null, "e": 5456, "s": 5290, "text": "Here, the two distributions look pretty similar although ham messages do appear to have a longer tail i.e. ham messages tend to have a higher punctuation percentage." }, { "code": null, "e": 5645, "s": 5456, "text": "If you have any experience working with real-world data, you would know that real-world data are oftentimes extremely messy and not so straightforward to process. This one is no exception." }, { "code": null, "e": 5937, "s": 5645, "text": "There is a lot of work to be done before we can move on to actually modelling and predicting the data. More specifically, in order for us to better manage the messy text messages, we will need to perform the following pre-processing steps (these steps are very specific to the NLP pipeline):" }, { "code": null, "e": 5974, "s": 5937, "text": "Convert words into lowercase letters" }, { "code": null, "e": 6007, "s": 5974, "text": "Remove punctuation and stopwords" }, { "code": null, "e": 6020, "s": 6007, "text": "Tokenisation" }, { "code": null, "e": 6067, "s": 6020, "text": "Stemming vs lemmatisation (text normalisation)" }, { "code": null, "e": 6107, "s": 6067, "text": "Let’s investigate each step one by one." }, { "code": null, "e": 6340, "s": 6107, "text": "Python does not see all characters as equal. For consistency, we will need to convert all words into lowercase letters. For example, Python will return False to the first statement below but will return True to the second statement." }, { "code": null, "e": 6412, "s": 6340, "text": "# False statement \"NLP\" == \"nlp\"# True statement \"NLP\".lower() == \"nlp\"" }, { "code": null, "e": 6667, "s": 6412, "text": "Similar to the argument made above, the rationale for removing punctuation is because punctuation does not hold any meaning in a text. Thus, we want Python to only focus on the words in a given text and not worry about the punctuations that are involved." }, { "code": null, "e": 6707, "s": 6667, "text": "Let’s take the following as an example." }, { "code": null, "e": 6754, "s": 6707, "text": "# False statement\"I love NLP\" == \"I love NLP.\"" }, { "code": null, "e": 6906, "s": 6754, "text": "As humans, we can immediately see that the two texts above are almost exactly identical, except the second one has a period at the end of the sentence." }, { "code": null, "e": 7109, "s": 6906, "text": "However, Python will fail to distinguish between the two texts. For that reason, it is important that we remove all punctuation in a sentence in order to allow Python to interpret the text more clearly." }, { "code": null, "e": 7204, "s": 7109, "text": "You can find a list of punctuations that are stored in the string library in Python by typing:" }, { "code": null, "e": 7223, "s": 7204, "text": "string.punctuation" }, { "code": null, "e": 7309, "s": 7223, "text": "And to remove punctuation in a sentence, we can deploy list comprehension as follows:" }, { "code": null, "e": 7532, "s": 7309, "text": "# Original text text = 'OMG! Did you see what happened to her? I was so shocked when I heard the news. :('# List comprehension to remove punctuation text = \"\".join([word for word in text if word not in string.punctuation])" }, { "code": null, "e": 7713, "s": 7532, "text": "In the context of NLP, tokenisation means to a string or a sentence into a list of characters and we can accomplish this by utilising the regular expression (re) library in Python." }, { "code": null, "e": 7775, "s": 7713, "text": "The two most straightforward commands in the library include:" }, { "code": null, "e": 7784, "s": 7775, "text": "re.split" }, { "code": null, "e": 7795, "s": 7784, "text": "re.findall" }, { "code": null, "e": 7895, "s": 7795, "text": "If you are interested to know how they work, I encourage checking out my notebook for more details." }, { "code": null, "e": 8196, "s": 7895, "text": "Stopwords are commonly used words in the English language like but, if and the that don’t contribute much to the overall meaning of a sentence. Therefore, stopwords are usually removed in order to reduce the number of tokens Python needs to store and process when building our machine learning model." }, { "code": null, "e": 8276, "s": 8196, "text": "Stopwords are stored in nltk.corpus.stopwords which can be accessed as follows:" }, { "code": null, "e": 8336, "s": 8276, "text": "stopwords = nltk.corpus.stopwords.words('english')stopwords" }, { "code": null, "e": 8414, "s": 8336, "text": "To remove stopwords in a given string, we can again apply list comprehension." }, { "code": null, "e": 8718, "s": 8414, "text": "# Original text text = 'OMG Did you see what happened to her I was so shocked when I heard the news'print(text)# Convert text into list of words in lowercase lettersprint(text.lower().split())# List comprehension to remove stopwords print([word for word in text.lower().split() if word not in stopwords]" }, { "code": null, "e": 8797, "s": 8718, "text": "After running the code snippet above, the following stopwords will be removed." }, { "code": null, "e": 8801, "s": 8797, "text": "did" }, { "code": null, "e": 8805, "s": 8801, "text": "you" }, { "code": null, "e": 8810, "s": 8805, "text": "what" }, { "code": null, "e": 8813, "s": 8810, "text": "to" }, { "code": null, "e": 8817, "s": 8813, "text": "her" }, { "code": null, "e": 8819, "s": 8817, "text": "i" }, { "code": null, "e": 8823, "s": 8819, "text": "was" }, { "code": null, "e": 8826, "s": 8823, "text": "so" }, { "code": null, "e": 8831, "s": 8826, "text": "when" }, { "code": null, "e": 8835, "s": 8831, "text": "the" }, { "code": null, "e": 9026, "s": 8835, "text": "Notice that we first turned the original text into a list of lowercase words before running our list comprehension. This is because words are stored in lowercase letters in the nltk library." }, { "code": null, "e": 9295, "s": 9026, "text": "Stemming: the process of reducing inflection or derived words to their word stem or root by crudely chopping off the ends of a word to leave only the base.Lemmatising: the process of grouping together inflected forms of a word so they can be analyzed as a single term." }, { "code": null, "e": 9640, "s": 9295, "text": "Broadly speaking, both stemming and lemmatising serve the purpose of condensing the variations of the same word down to their root form. This is to prevent the computer from storing every single unique word it sees in a corpus of words but instead only take note of a word in its most basic form and correlate other words with similar meanings." }, { "code": null, "e": 9811, "s": 9640, "text": "For example, grew, grown, growing and growth are all simply variations to the word grow. In this case, the computer only needs to remember the word grow and not the rest." }, { "code": null, "e": 9845, "s": 9811, "text": "To access stemmer and lemmatiser:" }, { "code": null, "e": 9900, "s": 9845, "text": "ps = nltk.PorterStemmer()wn = nltk.WordNetLemmatizer()" }, { "code": null, "e": 10153, "s": 9900, "text": "Stemmer takes a more crude approach than lemmatiser by simply chopping off the end of a word using heuristics, without any knowledge of the context in which a word is used. As a result, stemmer can sometimes not return an actual word in the dictionary." }, { "code": null, "e": 10421, "s": 10153, "text": "Lemmatiser, on the other hand, will always return a dictionary word. Lemmatiser considers multiple factors before simplifying a given word and is generally more accurate. However, this comes at the cost of being slower and more computationally expensive than stemmer." }, { "code": null, "e": 10625, "s": 10421, "text": "Awesome, now that we understand all the pre-processing steps that go into text cleaning, we want to summarise everything into a single function called clean_text that we can then apply to our input data." }, { "code": null, "e": 11039, "s": 10625, "text": "# Create function for text cleaning def clean_text(text): text = \"\".join([word.lower() for word in text if word not in string.punctuation]) tokens = re.findall('\\S+', text) text = [wn.lemmatize(word) for word in tokens if word not in stopwords] return text# Apply function to body_text data['cleaned_text'] = data['body_text'].apply(lambda x: clean_text(x))data[['body_text', 'cleaned_text']].head(10)" }, { "code": null, "e": 11135, "s": 11039, "text": "From there, we can compute the most common words that are observed in ham versus spam messages." }, { "code": null, "e": 11220, "s": 11135, "text": "Vectorisation is the process of encoding text as integers to create feature vectors." }, { "code": null, "e": 11317, "s": 11220, "text": "In this section, we will look at three different functions for vectorising text in scikit-learn:" }, { "code": null, "e": 11333, "s": 11317, "text": "CountVectorizer" }, { "code": null, "e": 11350, "s": 11333, "text": "TfidfTransformer" }, { "code": null, "e": 11366, "s": 11350, "text": "TfidfVectorizer" }, { "code": null, "e": 11518, "s": 11366, "text": "CountVectorizer creates a document-term matrix where the entry of each cell will be a count of the number of times that word occurred in that document." }, { "code": null, "e": 11803, "s": 11518, "text": "TfidfTransformer is similar to that of a CountVectorizer but instead of the cells representing the count, the cells represent a weighting that is meant to identify how important a word is to an individual text message. The formula to compute the weighting for each cell is as follows:" }, { "code": null, "e": 11850, "s": 11803, "text": "To demonstrate this, let’s look at an example." }, { "code": null, "e": 12101, "s": 11850, "text": "# CountVectorizercorpus = ['I love bananas', 'Bananas are so amazing!', 'Bananas go so well with pancakes']count_vect = CountVectorizer()corpus = count_vect.fit_transform(corpus)pd.DataFrame(corpus.toarray(), columns = count_vect.get_feature_names())" }, { "code": null, "e": 12438, "s": 12101, "text": "Each row in the dataframe represents a sentence (document) and each column represents a unique word, excluding stopwords, in the entire corpus. For instance, “Bananas are so amazing” have values of 1 (0 in the others) in the amazing, are, bananas and so columns because each one of those words shows up once in that particular sentence." }, { "code": null, "e": 12493, "s": 12438, "text": "TfidfTransformer, on the other hand, works as follows:" }, { "code": null, "e": 12670, "s": 12493, "text": "# TfidfTransformertfidf_transformer = TfidfTransformer()corpus = tfidf_transformer.fit_transform(corpus)pd.DataFrame(corpus.toarray(), columns = count_vect.get_feature_names())" }, { "code": null, "e": 12778, "s": 12670, "text": "Recall, the cells in TF-IDF represent a weighting of how important a word is to an individual text message." }, { "code": null, "e": 13147, "s": 12778, "text": "Let’s take the bananas column as an example. While the word bananas show up only once in each of the three sentences, a higher weighting is assigned to the first sentence compared to the second and third because the first sentence has the shortest length. In other words, the word bananas is more important in the first sentence than it is in the second and the third." }, { "code": null, "e": 13249, "s": 13147, "text": "The rarer (more infrequent) a word is in a document or corpus, the higher the weighting under TF-IDF." }, { "code": null, "e": 13328, "s": 13249, "text": "TfidfVectorizer is equivalent to CountVectorizer followed by TfidfTransformer." }, { "code": null, "e": 13579, "s": 13328, "text": "# TfidfVectorizercorpus = ['I love bananas', 'Bananas are so amazing!', 'Bananas go so well with pancakes']tfidf_vect = TfidfVectorizer()corpus = tfidf_vect.fit_transform(corpus)pd.DataFrame(corpus.toarray(), columns = tfidf_vect.get_feature_names())" }, { "code": null, "e": 13699, "s": 13579, "text": "As we can see, the result is exactly the same. Therefore, for convenience, we will use TfidfVectorizer for our project." }, { "code": null, "e": 13727, "s": 13699, "text": "Finally, time for some fun!" }, { "code": null, "e": 13875, "s": 13727, "text": "Now that our data is ready, we can finally move on to modelling, that is actually building our spam filter to classify a given text as ham or spam." }, { "code": null, "e": 14082, "s": 13875, "text": "Here, we will consider two approaches to modelling: train-test-split and pipeline as well as two types of machine learning models or more specifically, ensemble methods: random forest and gradient boosting." }, { "code": null, "e": 14311, "s": 14082, "text": "If you are new to machine learning, an ensemble method is essentially a technique whereby multiple models are created and combined with the goal of producing better prediction accuracy than any of the single models individually." }, { "code": null, "e": 15112, "s": 14311, "text": "# Train test splitX_train, X_test, Y_train, Y_test = train_test_split(data[['body_text', 'body_len', 'punct%']], data.label, random_state = 42, test_size = 0.2)# Instantiate and fit TfidfVectorizertfidf_vect = TfidfVectorizer(analyzer = clean_text)tfidf_vect_fit = tfidf_vect.fit(X_train['body_text'])# Use fitted TfidfVectorizer to transform body text in X_train and X_testtfidf_train = tfidf_vect.transform(X_train['body_text'])tfidf_test = tfidf_vect.transform(X_test['body_text'])# Recombine transformed body text with body_len and punct% featuresX_train = pd.concat([X_train[['body_len', 'punct%']].reset_index(drop = True), pd.DataFrame(tfidf_train.toarray())], axis = 1)X_test = pd.concat([X_test[['body_len', 'punct%']].reset_index(drop = True), pd.DataFrame(tfidf_test.toarray())], axis = 1)" }, { "code": null, "e": 15316, "s": 15112, "text": "RandomForestClassifier is an ensemble learning method that utilises bagging to construct a collection of decision trees and then aggregates the predictions of each tree to determine the final prediction." }, { "code": null, "e": 15376, "s": 15316, "text": "The key hyperparameters for RandomForestClassifier include:" }, { "code": null, "e": 15423, "s": 15376, "text": "max_depth: maximum depth of each decision tree" }, { "code": null, "e": 15479, "s": 15423, "text": "n_estimators: how many parallel decision trees to build" }, { "code": null, "e": 15521, "s": 15479, "text": "random_state: for reproducibility purpose" }, { "code": null, "e": 15563, "s": 15521, "text": "n_jobs: number of jobs to run in parallel" }, { "code": null, "e": 15738, "s": 15563, "text": "Before we begin training our random forest model on the data, let’s first build a manual grid search, using nested for loops, to find the most optimal set of hyperparameters." }, { "code": null, "e": 16335, "s": 15738, "text": "def explore_rf_params(n_est, depth): rf = RandomForestClassifier(n_estimators = n_est, max_depth = depth, n_jobs = -1, random_state = 42) rf_model = rf.fit(X_train, Y_train) Y_pred = rf_model.predict(X_test) precision, recall, fscore, support = score(Y_test, Y_pred, pos_label = 'spam', average = 'binary') print(f\"Est: {n_est} / Depth: {depth} ---- Precision: {round(precision, 3)} / Recall: {round(recall, 3)} / Accuracy: {round((Y_pred==Y_test).sum() / len(Y_pred), 3)}\") for n_est in [50, 100, 150]: for depth in [10, 20, 30, None]: explore_rf_params(n_est, depth)" }, { "code": null, "e": 16380, "s": 16335, "text": "From the output above, we can conclude that:" }, { "code": null, "e": 16421, "s": 16380, "text": "Precision is constant at 1 for all cases" }, { "code": null, "e": 16511, "s": 16421, "text": "Recall and accuracy both improve as max_depth increases with None giving the best results" }, { "code": null, "e": 16618, "s": 16511, "text": "There is very little improvement adding more trees after the 100th tree so we will set n_estimators = 100." }, { "code": null, "e": 16701, "s": 16618, "text": "Now that we have our hyperparameters, we can proceed to fit our model to the data." }, { "code": null, "e": 17415, "s": 16701, "text": "# Instantiate RandomForestClassifier with optimal set of hyperparameters rf = RandomForestClassifier(n_estimators = 100, max_depth = None, random_state = 42, n_jobs = -1)# Fit modelstart = time.time()rf_model = rf.fit(X_train, Y_train)end = time.time()fit_time = end - start# Predict start = time.time()Y_pred = rf_model.predict(X_test)end = time.time()pred_time = end - start# Time and prediction resultsprecision, recall, fscore, support = score(Y_test, Y_pred, pos_label = 'spam', average = 'binary')print(f\"Fit time: {round(fit_time, 3)} / Predict time: {round(pred_time, 3)}\")print(f\"Precision: {round(precision, 3)} / Recall: {round(recall, 3)} / Accuracy: {round((Y_pred==Y_test).sum() / len(Y_pred), 3)}\")" }, { "code": null, "e": 17432, "s": 17415, "text": "Fit time: 15.684" }, { "code": null, "e": 17452, "s": 17432, "text": "Predict time: 0.312" }, { "code": null, "e": 17467, "s": 17452, "text": "Precision: 1.0" }, { "code": null, "e": 17481, "s": 17467, "text": "Recall: 0.833" }, { "code": null, "e": 17497, "s": 17481, "text": "Accuracy: 0.978" }, { "code": null, "e": 17599, "s": 17497, "text": "Alternatively, we can also use a confusion matrix to visualise the result of a binary classification." }, { "code": null, "e": 17730, "s": 17599, "text": "# Confusion matrix for RandomForestClassifiermatrix = confusion_matrix(Y_test, Y_pred)sns.heatmap(matrix, annot = True, fmt = 'd')" }, { "code": null, "e": 17962, "s": 17730, "text": "GradientBoostingClassifier, on the other hand, is also an ensemble learning method that takes an iterative approach, known as bagging, to combine weak learners to create a strong learner by focusing on mistakes of prior iterations." }, { "code": null, "e": 18026, "s": 17962, "text": "The key hyperparameters for GradientBoostingClassifier include:" }, { "code": null, "e": 18096, "s": 18026, "text": "learning_rate: weight of each sequential tree on the final prediction" }, { "code": null, "e": 18143, "s": 18096, "text": "max_depth: maximum depth of each decision tree" }, { "code": null, "e": 18184, "s": 18143, "text": "n_estimators: number of sequential trees" }, { "code": null, "e": 18226, "s": 18184, "text": "random_state: for reproducibility purpose" }, { "code": null, "e": 18366, "s": 18226, "text": "Unfortunately, grid search for gradient boosting will take a long time so I have decided to stick with the default hyperparameters for now." }, { "code": null, "e": 19000, "s": 18366, "text": "# Instantiate GradientBoostingClassifiergb = GradientBoostingClassifier(random_state = 42)# Fit modelstart = time.time()gb_model = gb.fit(X_train, Y_train)end = time.time()fit_time = end - start# Predict start = time.time()Y_pred = gb_model.predict(X_test)end = time.time()pred_time = end - start# Time and prediction resultsprecision, recall, fscore, support = score(Y_test, Y_pred, pos_label = 'spam', average = 'binary')print(f\"Fit time: {round(fit_time, 3)} / Predict time: {round(pred_time, 3)}\")print(f\"Precision: {round(precision, 3)} / Recall: {round(recall, 3)} / Accuracy: {round((Y_pred==Y_test).sum() / len(Y_pred), 3)}\")" }, { "code": null, "e": 19018, "s": 19000, "text": "Fit time: 262.863" }, { "code": null, "e": 19038, "s": 19018, "text": "Predict time: 0.622" }, { "code": null, "e": 19055, "s": 19038, "text": "Precision: 0.953" }, { "code": null, "e": 19069, "s": 19055, "text": "Recall: 0.813" }, { "code": null, "e": 19084, "s": 19069, "text": "Accuracy: 0.97" }, { "code": null, "e": 19224, "s": 19084, "text": "A pipeline chains together multiple steps in the machine learning workflow where the output of each step is used as input to the next step." }, { "code": null, "e": 20213, "s": 19224, "text": "# Instantiate TfidfVectorizer, RandomForestClassifier and GradientBoostingClassifier tfidf_vect = TfidfVectorizer(analyzer = clean_text)rf = RandomForestClassifier(random_state = 42, n_jobs = -1)gb = GradientBoostingClassifier(random_state = 42)# Make columns transformertransformer = make_column_transformer((tfidf_vect, 'body_text'), remainder = 'passthrough')# Build two separate pipelines for RandomForestClassifier and GradientBoostingClassifier rf_pipeline = make_pipeline(transformer, rf)gb_pipeline = make_pipeline(transformer, gb)# Perform 5-fold cross validation and compute mean score rf_score = cross_val_score(rf_pipeline, data[['body_text', 'body_len', 'punct%']], data.label, cv = 5, scoring = 'accuracy', n_jobs = -1)gb_score = cross_val_score(gb_pipeline, data[['body_text', 'body_len', 'punct%']], data.label, cv = 5, scoring = 'accuracy', n_jobs = -1)print(f\"Random forest score: {round(mean(rf_score), 3)}\")print(f\"Gradient boosting score: {round(mean(gb_score), 3)}\")" }, { "code": null, "e": 20240, "s": 20213, "text": "Random forest score: 0.973" }, { "code": null, "e": 20271, "s": 20240, "text": "Gradient boosting score: 0.962" }, { "code": null, "e": 20592, "s": 20271, "text": "While both models, in this particular example, have returned very similar prediction results, it is important to bear in mind the trade-offs that may occur in other scenarios where this is not the case. More specifically, it is worth considering the business context and the overall purpose for which the model is built." }, { "code": null, "e": 21043, "s": 20592, "text": "For example, in spam classification, it is better to optimise for precision as we can probably deal with some spam messages in our inbox here and there but we definitely don’t want our model to classify an important message as spam. In contrast, in fraud detection, it is much better to optimise for recall as it is more costly if our model fails to identify a real threat (false negative) than it is if it identifies a false threat (false positive)." }, { "code": null, "e": 21250, "s": 21043, "text": "To wrap up, in this article, we have looked at an end-to-end natural language processing (NLP) project which involves building a binary classifier capable of classifying a given text message as spam or ham." }, { "code": null, "e": 21474, "s": 21250, "text": "We started off by exploring the dataset, followed by feature engineering where we created two new features: body_len and punct%. We then moved on to several preprocessing steps that are specific to the NLP workflow such as:" }, { "code": null, "e": 21511, "s": 21474, "text": "Convert words into lowercase letters" }, { "code": null, "e": 21544, "s": 21511, "text": "Remove punctuation and stopwords" }, { "code": null, "e": 21557, "s": 21544, "text": "Tokenisation" }, { "code": null, "e": 21604, "s": 21557, "text": "Stemming vs lemmatisation (text normalisation)" }, { "code": null, "e": 21912, "s": 21604, "text": "After that, we performed vectorisation using in order to encode text and turn them into feature vectors for machine learning. Finally, we finished off by building two separate prediction models, random forest and gradient boosting, as well as compare their respective accuracy and overall model performance." } ]
How to open browser window in incognito/private mode using python selenium webdriver?
We can open a browser window in incognito/private mode with Selenium webdriver in Python using the ChromeOptions class. We have to create an object of the ChromeOptions class. Then apply the method add_argument to that object and pass the parameter -- incognito has a parameter. Finally, this information has to be passed to the webdriver object. c = webdriver.ChromeOptions() c.add_argument("--incognito") from selenium import webdriver #object of ChromeOptions class c = webdriver.ChromeOptions() #incognito parameter passed c.add_argument("--incognito") #set chromodriver.exe path driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe",options=c) driver.implicitly_wait(0.5) #launch URL driver.get("https://www.tutorialspoint.com/tutor_connect/index.php")
[ { "code": null, "e": 1238, "s": 1062, "text": "We can open a browser window in incognito/private mode with Selenium webdriver in Python using the ChromeOptions class. We have to create an object of the ChromeOptions class." }, { "code": null, "e": 1409, "s": 1238, "text": "Then apply the method add_argument to that object and pass the parameter -- incognito has a parameter. Finally, this information has to be passed to the webdriver object." }, { "code": null, "e": 1469, "s": 1409, "text": "c = webdriver.ChromeOptions()\nc.add_argument(\"--incognito\")" }, { "code": null, "e": 1831, "s": 1469, "text": "from selenium import webdriver\n#object of ChromeOptions class\nc = webdriver.ChromeOptions()\n#incognito parameter passed\nc.add_argument(\"--incognito\")\n#set chromodriver.exe path\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\",options=c)\ndriver.implicitly_wait(0.5)\n#launch URL\ndriver.get(\"https://www.tutorialspoint.com/tutor_connect/index.php\")" } ]
Count numbers which are divisible by all the numbers from 2 to 10 in C++
We are given a number let’s say, num and the task is to calculate the count of numbers in the range 1 to num that are divisible by 2, 3, 4, 5, 6, 7, 8, 9 and 10. Input − int num = 10000 Output − Count numbers which are divisible by all the numbers from 2 to 10 are: 3 Explanation − There are 3 numbers from 1 to 10000 that are divisible by all the numbers starting from 2 till 10 and those are − 2520-: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 15, 18, 20, 21, 24, 28, 30, 35, 36, 40, 42, 45, 56, 60, 63, 70, 72, 84, 90, 105, 120, 126, 140, 168, 180, 210, 252, 280, 315, 360, 420, 504, 630, 840, 1260, 2520. 5040-: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 24, 28, 30, 35, 36, 40, 42, 45, 48, 56, 60, 63, 70, 72, 80, 84, 90, 105, 112, 120, 126, 140, 144, 168, 180, 210, 240, 252, 280, 315, 336, 360, 420, 504, 560, 630, 720, 840, 1008, 1260, 1680, 2520, 5040 7560-: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 15, 18, 20, 21, 24, 27, 28, 30, 35, 36, 40, 42, 45, 54, 56, 60, 63, 70, 72, 84, 90, 105, 108, 120, 126, 135, 140, 168, 180, 189, 210, 216, 252, 270, 280, 315, 360, 378, 420, 504, 540, 630, 756, 840, 945, 1080, 1260, 1512, 1890, 2520, 3780. Input − int num = 20000 Output − Count numbers which are divisible by all the numbers from 2 to 10 are − 3 Explanation − There are 7 numbers from 1 to 10000 that are divisible by all the numbers starting from 2 till 10 and those are − 2520, 5040, 7560, 10080, 12600, 15120 and 17640, There can be multiple approaches to solve the given problem i.e. naive approach and efficient approach. So let’s first look at the naive approach. Input the number let’s say num Input the number let’s say num Take an array and store all the numbers from 2 to 10 inside an integer array of fixed length which is 9. Take an array and store all the numbers from 2 to 10 inside an integer array of fixed length which is 9. Take temporary variables first is count to store the total of numbers and another is flag to check whether the number is divisible or not. Take temporary variables first is count to store the total of numbers and another is flag to check whether the number is divisible or not. Start loop For from i to 1 till the num Start loop For from i to 1 till the num Inside the loop, set num to i and index to 0 Inside the loop, set num to i and index to 0 Start while till index is less than 9 i.e. size of an array Start while till index is less than 9 i.e. size of an array Check IF num % arr[index++] == 0 then set flag as 1 Else set flag as 0 Check IF num % arr[index++] == 0 then set flag as 1 Else set flag as 0 Check IF flag is 1 then increment the count by 1 Check IF flag is 1 then increment the count by 1 Return count Return count Print the result. Print the result. As we can see there is a pattern in the numbers that is divisible by all the numbers from 2 to 10. The smallest number which is divisible by all the numbers from 2 to 10 is 2520 5 * 7 * 8 * 9 = 2520(n = 1) 5 * 7 * 8 * 9 * 2 = 5040(n = 2) 5 * 7 * 8 * 9 * 3 = 7560(n = 3) . . As we can see 2520 is the common factor of all the numbers divisible by 2, 3, 4, 5, 6, 7, 8, 9, 10. so , if we divide the given number by 2520 we will get our result. Live Demo #include <bits/stdc++.h> using namespace std; int count(int num){ int count = 0; int flag=0; int index=0; int arr[9] = {2, 3, 4, 5, 6, 7, 8, 9, 10 }; for (int i = 1; i <= num; i++){ int num = i; index=0; while(index<9){ if(num % arr[index++] == 0){ flag=1; } else{ flag=0; break; } } if (flag == 1){ count++; } } return count; } int main(){ int num = 10000; cout<<"Count numbers which are divisible by all the numbers from 2 to 10 are: "<<count(num); return 0; } If we run the above code it will generate the following output − Count numbers which are divisible by all the numbers from 2 to 10 are: 3 Live Demo #include <bits/stdc++.h> using namespace std; int main(){ int num = 10000; int count = num / 2520; cout<<"Count numbers which are divisible by all the numbers from 2 to 10 are: "<<count; return 0; } If we run the above code it will generate the following output − Count numbers which are divisible by all the numbers from 2 to 10 are: 3
[ { "code": null, "e": 1224, "s": 1062, "text": "We are given a number let’s say, num and the task is to calculate the count of numbers in the range 1 to num that are divisible by 2, 3, 4, 5, 6, 7, 8, 9 and 10." }, { "code": null, "e": 1248, "s": 1224, "text": "Input − int num = 10000" }, { "code": null, "e": 1330, "s": 1248, "text": "Output − Count numbers which are divisible by all the numbers from 2 to 10 are: 3" }, { "code": null, "e": 1458, "s": 1330, "text": "Explanation − There are 3 numbers from 1 to 10000 that are divisible by all the numbers starting from 2 till 10 and those are −" }, { "code": null, "e": 2221, "s": 1458, "text": "2520-: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 15, 18, 20, 21, 24, 28, 30, 35, 36, 40, 42, 45, 56, 60, 63, 70, 72, 84, 90, 105, 120, 126, 140, 168, 180, 210, 252, 280, 315, 360, 420, 504, 630, 840, 1260, 2520.\n5040-: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 24, 28, 30, 35, 36, 40, 42, 45, 48, 56, 60, 63, 70, 72, 80, 84, 90, 105, 112, 120, 126, 140, 144, 168, 180, 210, 240, 252, 280, 315, 336, 360, 420, 504, 560, 630, 720, 840, 1008, 1260, 1680, 2520, 5040\n7560-: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 15, 18, 20, 21, 24, 27, 28, 30, 35, 36, 40, 42, 45, 54, 56, 60, 63, 70, 72, 84, 90, 105, 108, 120, 126, 135, 140, 168, 180, 189, 210, 216, 252, 270, 280, 315, 360, 378, 420, 504, 540, 630, 756, 840, 945, 1080, 1260, 1512, 1890, 2520, 3780." }, { "code": null, "e": 2245, "s": 2221, "text": "Input − int num = 20000" }, { "code": null, "e": 2328, "s": 2245, "text": "Output − Count numbers which are divisible by all the numbers from 2 to 10 are − 3" }, { "code": null, "e": 2505, "s": 2328, "text": "Explanation − There are 7 numbers from 1 to 10000 that are divisible by all the numbers starting from 2 till 10 and those are − 2520, 5040, 7560, 10080, 12600, 15120 and 17640," }, { "code": null, "e": 2652, "s": 2505, "text": "There can be multiple approaches to solve the given problem i.e. naive approach and efficient approach. So let’s first look at the naive approach." }, { "code": null, "e": 2683, "s": 2652, "text": "Input the number let’s say num" }, { "code": null, "e": 2714, "s": 2683, "text": "Input the number let’s say num" }, { "code": null, "e": 2819, "s": 2714, "text": "Take an array and store all the numbers from 2 to 10 inside an integer array of fixed length which is 9." }, { "code": null, "e": 2924, "s": 2819, "text": "Take an array and store all the numbers from 2 to 10 inside an integer array of fixed length which is 9." }, { "code": null, "e": 3063, "s": 2924, "text": "Take temporary variables first is count to store the total of numbers and another is flag to check whether the number is divisible or not." }, { "code": null, "e": 3202, "s": 3063, "text": "Take temporary variables first is count to store the total of numbers and another is flag to check whether the number is divisible or not." }, { "code": null, "e": 3242, "s": 3202, "text": "Start loop For from i to 1 till the num" }, { "code": null, "e": 3282, "s": 3242, "text": "Start loop For from i to 1 till the num" }, { "code": null, "e": 3327, "s": 3282, "text": "Inside the loop, set num to i and index to 0" }, { "code": null, "e": 3372, "s": 3327, "text": "Inside the loop, set num to i and index to 0" }, { "code": null, "e": 3432, "s": 3372, "text": "Start while till index is less than 9 i.e. size of an array" }, { "code": null, "e": 3492, "s": 3432, "text": "Start while till index is less than 9 i.e. size of an array" }, { "code": null, "e": 3563, "s": 3492, "text": "Check IF num % arr[index++] == 0 then set flag as 1 Else set flag as 0" }, { "code": null, "e": 3634, "s": 3563, "text": "Check IF num % arr[index++] == 0 then set flag as 1 Else set flag as 0" }, { "code": null, "e": 3683, "s": 3634, "text": "Check IF flag is 1 then increment the count by 1" }, { "code": null, "e": 3732, "s": 3683, "text": "Check IF flag is 1 then increment the count by 1" }, { "code": null, "e": 3745, "s": 3732, "text": "Return count" }, { "code": null, "e": 3758, "s": 3745, "text": "Return count" }, { "code": null, "e": 3776, "s": 3758, "text": "Print the result." }, { "code": null, "e": 3794, "s": 3776, "text": "Print the result." }, { "code": null, "e": 3893, "s": 3794, "text": "As we can see there is a pattern in the numbers that is divisible by all the numbers from 2 to 10." }, { "code": null, "e": 3972, "s": 3893, "text": "The smallest number which is divisible by all the numbers from 2 to 10 is 2520" }, { "code": null, "e": 4068, "s": 3972, "text": "5 * 7 * 8 * 9 = 2520(n = 1)\n5 * 7 * 8 * 9 * 2 = 5040(n = 2)\n5 * 7 * 8 * 9 * 3 = 7560(n = 3)\n.\n." }, { "code": null, "e": 4235, "s": 4068, "text": "As we can see 2520 is the common factor of all the numbers divisible by 2, 3, 4, 5, 6, 7, 8, 9, 10. so , if we divide the given number by 2520 we will get our result." }, { "code": null, "e": 4246, "s": 4235, "text": " Live Demo" }, { "code": null, "e": 4853, "s": 4246, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint count(int num){\n int count = 0;\n int flag=0;\n int index=0;\n int arr[9] = {2, 3, 4, 5, 6, 7, 8, 9, 10 };\n for (int i = 1; i <= num; i++){\n int num = i;\n index=0;\n while(index<9){\n if(num % arr[index++] == 0){\n flag=1;\n }\n else{\n flag=0;\n break;\n }\n }\n if (flag == 1){\n count++;\n }\n }\n return count;\n}\nint main(){\n int num = 10000;\n cout<<\"Count numbers which are divisible by all the numbers from 2 to 10 are: \"<<count(num);\nreturn 0;\n}" }, { "code": null, "e": 4918, "s": 4853, "text": "If we run the above code it will generate the following output −" }, { "code": null, "e": 4991, "s": 4918, "text": "Count numbers which are divisible by all the numbers from 2 to 10 are: 3" }, { "code": null, "e": 5002, "s": 4991, "text": " Live Demo" }, { "code": null, "e": 5213, "s": 5002, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint main(){\n int num = 10000;\n int count = num / 2520;\n cout<<\"Count numbers which are divisible by all the numbers from 2 to 10 are: \"<<count;\n return 0;\n}" }, { "code": null, "e": 5278, "s": 5213, "text": "If we run the above code it will generate the following output −" }, { "code": null, "e": 5351, "s": 5278, "text": "Count numbers which are divisible by all the numbers from 2 to 10 are: 3" } ]
How to sort List in descending order using Comparator in Java
Let us first create an ArrayList − ArrayList<Integer>arrList = new ArrayList<Integer>(); arrList.add(10); arrList.add(50); arrList.add(100); arrList.add(150); arrList.add(250); Use Comparators interface to order in reverse order with reverseOrder() − Comparator comparator = Collections.reverseOrder(); Now, sort with Collections: Collections.sort(arrList, comparator); Live Demo import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; public class Demo { public static void main(String[] args) { ArrayList<Integer>arrList = new ArrayList<Integer>(); arrList.add(10); arrList.add(50); arrList.add(100); arrList.add(150); arrList.add(250); arrList.add(100); arrList.add(150); arrList.add(250); Comparator comparator = Collections.reverseOrder(); System.out.println("List = "+arrList); Collections.sort(arrList, comparator); System.out.println("Sorted List in descending order = "+arrList); } } List = [10, 50, 100, 150, 250, 100, 150, 250] Sorted List in descending order = [250, 250, 150, 150, 100, 100, 50, 10]
[ { "code": null, "e": 1097, "s": 1062, "text": "Let us first create an ArrayList −" }, { "code": null, "e": 1239, "s": 1097, "text": "ArrayList<Integer>arrList = new ArrayList<Integer>();\narrList.add(10);\narrList.add(50);\narrList.add(100);\narrList.add(150);\narrList.add(250);" }, { "code": null, "e": 1313, "s": 1239, "text": "Use Comparators interface to order in reverse order with reverseOrder() −" }, { "code": null, "e": 1432, "s": 1313, "text": "Comparator comparator = Collections.reverseOrder();\nNow, sort with Collections:\nCollections.sort(arrList, comparator);" }, { "code": null, "e": 1443, "s": 1432, "text": " Live Demo" }, { "code": null, "e": 2071, "s": 1443, "text": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\npublic class Demo {\n public static void main(String[] args) {\n ArrayList<Integer>arrList = new ArrayList<Integer>();\n arrList.add(10);\n arrList.add(50);\n arrList.add(100);\n arrList.add(150);\n arrList.add(250);\n arrList.add(100);\n arrList.add(150);\n arrList.add(250);\n Comparator comparator = Collections.reverseOrder();\n System.out.println(\"List = \"+arrList);\n Collections.sort(arrList, comparator);\n System.out.println(\"Sorted List in descending order = \"+arrList);\n }\n}" }, { "code": null, "e": 2190, "s": 2071, "text": "List = [10, 50, 100, 150, 250, 100, 150, 250]\nSorted List in descending order = [250, 250, 150, 150, 100, 100, 50, 10]" } ]
WWW-Authenticate Response Header Field
The resource server must include the HTTP "WWW-Authenticate" response header field, if the protected resource request contains an access token that is invalid or if the access token is malformed. "WWW-Authenticate" header field uses the following format − challenge = "OAuth" RWS token-challenge token-challenge = realm [CS error] [CS error-uri] [CS scope] [CS 1#auth –param] error = "error" "=" <"> token <"> error-desc = "error_description" "=" quoted-string error-uri = "error_uri" = <"> URI-Reference <"> scope = quoted-value / <"> quoted-value *(1*SP quoted-value) <"> quoted-value = 1* quoted-char where, realm − It is an attribute which specifies the scope of protection and is displayed to the users so that they know which username and password to use. This attribute must appear only once. realm − It is an attribute which specifies the scope of protection and is displayed to the users so that they know which username and password to use. This attribute must appear only once. error − It is an attribute used to provide a client the specific reason why the access request was declined. error − It is an attribute used to provide a client the specific reason why the access request was declined. error_description − It is an attribute that provides a human-readable text that can be used to help in understanding the error that occurred. error_description − It is an attribute that provides a human-readable text that can be used to help in understanding the error that occurred. error_uri − It is an attribute that provides a URI to identify a human-readable web page along with the information about the error that has occurred. error_uri − It is an attribute that provides a URI to identify a human-readable web page along with the information about the error that has occurred. scope − It is an attribute which specifies the required scope of the access token in order to access the requested resource. scope − It is an attribute which specifies the required scope of the access token in order to access the requested resource. Print Add Notes Bookmark this page
[ { "code": null, "e": 1981, "s": 1785, "text": "The resource server must include the HTTP \"WWW-Authenticate\" response header field, if the protected resource request contains an access token that is invalid or if the access token is malformed." }, { "code": null, "e": 2041, "s": 1981, "text": "\"WWW-Authenticate\" header field uses the following format −" }, { "code": null, "e": 2613, "s": 2041, "text": "challenge = \"OAuth\" RWS token-challenge\ntoken-challenge = realm\n [CS error]\n [CS error-uri]\n [CS scope]\n [CS 1#auth –param]\nerror = \"error\" \"=\" <\"> token <\">\nerror-desc = \"error_description\" \"=\" quoted-string\nerror-uri = \"error_uri\" = <\"> URI-Reference <\">\nscope = quoted-value / <\"> quoted-value *(1*SP quoted-value) <\">\n quoted-value = 1* quoted-char\n" }, { "code": null, "e": 2620, "s": 2613, "text": "where," }, { "code": null, "e": 2809, "s": 2620, "text": "realm − It is an attribute which specifies the scope of protection and is displayed to the users so that they know which username and password to use. This attribute must appear only once." }, { "code": null, "e": 2998, "s": 2809, "text": "realm − It is an attribute which specifies the scope of protection and is displayed to the users so that they know which username and password to use. This attribute must appear only once." }, { "code": null, "e": 3107, "s": 2998, "text": "error − It is an attribute used to provide a client the specific reason why the access request was declined." }, { "code": null, "e": 3216, "s": 3107, "text": "error − It is an attribute used to provide a client the specific reason why the access request was declined." }, { "code": null, "e": 3358, "s": 3216, "text": "error_description − It is an attribute that provides a human-readable text that can be used to help in understanding the error that occurred." }, { "code": null, "e": 3500, "s": 3358, "text": "error_description − It is an attribute that provides a human-readable text that can be used to help in understanding the error that occurred." }, { "code": null, "e": 3651, "s": 3500, "text": "error_uri − It is an attribute that provides a URI to identify a human-readable web page along with the information about the error that has occurred." }, { "code": null, "e": 3802, "s": 3651, "text": "error_uri − It is an attribute that provides a URI to identify a human-readable web page along with the information about the error that has occurred." }, { "code": null, "e": 3927, "s": 3802, "text": "scope − It is an attribute which specifies the required scope of the access token in order to access the requested resource." }, { "code": null, "e": 4052, "s": 3927, "text": "scope − It is an attribute which specifies the required scope of the access token in order to access the requested resource." }, { "code": null, "e": 4059, "s": 4052, "text": " Print" }, { "code": null, "e": 4070, "s": 4059, "text": " Add Notes" } ]
Tic-Tac-Toe Game in Java - GeeksforGeeks
13 Oct, 2020 In the Tic-Tac-Toe game, you will see the approach of the game is implemented. In this game, two players will be played and you have one print board on the screen where from 1 to 9 number will be displayed or you can say it box number. Now, you have to choose X or O for the specific box number. For example, if you have to select any number then for X or O will be shown on the print board, and turn for next will be there. The task is to create a Java program to implement a 3×3 Tic-Tac-Toe game for two players. Game board : |---|---|---| | 1 | 2 | 3 | |-----------| | 4 | 5 | 6 | |-----------| | 7 | 8 | 9 | |---|---|---| Sample Input : Enter a slot number to place X in: 3 Sample Output : |---|---|---| | 1 | 2 | X | |-----------| | 4 | 5 | 6 | |-----------| | 7 | 8 | 9 | |---|---|---| Sample Input : Now, O’s turn, Enter a slot number to place O in: 5 Sample Output : |---|---|---| | 1 | 2 | X | |-----------| | 4 | O | 6 | |-----------| | 7 | 8 | 9 | |---|---|---| So, like this game will be continued. How to Play the Game : Both the players choose either X or O to mark their cells. There will be a 3×3 grid with numbers assigned to each of the 9 cells. The player who chose X begins to play first. He enters the cell number where he wishes to place X. Now, both O and X play alternatively until any one of the two wins. Winning criteria: Whenever any of the two players has fully filled one row/ column/ diagonal with his symbol (X/ O), he wins and the game ends. If neither of the two players wins, the game is said to have ended in a draw. Below is the implementation of the game in Java : Java // A simple program to demonstrate // Tic-Tac-Toe Game.import java.util.*; public class GFG { static String[] board; static String turn; // CheckWinner method will // decide the combination // of three box given below. static String checkWinner() { for (int a = 0; a < 8; a++) { String line = null; switch (a) { case 0: line = board[0] + board[1] + board[2]; break; case 1: line = board[3] + board[4] + board[5]; break; case 2: line = board[6] + board[7] + board[8]; break; case 3: line = board[0] + board[3] + board[6]; break; case 4: line = board[1] + board[4] + board[7]; break; case 5: line = board[2] + board[5] + board[8]; break; case 6: line = board[0] + board[4] + board[8]; break; case 7: line = board[2] + board[4] + board[6]; break; } //For X winner if (line.equals("XXX")) { return "X"; } // For O winner else if (line.equals("OOO")) { return "O"; } } for (int a = 0; a < 9; a++) { if (Arrays.asList(board).contains( String.valueOf(a + 1))) { break; } else if (a == 8) { return "draw"; } } // To enter the X Or O at the exact place on board. System.out.println( turn + "'s turn; enter a slot number to place " + turn + " in:"); return null; } // To print out the board. /* |---|---|---| | 1 | 2 | 3 | |-----------| | 4 | 5 | 6 | |-----------| | 7 | 8 | 9 | |---|---|---|*/ static void printBoard() { System.out.println("|---|---|---|"); System.out.println("| " + board[0] + " | " + board[1] + " | " + board[2] + " |"); System.out.println("|-----------|"); System.out.println("| " + board[3] + " | " + board[4] + " | " + board[5] + " |"); System.out.println("|-----------|"); System.out.println("| " + board[6] + " | " + board[7] + " | " + board[8] + " |"); System.out.println("|---|---|---|"); } public static void main(String[] args) { Scanner in = new Scanner(System.in); board = new String[9]; turn = "X"; String winner = null; for (int a = 0; a < 9; a++) { board[a] = String.valueOf(a + 1); } System.out.println("Welcome to 3x3 Tic Tac Toe."); printBoard(); System.out.println( "X will play first. Enter a slot number to place X in:"); while (winner == null) { int numInput; // Exception handling. // numInput will take input from user like from 1 to 9. // If it is not in range from 1 to 9. // then it will show you an error "Invalid input." try { numInput = in.nextInt(); if (!(numInput > 0 && numInput <= 9)) { System.out.println( "Invalid input; re-enter slot number:"); continue; } } catch (InputMismatchException e) { System.out.println( "Invalid input; re-enter slot number:"); continue; } // This game has two player x and O. // Here is the logic to decide the turn. if (board[numInput - 1].equals( String.valueOf(numInput))) { board[numInput - 1] = turn; if (turn.equals("X")) { turn = "O"; } else { turn = "X"; } printBoard(); winner = checkWinner(); } else { System.out.println( "Slot already taken; re-enter slot number:"); } } // If no one win or lose from both player x and O. // then here is the logic to print "draw". if (winner.equalsIgnoreCase("draw")) { System.out.println( "It's a draw! Thanks for playing."); } // For winner -to display Congratulations! message. else { System.out.println( "Congratulations! " + winner + "'s have won! Thanks for playing."); } }} Output: Below is the output of the above program : Welcome to 3x3 Tic Tac Toe. |---|---|---| | 1 | 2 | 3 | |-----------| | 4 | 5 | 6 | |-----------| | 7 | 8 | 9 | |---|---|---| X will play first. Enter a slot number to place X in: 3 |---|---|---| | 1 | 2 | X | |-----------| | 4 | 5 | 6 | |-----------| | 7 | 8 | 9 | |---|---|---| O's turn; enter a slot number to place O in: 5 |---|---|---| | 1 | 2 | X | |-----------| | 4 | O | 6 | |-----------| | 7 | 8 | 9 | |---|---|---| X's turn; enter a slot number to place X in: 6 |---|---|---| | 1 | 2 | X | |-----------| | 4 | O | X | |-----------| | 7 | 8 | 9 | |---|---|---| O's turn; enter a slot number to place O in: 1 |---|---|---| | O | 2 | X | |-----------| | 4 | O | X | |-----------| | 7 | 8 | 9 | |---|---|---| X's turn; enter a slot number to place X in: 9 |---|---|---| | O | 2 | X | |-----------| | 4 | O | X | |-----------| | 7 | 8 | X | |---|---|---| Congratulations! X's have won! Thanks for playing. Run-on Eclipse IDE : Open Eclipse IDE. Create a New Java project. Right-click on the src folder and create a new class like a Class name -GFG. Now, write your source code and ctrl+s to save it. Now, to execute the program right-click the src folder and click on run as Java application. You can check below given screenshot for your reference. Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples How to iterate any Map in Java Interfaces in Java Initialize an ArrayList in Java Convert a String to Character array in Java Initializing a List in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 24429, "s": 24401, "text": "\n13 Oct, 2020" }, { "code": null, "e": 24944, "s": 24429, "text": "In the Tic-Tac-Toe game, you will see the approach of the game is implemented. In this game, two players will be played and you have one print board on the screen where from 1 to 9 number will be displayed or you can say it box number. Now, you have to choose X or O for the specific box number. For example, if you have to select any number then for X or O will be shown on the print board, and turn for next will be there. The task is to create a Java program to implement a 3×3 Tic-Tac-Toe game for two players." }, { "code": null, "e": 24958, "s": 24944, "text": " Game board :" }, { "code": null, "e": 25109, "s": 24958, "text": " |---|---|---| \n | 1 | 2 | 3 |\n |-----------|\n | 4 | 5 | 6 |\n |-----------|\n | 7 | 8 | 9 |\n |---|---|---| \n" }, { "code": null, "e": 25124, "s": 25109, "text": "Sample Input :" }, { "code": null, "e": 25162, "s": 25124, "text": "Enter a slot number to place X in: 3 " }, { "code": null, "e": 25178, "s": 25162, "text": "Sample Output :" }, { "code": null, "e": 25329, "s": 25178, "text": " |---|---|---| \n | 1 | 2 | X |\n |-----------|\n | 4 | 5 | 6 |\n |-----------|\n | 7 | 8 | 9 |\n |---|---|---| \n" }, { "code": null, "e": 25344, "s": 25329, "text": "Sample Input :" }, { "code": null, "e": 25396, "s": 25344, "text": "Now, O’s turn, Enter a slot number to place O in: 5" }, { "code": null, "e": 25412, "s": 25396, "text": "Sample Output :" }, { "code": null, "e": 25563, "s": 25412, "text": " |---|---|---| \n | 1 | 2 | X |\n |-----------|\n | 4 | O | 6 |\n |-----------|\n | 7 | 8 | 9 |\n |---|---|---| \n" }, { "code": null, "e": 25601, "s": 25563, "text": "So, like this game will be continued." }, { "code": null, "e": 25624, "s": 25601, "text": "How to Play the Game :" }, { "code": null, "e": 25683, "s": 25624, "text": "Both the players choose either X or O to mark their cells." }, { "code": null, "e": 25754, "s": 25683, "text": "There will be a 3×3 grid with numbers assigned to each of the 9 cells." }, { "code": null, "e": 25799, "s": 25754, "text": "The player who chose X begins to play first." }, { "code": null, "e": 25853, "s": 25799, "text": "He enters the cell number where he wishes to place X." }, { "code": null, "e": 25921, "s": 25853, "text": "Now, both O and X play alternatively until any one of the two wins." }, { "code": null, "e": 26065, "s": 25921, "text": "Winning criteria: Whenever any of the two players has fully filled one row/ column/ diagonal with his symbol (X/ O), he wins and the game ends." }, { "code": null, "e": 26143, "s": 26065, "text": "If neither of the two players wins, the game is said to have ended in a draw." }, { "code": null, "e": 26193, "s": 26143, "text": "Below is the implementation of the game in Java :" }, { "code": null, "e": 26198, "s": 26193, "text": "Java" }, { "code": "// A simple program to demonstrate // Tic-Tac-Toe Game.import java.util.*; public class GFG { static String[] board; static String turn; // CheckWinner method will // decide the combination // of three box given below. static String checkWinner() { for (int a = 0; a < 8; a++) { String line = null; switch (a) { case 0: line = board[0] + board[1] + board[2]; break; case 1: line = board[3] + board[4] + board[5]; break; case 2: line = board[6] + board[7] + board[8]; break; case 3: line = board[0] + board[3] + board[6]; break; case 4: line = board[1] + board[4] + board[7]; break; case 5: line = board[2] + board[5] + board[8]; break; case 6: line = board[0] + board[4] + board[8]; break; case 7: line = board[2] + board[4] + board[6]; break; } //For X winner if (line.equals(\"XXX\")) { return \"X\"; } // For O winner else if (line.equals(\"OOO\")) { return \"O\"; } } for (int a = 0; a < 9; a++) { if (Arrays.asList(board).contains( String.valueOf(a + 1))) { break; } else if (a == 8) { return \"draw\"; } } // To enter the X Or O at the exact place on board. System.out.println( turn + \"'s turn; enter a slot number to place \" + turn + \" in:\"); return null; } // To print out the board. /* |---|---|---| | 1 | 2 | 3 | |-----------| | 4 | 5 | 6 | |-----------| | 7 | 8 | 9 | |---|---|---|*/ static void printBoard() { System.out.println(\"|---|---|---|\"); System.out.println(\"| \" + board[0] + \" | \" + board[1] + \" | \" + board[2] + \" |\"); System.out.println(\"|-----------|\"); System.out.println(\"| \" + board[3] + \" | \" + board[4] + \" | \" + board[5] + \" |\"); System.out.println(\"|-----------|\"); System.out.println(\"| \" + board[6] + \" | \" + board[7] + \" | \" + board[8] + \" |\"); System.out.println(\"|---|---|---|\"); } public static void main(String[] args) { Scanner in = new Scanner(System.in); board = new String[9]; turn = \"X\"; String winner = null; for (int a = 0; a < 9; a++) { board[a] = String.valueOf(a + 1); } System.out.println(\"Welcome to 3x3 Tic Tac Toe.\"); printBoard(); System.out.println( \"X will play first. Enter a slot number to place X in:\"); while (winner == null) { int numInput; // Exception handling. // numInput will take input from user like from 1 to 9. // If it is not in range from 1 to 9. // then it will show you an error \"Invalid input.\" try { numInput = in.nextInt(); if (!(numInput > 0 && numInput <= 9)) { System.out.println( \"Invalid input; re-enter slot number:\"); continue; } } catch (InputMismatchException e) { System.out.println( \"Invalid input; re-enter slot number:\"); continue; } // This game has two player x and O. // Here is the logic to decide the turn. if (board[numInput - 1].equals( String.valueOf(numInput))) { board[numInput - 1] = turn; if (turn.equals(\"X\")) { turn = \"O\"; } else { turn = \"X\"; } printBoard(); winner = checkWinner(); } else { System.out.println( \"Slot already taken; re-enter slot number:\"); } } // If no one win or lose from both player x and O. // then here is the logic to print \"draw\". if (winner.equalsIgnoreCase(\"draw\")) { System.out.println( \"It's a draw! Thanks for playing.\"); } // For winner -to display Congratulations! message. else { System.out.println( \"Congratulations! \" + winner + \"'s have won! Thanks for playing.\"); } }}", "e": 31143, "s": 26198, "text": null }, { "code": null, "e": 31151, "s": 31143, "text": "Output:" }, { "code": null, "e": 32106, "s": 31151, "text": "Below is the output of the above program :\nWelcome to 3x3 Tic Tac Toe.\n|---|---|---|\n| 1 | 2 | 3 |\n|-----------|\n| 4 | 5 | 6 |\n|-----------|\n| 7 | 8 | 9 |\n|---|---|---|\nX will play first. Enter a slot number to place X in:\n3\n|---|---|---|\n| 1 | 2 | X |\n|-----------|\n| 4 | 5 | 6 |\n|-----------|\n| 7 | 8 | 9 |\n|---|---|---|\nO's turn; enter a slot number to place O in:\n5\n|---|---|---|\n| 1 | 2 | X |\n|-----------|\n| 4 | O | 6 |\n|-----------|\n| 7 | 8 | 9 |\n|---|---|---|\nX's turn; enter a slot number to place X in:\n6\n|---|---|---|\n| 1 | 2 | X |\n|-----------|\n| 4 | O | X |\n|-----------|\n| 7 | 8 | 9 |\n|---|---|---|\nO's turn; enter a slot number to place O in:\n1\n|---|---|---|\n| O | 2 | X |\n|-----------|\n| 4 | O | X |\n|-----------|\n| 7 | 8 | 9 |\n|---|---|---|\nX's turn; enter a slot number to place X in:\n9\n|---|---|---|\n| O | 2 | X |\n|-----------|\n| 4 | O | X |\n|-----------|\n| 7 | 8 | X |\n|---|---|---|\nCongratulations! X's have won! Thanks for playing.\n" }, { "code": null, "e": 32127, "s": 32106, "text": "Run-on Eclipse IDE :" }, { "code": null, "e": 32145, "s": 32127, "text": "Open Eclipse IDE." }, { "code": null, "e": 32172, "s": 32145, "text": "Create a New Java project." }, { "code": null, "e": 32249, "s": 32172, "text": "Right-click on the src folder and create a new class like a Class name -GFG." }, { "code": null, "e": 32300, "s": 32249, "text": "Now, write your source code and ctrl+s to save it." }, { "code": null, "e": 32393, "s": 32300, "text": "Now, to execute the program right-click the src folder and click on run as Java application." }, { "code": null, "e": 32450, "s": 32393, "text": "You can check below given screenshot for your reference." }, { "code": null, "e": 32455, "s": 32450, "text": "Java" }, { "code": null, "e": 32469, "s": 32455, "text": "Java Programs" }, { "code": null, "e": 32474, "s": 32469, "text": "Java" }, { "code": null, "e": 32572, "s": 32474, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32581, "s": 32572, "text": "Comments" }, { "code": null, "e": 32594, "s": 32581, "text": "Old Comments" }, { "code": null, "e": 32645, "s": 32594, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 32675, "s": 32645, "text": "HashMap in Java with Examples" }, { "code": null, "e": 32706, "s": 32675, "text": "How to iterate any Map in Java" }, { "code": null, "e": 32725, "s": 32706, "text": "Interfaces in Java" }, { "code": null, "e": 32757, "s": 32725, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 32801, "s": 32757, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 32829, "s": 32801, "text": "Initializing a List in Java" }, { "code": null, "e": 32855, "s": 32829, "text": "Java Programming Examples" }, { "code": null, "e": 32889, "s": 32855, "text": "Convert Double to Integer in Java" } ]
Birthday Paradox in C++
The birthday paradox is a very famous problem in the section of probability. The problem statement of this problem is stated as, There are several people at a birthday party, some are having the same birthday collision. We need to find the approximate no. of people at a birthday party on the basis of having the same birthday. In the probability we know that the chance of getting ahead is 1/2 same as if we have some coins, the chance of getting 10 heads is 1/100 or 0.001. Let us understand the concept, The chance of two people having the different birthday is, 364/365 which is 1-1/365 in a Non-leap year. Thus we can say that the first person having the probability of a specific birthday is ‘1’ and for others, it would be different which is, P(different)= 1×(1-1/365)× (1-2/365)× (1-3/365) × (1-4/365)....... Thus P(same)= 1- P(different) For Example, No. of people having the same birthday for which probability is 0.70. N= √2×365×log(1-1/p). N= √2×365×log(1-1/0.70)= 30 Thus total approximate no. of people having the same birthday is 30. Live Demo #include<bits/stdc++.h> using namespace std; int findPeople(double p){ return ceil(sqrt(2*365*log(1/(1-p)))); } int main(){ printf("%d",findPeople(0.70)); } 30
[ { "code": null, "e": 1191, "s": 1062, "text": "The birthday paradox is a very famous problem in the section of probability. The problem statement of this problem is stated as," }, { "code": null, "e": 1390, "s": 1191, "text": "There are several people at a birthday party, some are having the same birthday collision. We need to find the approximate no. of people at a birthday party on the basis of having the same birthday." }, { "code": null, "e": 1538, "s": 1390, "text": "In the probability we know that the chance of getting ahead is 1/2 same as if we have some coins, the chance of getting 10 heads is 1/100 or 0.001." }, { "code": null, "e": 1569, "s": 1538, "text": "Let us understand the concept," }, { "code": null, "e": 1628, "s": 1569, "text": "The chance of two people having the different birthday is," }, { "code": null, "e": 1673, "s": 1628, "text": "364/365 which is 1-1/365 in a Non-leap year." }, { "code": null, "e": 1812, "s": 1673, "text": "Thus we can say that the first person having the probability of a specific birthday is ‘1’ and for others, it would be different which is," }, { "code": null, "e": 1879, "s": 1812, "text": "P(different)= 1×(1-1/365)× (1-2/365)× (1-3/365) × (1-4/365)......." }, { "code": null, "e": 1909, "s": 1879, "text": "Thus P(same)= 1- P(different)" }, { "code": null, "e": 1922, "s": 1909, "text": "For Example," }, { "code": null, "e": 1992, "s": 1922, "text": "No. of people having the same birthday for which probability is 0.70." }, { "code": null, "e": 2014, "s": 1992, "text": "N= √2×365×log(1-1/p)." }, { "code": null, "e": 2042, "s": 2014, "text": "N= √2×365×log(1-1/0.70)= 30" }, { "code": null, "e": 2111, "s": 2042, "text": "Thus total approximate no. of people having the same birthday is 30." }, { "code": null, "e": 2122, "s": 2111, "text": " Live Demo" }, { "code": null, "e": 2285, "s": 2122, "text": "#include<bits/stdc++.h>\nusing namespace std;\nint findPeople(double p){\n return ceil(sqrt(2*365*log(1/(1-p))));\n}\nint main(){\n printf(\"%d\",findPeople(0.70));\n}" }, { "code": null, "e": 2288, "s": 2285, "text": "30" } ]
Scala Stream - GeeksforGeeks
07 Aug, 2019 The Stream is a lazy lists where elements are evaluated only when they are needed. This is a scala feature. Scala supports lazy computation. It increases performance of our program. Streams have the same performance characteristics as lists. Syntax : val str = 1 #:: 2 #:: 3 #:: Stream.empty In scala a List can be constructed with :: operator, whereas a Stream can be constructed with the #:: operator method, using Stream.empty at the end of the expression. In above syntax the head of this stream is 1, and the tail of it has 2 and 3. Create a Stream: Below is the examples to create a streams in Scala.Example : // Program to creating an empty stream // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creating stream val stream = 1 #:: 2#:: 8 #:: Stream.empty println(stream) } } Output: Stream(1, ?) In the above output, we can see that second element is not evaluated. Here, a question mark is displayed in place of element. Scala does not evaluate list until it is required. The tail is not printed, because it hasn’t been computed yet. Streams are specified to lazy computation. Create a Stream using Stream.cons : We can also create a Stream by using Stream.cons . A package import scala.collection.immutable.Stream.cons is used for creating stream. Example : // Program to creating an stream// using consimport scala.collection.immutable.Stream.cons // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creating stream val stream2: Stream[Int] = cons(1, cons(2, cons(3, Stream.empty) ) ) println(s"Elements of stream2 = ${stream2}") } } Output: Elements of stream2 = Stream(1, ?) Using take function on stream: take function is used to take elements from stream. Below is the example of using take function. Example : // Program to Using take function on stream // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creating stream val stream = 1 #:: 2#:: 8 #:: Stream.empty println(stream) // Taking elements from stream print("Take first 2 numbers from stream = ") stream.take(2).print print("\nTake first 10 numbers from stream2 = ") stream.take(10).print } } Output : Stream(1, ?) Take first 2 numbers from stream = 1, 2, empty Take first 10 numbers from stream2 = 1, 2, 8, empty When we wanted to take 10 numbers from a Stream, although it only contained 3 elements, it did not throw any IndexOutOfBoundsException. Using map function on stream: map function is used to perform operation on stream. Example : // Scala program to using map function on stream // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creating stream val stream = 1 #:: 2#:: 8 #:: Stream.empty println(stream) // map elements from stream println(stream.map{_+5}) } } Output: Stream(1, ?) Stream(6, ?) In above example by using map function we are transforming the input collection to a new output collection. Initialize an empty Stream: Below code shows how to initialize an empty Stream.Example : // Program to create empty stream // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creating empty stream val emptyStream: Stream[Int] = Stream.empty[Int] println(s"Empty Stream = $emptyStream") } } Output: Empty Stream = Stream() scala-collection Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Throw Keyword in Scala Scala | Functions Call-by-Name Comments In Scala How to install Scala on Windows? HashMap in Scala Operators in Scala Scala Singleton and Companion Objects Type Casting in Scala Scala map contains() method with example
[ { "code": null, "e": 23587, "s": 23559, "text": "\n07 Aug, 2019" }, { "code": null, "e": 23829, "s": 23587, "text": "The Stream is a lazy lists where elements are evaluated only when they are needed. This is a scala feature. Scala supports lazy computation. It increases performance of our program. Streams have the same performance characteristics as lists." }, { "code": null, "e": 23838, "s": 23829, "text": "Syntax :" }, { "code": null, "e": 23879, "s": 23838, "text": "val str = 1 #:: 2 #:: 3 #:: Stream.empty" }, { "code": null, "e": 24125, "s": 23879, "text": "In scala a List can be constructed with :: operator, whereas a Stream can be constructed with the #:: operator method, using Stream.empty at the end of the expression. In above syntax the head of this stream is 1, and the tail of it has 2 and 3." }, { "code": null, "e": 24203, "s": 24125, "text": "Create a Stream: Below is the examples to create a streams in Scala.Example :" }, { "code": "// Program to creating an empty stream // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creating stream val stream = 1 #:: 2#:: 8 #:: Stream.empty println(stream) } }", "e": 24438, "s": 24203, "text": null }, { "code": null, "e": 24446, "s": 24438, "text": "Output:" }, { "code": null, "e": 24459, "s": 24446, "text": "Stream(1, ?)" }, { "code": null, "e": 24913, "s": 24459, "text": "In the above output, we can see that second element is not evaluated. Here, a question mark is displayed in place of element. Scala does not evaluate list until it is required. The tail is not printed, because it hasn’t been computed yet. Streams are specified to lazy computation. Create a Stream using Stream.cons : We can also create a Stream by using Stream.cons . A package import scala.collection.immutable.Stream.cons is used for creating stream." }, { "code": null, "e": 24923, "s": 24913, "text": "Example :" }, { "code": "// Program to creating an stream// using consimport scala.collection.immutable.Stream.cons // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creating stream val stream2: Stream[Int] = cons(1, cons(2, cons(3, Stream.empty) ) ) println(s\"Elements of stream2 = ${stream2}\") } }", "e": 25263, "s": 24923, "text": null }, { "code": null, "e": 25271, "s": 25263, "text": "Output:" }, { "code": null, "e": 25306, "s": 25271, "text": "Elements of stream2 = Stream(1, ?)" }, { "code": null, "e": 25435, "s": 25306, "text": " Using take function on stream: take function is used to take elements from stream. Below is the example of using take function." }, { "code": null, "e": 25445, "s": 25435, "text": "Example :" }, { "code": "// Program to Using take function on stream // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creating stream val stream = 1 #:: 2#:: 8 #:: Stream.empty println(stream) // Taking elements from stream print(\"Take first 2 numbers from stream = \") stream.take(2).print print(\"\\nTake first 10 numbers from stream2 = \") stream.take(10).print } }", "e": 25898, "s": 25445, "text": null }, { "code": null, "e": 25907, "s": 25898, "text": "Output :" }, { "code": null, "e": 26019, "s": 25907, "text": "Stream(1, ?)\nTake first 2 numbers from stream = 1, 2, empty\nTake first 10 numbers from stream2 = 1, 2, 8, empty" }, { "code": null, "e": 26156, "s": 26019, "text": "When we wanted to take 10 numbers from a Stream, although it only contained 3 elements, it did not throw any IndexOutOfBoundsException. " }, { "code": null, "e": 26239, "s": 26156, "text": "Using map function on stream: map function is used to perform operation on stream." }, { "code": null, "e": 26249, "s": 26239, "text": "Example :" }, { "code": "// Scala program to using map function on stream // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creating stream val stream = 1 #:: 2#:: 8 #:: Stream.empty println(stream) // map elements from stream println(stream.map{_+5}) } }", "e": 26572, "s": 26249, "text": null }, { "code": null, "e": 26580, "s": 26572, "text": "Output:" }, { "code": null, "e": 26606, "s": 26580, "text": "Stream(1, ?)\nStream(6, ?)" }, { "code": null, "e": 26803, "s": 26606, "text": "In above example by using map function we are transforming the input collection to a new output collection. Initialize an empty Stream: Below code shows how to initialize an empty Stream.Example :" }, { "code": "// Program to create empty stream // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creating empty stream val emptyStream: Stream[Int] = Stream.empty[Int] println(s\"Empty Stream = $emptyStream\") } }", "e": 27067, "s": 26803, "text": null }, { "code": null, "e": 27075, "s": 27067, "text": "Output:" }, { "code": null, "e": 27100, "s": 27075, "text": " Empty Stream = Stream()" }, { "code": null, "e": 27117, "s": 27100, "text": "scala-collection" }, { "code": null, "e": 27123, "s": 27117, "text": "Scala" }, { "code": null, "e": 27221, "s": 27123, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27230, "s": 27221, "text": "Comments" }, { "code": null, "e": 27243, "s": 27230, "text": "Old Comments" }, { "code": null, "e": 27266, "s": 27243, "text": "Throw Keyword in Scala" }, { "code": null, "e": 27297, "s": 27266, "text": "Scala | Functions Call-by-Name" }, { "code": null, "e": 27315, "s": 27297, "text": "Comments In Scala" }, { "code": null, "e": 27348, "s": 27315, "text": "How to install Scala on Windows?" }, { "code": null, "e": 27365, "s": 27348, "text": "HashMap in Scala" }, { "code": null, "e": 27384, "s": 27365, "text": "Operators in Scala" }, { "code": null, "e": 27422, "s": 27384, "text": "Scala Singleton and Companion Objects" }, { "code": null, "e": 27444, "s": 27422, "text": "Type Casting in Scala" } ]
Program to compute log a to any base b (logb a) - GeeksforGeeks
19 Mar, 2022 Given two integers a and b, the task is to find the log of a to any base b, i.e. logb a.Examples: Input: a = 3, b = 2 Output: 1 Input: a = 256, b = 4 Output: 4 Find the log of a to the base 2 with the help of log2() method Find the log of b to the base 2 with the help of log2() method Divide the computed log a from the log b to get the logb a, i.e, Find the log of a to the base 2 with the help of log2() method Find the log of b to the base 2 with the help of log2() method Divide the computed log a from the log b to get the logb a, i.e, Below is the implementation of the above approach C++ C Java Python3 C# Javascript // C++ program to find log(a) on any base b#include <bits/stdc++.h>using namespace std; int log_a_to_base_b(int a, int b){ return log2(a) / log2(b);} // Driver codeint main(){ int a = 3; int b = 2; cout << log_a_to_base_b(a, b) << endl; a = 256; b = 4; cout << log_a_to_base_b(a, b) << endl; return 0;} // This code is contributed by shubhamsingh10, yousefonweb // C program to find log(a) on any base b #include <math.h>#include <stdio.h> int log_a_to_base_b(int a, int b){ return log2(a) / log2(b);} // Driver codeint main(){ int a = 3; int b = 2; printf("%d\n", log_a_to_base_b(a, b)); a = 256; b = 4; printf("%d\n", log_a_to_base_b(a, b)); return 0;} // Java program to find log(a) on any base bclass GFG{ static int log_a_to_base_b(int a, int b) { return (int)(Math.log(a) / Math.log(b)); } // Driver code public static void main (String[] args) { int a = 3; int b = 2; System.out.println(log_a_to_base_b(a, b)); a = 256; b = 4; System.out.println(log_a_to_base_b(a, b)); }} // This code is contributed by AnkitRai01 # Python3 program to find log(a) on any base bfrom math import log2 def log_a_to_base_b(a, b) : return log2(a) // log2(b); # Driver codeif __name__ == "__main__" : a = 3; b = 2; print(log_a_to_base_b(a, b)); a = 256; b = 4; print(log_a_to_base_b(a, b)); # This code is contributed by AnkitRai01 // C# program to find log(a) on any base b using System; public class GFG{ static int log_a_to_base_b(int a, int b) { return (int)(Math.Log(a) / Math.Log(b)); } // Driver code public static void Main() { int a = 3; int b = 2; Console.WriteLine(log_a_to_base_b(a, b)); a = 256; b = 4; Console.WriteLine(log_a_to_base_b(a, b)); }} // This code is contributed by AnkitRai01 <script> // Javascript program to find log(a) on any base b function log_a_to_base_b(a, b){ return parseInt(Math.log(a) / Math.log(b));} // Driver codevar a = 3;var b = 2;document.write(log_a_to_base_b(a, b) + "<br>");a = 256;b = 4;document.write(log_a_to_base_b(a, b)); // This code is contributed by rutvik_56.</script> 1 4 Time Complexity: O(logba) Auxiliary Space: O(1) Recursively divide a by b till a is greater than b. Count the number of times the divide is possible. This is the log of a to the base b, i.e. logb a Recursively divide a by b till a is greater than b. Count the number of times the divide is possible. This is the log of a to the base b, i.e. logb a Below is the implementation of the above approach C++ C Java Python3 C# Javascript // C++ program to find log(a) on// any base b using Recursion#include <iostream>using namespace std; // Recursive function to compute// log a to the base bint log_a_to_base_b(int a, int b){ return (a > b - 1) ? 1 + log_a_to_base_b(a / b, b) : 0;} // Driver codeint main(){ int a = 3; int b = 2; cout << log_a_to_base_b(a, b) << endl; a = 256; b = 4; cout << log_a_to_base_b(a, b) << endl; return 0;} // This code is contributed by shubhamsingh10 // C program to find log(a) on// any base b using Recursion #include <stdio.h> // Recursive function to compute// log a to the base bint log_a_to_base_b(int a, int b){ return (a > b - 1) ? 1 + log_a_to_base_b(a / b, b) : 0;} // Driver codeint main(){ int a = 3; int b = 2; printf("%d\n", log_a_to_base_b(a, b)); a = 256; b = 4; printf("%d\n", log_a_to_base_b(a, b)); return 0;} // Java program to find log(a) on// any base b using Recursionclass GFG{ // Recursive function to compute // log a to the base b static int log_a_to_base_b(int a, int b) { int rslt = (a > b - 1)? 1 + log_a_to_base_b(a / b, b): 0; return rslt; } // Driver code public static void main (String[] args) { int a = 3; int b = 2; System.out.println(log_a_to_base_b(a, b)); a = 256; b = 4; System.out.println(log_a_to_base_b(a, b)); }} // This code is contributed by AnkitRai01 # Python3 program to find log(a) on# any base b using Recursion # Recursive function to compute# log a to the base bdef log_a_to_base_b(a, b) : rslt = (1 + log_a_to_base_b(a // b, b)) if (a > (b - 1)) else 0; return rslt; # Driver codeif __name__ == "__main__" : a = 3; b = 2; print(log_a_to_base_b(a, b)); a = 256; b = 4; print(log_a_to_base_b(a, b)); # This code is contributed by AnkitRai01 // C# program to find log(a) on// any base b using Recursionusing System; class GFG{ // Recursive function to compute // log a to the base b static int log_a_to_base_b(int a, int b) { int rslt = (a > b - 1)? 1 + log_a_to_base_b(a / b, b): 0; return rslt; } // Driver code public static void Main() { int a = 3; int b = 2; Console.WriteLine(log_a_to_base_b(a, b)); a = 256; b = 4; Console.WriteLine(log_a_to_base_b(a, b)); }} // This code is contributed by Yash_R <script>// javascript program to find log(a) on// any base b using Recursion // Recursive function to compute // log a to the base b function log_a_to_base_b(a , b) { var rslt = (a > b - 1) ? 1 + log_a_to_base_b(parseInt(a / b), b) : 0; return rslt; } // Driver code var a = 3; var b = 2; document.write(log_a_to_base_b(a, b)+"<br/>"); a = 256; b = 4; document.write(log_a_to_base_b(a, b)); // This code is contributed by umadevi9616</script> 1 4 ankthon Yash_R SHUBHAMSINGH10 rutvik_56 umadevi9616 subhammahato348 yousefonweb maths-log Mathematical School Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Find all factors of a natural number | Set 1 Check if a number is Palindrome Program to print prime numbers from 1 to N. Program to add two binary strings Program to multiply two matrices Python Dictionary Arrays in C/C++ Reverse a string in Java Inheritance in C++ Constructors in C++
[ { "code": null, "e": 24301, "s": 24273, "text": "\n19 Mar, 2022" }, { "code": null, "e": 24401, "s": 24301, "text": "Given two integers a and b, the task is to find the log of a to any base b, i.e. logb a.Examples: " }, { "code": null, "e": 24464, "s": 24401, "text": "Input: a = 3, b = 2\nOutput: 1\n\nInput: a = 256, b = 4\nOutput: 4" }, { "code": null, "e": 24665, "s": 24470, "text": "Find the log of a to the base 2 with the help of log2() method Find the log of b to the base 2 with the help of log2() method Divide the computed log a from the log b to get the logb a, i.e, " }, { "code": null, "e": 24730, "s": 24665, "text": "Find the log of a to the base 2 with the help of log2() method " }, { "code": null, "e": 24795, "s": 24730, "text": "Find the log of b to the base 2 with the help of log2() method " }, { "code": null, "e": 24862, "s": 24795, "text": "Divide the computed log a from the log b to get the logb a, i.e, " }, { "code": null, "e": 24914, "s": 24862, "text": "Below is the implementation of the above approach " }, { "code": null, "e": 24918, "s": 24914, "text": "C++" }, { "code": null, "e": 24920, "s": 24918, "text": "C" }, { "code": null, "e": 24925, "s": 24920, "text": "Java" }, { "code": null, "e": 24933, "s": 24925, "text": "Python3" }, { "code": null, "e": 24936, "s": 24933, "text": "C#" }, { "code": null, "e": 24947, "s": 24936, "text": "Javascript" }, { "code": "// C++ program to find log(a) on any base b#include <bits/stdc++.h>using namespace std; int log_a_to_base_b(int a, int b){ return log2(a) / log2(b);} // Driver codeint main(){ int a = 3; int b = 2; cout << log_a_to_base_b(a, b) << endl; a = 256; b = 4; cout << log_a_to_base_b(a, b) << endl; return 0;} // This code is contributed by shubhamsingh10, yousefonweb", "e": 25335, "s": 24947, "text": null }, { "code": "// C program to find log(a) on any base b #include <math.h>#include <stdio.h> int log_a_to_base_b(int a, int b){ return log2(a) / log2(b);} // Driver codeint main(){ int a = 3; int b = 2; printf(\"%d\\n\", log_a_to_base_b(a, b)); a = 256; b = 4; printf(\"%d\\n\", log_a_to_base_b(a, b)); return 0;}", "e": 25674, "s": 25335, "text": null }, { "code": "// Java program to find log(a) on any base bclass GFG{ static int log_a_to_base_b(int a, int b) { return (int)(Math.log(a) / Math.log(b)); } // Driver code public static void main (String[] args) { int a = 3; int b = 2; System.out.println(log_a_to_base_b(a, b)); a = 256; b = 4; System.out.println(log_a_to_base_b(a, b)); }} // This code is contributed by AnkitRai01", "e": 26126, "s": 25674, "text": null }, { "code": "# Python3 program to find log(a) on any base bfrom math import log2 def log_a_to_base_b(a, b) : return log2(a) // log2(b); # Driver codeif __name__ == \"__main__\" : a = 3; b = 2; print(log_a_to_base_b(a, b)); a = 256; b = 4; print(log_a_to_base_b(a, b)); # This code is contributed by AnkitRai01", "e": 26448, "s": 26126, "text": null }, { "code": "// C# program to find log(a) on any base b using System; public class GFG{ static int log_a_to_base_b(int a, int b) { return (int)(Math.Log(a) / Math.Log(b)); } // Driver code public static void Main() { int a = 3; int b = 2; Console.WriteLine(log_a_to_base_b(a, b)); a = 256; b = 4; Console.WriteLine(log_a_to_base_b(a, b)); }} // This code is contributed by AnkitRai01", "e": 26904, "s": 26448, "text": null }, { "code": "<script> // Javascript program to find log(a) on any base b function log_a_to_base_b(a, b){ return parseInt(Math.log(a) / Math.log(b));} // Driver codevar a = 3;var b = 2;document.write(log_a_to_base_b(a, b) + \"<br>\");a = 256;b = 4;document.write(log_a_to_base_b(a, b)); // This code is contributed by rutvik_56.</script>", "e": 27229, "s": 26904, "text": null }, { "code": null, "e": 27233, "s": 27229, "text": "1\n4" }, { "code": null, "e": 27261, "s": 27235, "text": "Time Complexity: O(logba)" }, { "code": null, "e": 27283, "s": 27261, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 27436, "s": 27283, "text": "Recursively divide a by b till a is greater than b. Count the number of times the divide is possible. This is the log of a to the base b, i.e. logb a " }, { "code": null, "e": 27490, "s": 27436, "text": "Recursively divide a by b till a is greater than b. " }, { "code": null, "e": 27590, "s": 27490, "text": "Count the number of times the divide is possible. This is the log of a to the base b, i.e. logb a " }, { "code": null, "e": 27642, "s": 27590, "text": "Below is the implementation of the above approach " }, { "code": null, "e": 27646, "s": 27642, "text": "C++" }, { "code": null, "e": 27648, "s": 27646, "text": "C" }, { "code": null, "e": 27653, "s": 27648, "text": "Java" }, { "code": null, "e": 27661, "s": 27653, "text": "Python3" }, { "code": null, "e": 27664, "s": 27661, "text": "C#" }, { "code": null, "e": 27675, "s": 27664, "text": "Javascript" }, { "code": "// C++ program to find log(a) on// any base b using Recursion#include <iostream>using namespace std; // Recursive function to compute// log a to the base bint log_a_to_base_b(int a, int b){ return (a > b - 1) ? 1 + log_a_to_base_b(a / b, b) : 0;} // Driver codeint main(){ int a = 3; int b = 2; cout << log_a_to_base_b(a, b) << endl; a = 256; b = 4; cout << log_a_to_base_b(a, b) << endl; return 0;} // This code is contributed by shubhamsingh10", "e": 28169, "s": 27675, "text": null }, { "code": "// C program to find log(a) on// any base b using Recursion #include <stdio.h> // Recursive function to compute// log a to the base bint log_a_to_base_b(int a, int b){ return (a > b - 1) ? 1 + log_a_to_base_b(a / b, b) : 0;} // Driver codeint main(){ int a = 3; int b = 2; printf(\"%d\\n\", log_a_to_base_b(a, b)); a = 256; b = 4; printf(\"%d\\n\", log_a_to_base_b(a, b)); return 0;}", "e": 28621, "s": 28169, "text": null }, { "code": "// Java program to find log(a) on// any base b using Recursionclass GFG{ // Recursive function to compute // log a to the base b static int log_a_to_base_b(int a, int b) { int rslt = (a > b - 1)? 1 + log_a_to_base_b(a / b, b): 0; return rslt; } // Driver code public static void main (String[] args) { int a = 3; int b = 2; System.out.println(log_a_to_base_b(a, b)); a = 256; b = 4; System.out.println(log_a_to_base_b(a, b)); }} // This code is contributed by AnkitRai01", "e": 29190, "s": 28621, "text": null }, { "code": "# Python3 program to find log(a) on# any base b using Recursion # Recursive function to compute# log a to the base bdef log_a_to_base_b(a, b) : rslt = (1 + log_a_to_base_b(a // b, b)) if (a > (b - 1)) else 0; return rslt; # Driver codeif __name__ == \"__main__\" : a = 3; b = 2; print(log_a_to_base_b(a, b)); a = 256; b = 4; print(log_a_to_base_b(a, b)); # This code is contributed by AnkitRai01", "e": 29628, "s": 29190, "text": null }, { "code": "// C# program to find log(a) on// any base b using Recursionusing System; class GFG{ // Recursive function to compute // log a to the base b static int log_a_to_base_b(int a, int b) { int rslt = (a > b - 1)? 1 + log_a_to_base_b(a / b, b): 0; return rslt; } // Driver code public static void Main() { int a = 3; int b = 2; Console.WriteLine(log_a_to_base_b(a, b)); a = 256; b = 4; Console.WriteLine(log_a_to_base_b(a, b)); }} // This code is contributed by Yash_R", "e": 30189, "s": 29628, "text": null }, { "code": "<script>// javascript program to find log(a) on// any base b using Recursion // Recursive function to compute // log a to the base b function log_a_to_base_b(a , b) { var rslt = (a > b - 1) ? 1 + log_a_to_base_b(parseInt(a / b), b) : 0; return rslt; } // Driver code var a = 3; var b = 2; document.write(log_a_to_base_b(a, b)+\"<br/>\"); a = 256; b = 4; document.write(log_a_to_base_b(a, b)); // This code is contributed by umadevi9616</script>", "e": 30708, "s": 30189, "text": null }, { "code": null, "e": 30712, "s": 30708, "text": "1\n4" }, { "code": null, "e": 30722, "s": 30714, "text": "ankthon" }, { "code": null, "e": 30729, "s": 30722, "text": "Yash_R" }, { "code": null, "e": 30744, "s": 30729, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 30754, "s": 30744, "text": "rutvik_56" }, { "code": null, "e": 30766, "s": 30754, "text": "umadevi9616" }, { "code": null, "e": 30782, "s": 30766, "text": "subhammahato348" }, { "code": null, "e": 30794, "s": 30782, "text": "yousefonweb" }, { "code": null, "e": 30804, "s": 30794, "text": "maths-log" }, { "code": null, "e": 30817, "s": 30804, "text": "Mathematical" }, { "code": null, "e": 30836, "s": 30817, "text": "School Programming" }, { "code": null, "e": 30849, "s": 30836, "text": "Mathematical" }, { "code": null, "e": 30947, "s": 30849, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30956, "s": 30947, "text": "Comments" }, { "code": null, "e": 30969, "s": 30956, "text": "Old Comments" }, { "code": null, "e": 31014, "s": 30969, "text": "Find all factors of a natural number | Set 1" }, { "code": null, "e": 31046, "s": 31014, "text": "Check if a number is Palindrome" }, { "code": null, "e": 31090, "s": 31046, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 31124, "s": 31090, "text": "Program to add two binary strings" }, { "code": null, "e": 31157, "s": 31124, "text": "Program to multiply two matrices" }, { "code": null, "e": 31175, "s": 31157, "text": "Python Dictionary" }, { "code": null, "e": 31191, "s": 31175, "text": "Arrays in C/C++" }, { "code": null, "e": 31216, "s": 31191, "text": "Reverse a string in Java" }, { "code": null, "e": 31235, "s": 31216, "text": "Inheritance in C++" } ]
HTML Id Attributes
14 Dec, 2021 In this article, we will know how to identify the specific HTML element by its id using HTML id Attribute, along with understanding its implementation through the examples. The id attribute is a unique identifier that is used to specify the document. It is used by CSS and JavaScript to perform a certain task for a unique element. In CSS, the id attribute is used using the # symbol followed by id. quotes are not mandatory in tag=” ” in all cases. But writing with quotes is a good practice. Syntax: <tag id=""></tag> Note: This is a global attribute, it can be used in all the tags. Example 1: In this example, we simply style the element with id “geeks”. HTML <!DOCTYPE html><html> <head> <style> #geeks { color: green; } </style></head> <body> <h2>Welcome to GeeksforGeeks</h2> <h1 id="geeks">Hi Geeks!</h1> </body> </html> Output: HTML id Attribute Example 2: In this example, we are adding the styling properties to the specific id attribute value by fetching its id value. HTML <!DOCTYPE html><html> <head> <title>Id Attributes</title> <style> #gfg { color: #009900; font-size: 50px; font-weight: bold; text-align: center; } #geeks { text-align: center; font-size: 20px; } </style></head> <body> <div id="gfg">GeeksforGeeks</div> <div id="geeks"> A computer science portal for geeks </div></body> </html> Output: Adding the style properties to the specific id attribute value Note: In HTML5, id attributes can be used by any HTML tag but in HTML 4.01 there are some restriction to use id attributes. It can not be used by <base>, <head>, <html>, <meta>, <param>, <script>, <style>, and <title> tag. In HTML4.01 id can not start with number. Use of ID attributes in JavaScript: In JavaScript, the id attribute is used to manipulate the text, if you want to make changes to a precise element in your script, then you can use the id attribute. Example 3: This example describes getting the id attribute value in Javascript through getElementById() Method. HTML <!DOCTYPE html><html> <head> <title>Using the id in Javascript</title> <style> #geeks { font-size: 50px; color: #009900; font-weight: bold; margin-bottom: 10px; } </style></head> <body> <div id="geeks">GeeksforGeeks</div> <button onclick="geeksResult()">Display text change</button> <script> function geeksResult() { document.getElementById("geeks").innerHTML = "A computer science portal for geeks"; document.getElementById("geeks").style.color = "black"; } </script></body> </html> Output: Getting the id attribute value using getElementById() Method Supported Browsers: Google Chrome Edge 12 and above Firefox 32 and above Internet Explorer Mozilla Opera Safari vamsiathota123 shubhamyadav4 bhaskargeeksforgeeks HTML-Attributes Picked CSS HTML Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? CSS to put icon inside an input element in a form How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? REST API (Introduction) Hide or show elements in HTML using display property
[ { "code": null, "e": 53, "s": 25, "text": "\n14 Dec, 2021" }, { "code": null, "e": 226, "s": 53, "text": "In this article, we will know how to identify the specific HTML element by its id using HTML id Attribute, along with understanding its implementation through the examples." }, { "code": null, "e": 547, "s": 226, "text": "The id attribute is a unique identifier that is used to specify the document. It is used by CSS and JavaScript to perform a certain task for a unique element. In CSS, the id attribute is used using the # symbol followed by id. quotes are not mandatory in tag=” ” in all cases. But writing with quotes is a good practice." }, { "code": null, "e": 555, "s": 547, "text": "Syntax:" }, { "code": null, "e": 574, "s": 555, "text": " <tag id=\"\"></tag>" }, { "code": null, "e": 640, "s": 574, "text": "Note: This is a global attribute, it can be used in all the tags." }, { "code": null, "e": 713, "s": 640, "text": "Example 1: In this example, we simply style the element with id “geeks”." }, { "code": null, "e": 718, "s": 713, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> #geeks { color: green; } </style></head> <body> <h2>Welcome to GeeksforGeeks</h2> <h1 id=\"geeks\">Hi Geeks!</h1> </body> </html>", "e": 911, "s": 718, "text": null }, { "code": null, "e": 919, "s": 911, "text": "Output:" }, { "code": null, "e": 937, "s": 919, "text": "HTML id Attribute" }, { "code": null, "e": 1063, "s": 937, "text": "Example 2: In this example, we are adding the styling properties to the specific id attribute value by fetching its id value." }, { "code": null, "e": 1068, "s": 1063, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Id Attributes</title> <style> #gfg { color: #009900; font-size: 50px; font-weight: bold; text-align: center; } #geeks { text-align: center; font-size: 20px; } </style></head> <body> <div id=\"gfg\">GeeksforGeeks</div> <div id=\"geeks\"> A computer science portal for geeks </div></body> </html>", "e": 1483, "s": 1068, "text": null }, { "code": null, "e": 1491, "s": 1483, "text": "Output:" }, { "code": null, "e": 1554, "s": 1491, "text": "Adding the style properties to the specific id attribute value" }, { "code": null, "e": 1819, "s": 1554, "text": "Note: In HTML5, id attributes can be used by any HTML tag but in HTML 4.01 there are some restriction to use id attributes. It can not be used by <base>, <head>, <html>, <meta>, <param>, <script>, <style>, and <title> tag. In HTML4.01 id can not start with number." }, { "code": null, "e": 2020, "s": 1819, "text": "Use of ID attributes in JavaScript: In JavaScript, the id attribute is used to manipulate the text, if you want to make changes to a precise element in your script, then you can use the id attribute. " }, { "code": null, "e": 2132, "s": 2020, "text": "Example 3: This example describes getting the id attribute value in Javascript through getElementById() Method." }, { "code": null, "e": 2137, "s": 2132, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Using the id in Javascript</title> <style> #geeks { font-size: 50px; color: #009900; font-weight: bold; margin-bottom: 10px; } </style></head> <body> <div id=\"geeks\">GeeksforGeeks</div> <button onclick=\"geeksResult()\">Display text change</button> <script> function geeksResult() { document.getElementById(\"geeks\").innerHTML = \"A computer science portal for geeks\"; document.getElementById(\"geeks\").style.color = \"black\"; } </script></body> </html>", "e": 2707, "s": 2137, "text": null }, { "code": null, "e": 2715, "s": 2707, "text": "Output:" }, { "code": null, "e": 2776, "s": 2715, "text": "Getting the id attribute value using getElementById() Method" }, { "code": null, "e": 2796, "s": 2776, "text": "Supported Browsers:" }, { "code": null, "e": 2810, "s": 2796, "text": "Google Chrome" }, { "code": null, "e": 2828, "s": 2810, "text": "Edge 12 and above" }, { "code": null, "e": 2849, "s": 2828, "text": "Firefox 32 and above" }, { "code": null, "e": 2867, "s": 2849, "text": "Internet Explorer" }, { "code": null, "e": 2875, "s": 2867, "text": "Mozilla" }, { "code": null, "e": 2881, "s": 2875, "text": "Opera" }, { "code": null, "e": 2888, "s": 2881, "text": "Safari" }, { "code": null, "e": 2903, "s": 2888, "text": "vamsiathota123" }, { "code": null, "e": 2917, "s": 2903, "text": "shubhamyadav4" }, { "code": null, "e": 2938, "s": 2917, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 2954, "s": 2938, "text": "HTML-Attributes" }, { "code": null, "e": 2961, "s": 2954, "text": "Picked" }, { "code": null, "e": 2965, "s": 2961, "text": "CSS" }, { "code": null, "e": 2970, "s": 2965, "text": "HTML" }, { "code": null, "e": 2997, "s": 2970, "text": "Web technologies Questions" }, { "code": null, "e": 3002, "s": 2997, "text": "HTML" }, { "code": null, "e": 3100, "s": 3002, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3148, "s": 3100, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 3210, "s": 3148, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3260, "s": 3210, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 3318, "s": 3260, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 3368, "s": 3318, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 3416, "s": 3368, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 3478, "s": 3416, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3528, "s": 3478, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 3552, "s": 3528, "text": "REST API (Introduction)" } ]
Difference between Image Sampling and Quantization
03 Dec, 2019 To create a digital image, we need to convert the continuous sensed data into digital form.This process includes 2 processes: Sampling: Digitizing the co-ordinate value is called sampling.Quantization: Digitizing the amplitude value is called quantization. Sampling: Digitizing the co-ordinate value is called sampling. Quantization: Digitizing the amplitude value is called quantization. To convert a continuous image f(x, y) into digital form, we have to sample the function in both co-ordinates and amplitude. Difference between Image Sampling and Quantization: computer-graphics Difference Between Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n03 Dec, 2019" }, { "code": null, "e": 179, "s": 53, "text": "To create a digital image, we need to convert the continuous sensed data into digital form.This process includes 2 processes:" }, { "code": null, "e": 310, "s": 179, "text": "Sampling: Digitizing the co-ordinate value is called sampling.Quantization: Digitizing the amplitude value is called quantization." }, { "code": null, "e": 373, "s": 310, "text": "Sampling: Digitizing the co-ordinate value is called sampling." }, { "code": null, "e": 442, "s": 373, "text": "Quantization: Digitizing the amplitude value is called quantization." }, { "code": null, "e": 566, "s": 442, "text": "To convert a continuous image f(x, y) into digital form, we have to sample the function in both co-ordinates and amplitude." }, { "code": null, "e": 618, "s": 566, "text": "Difference between Image Sampling and Quantization:" }, { "code": null, "e": 636, "s": 618, "text": "computer-graphics" }, { "code": null, "e": 655, "s": 636, "text": "Difference Between" } ]
How to skip rows while reading csv file using Pandas?
27 Aug, 2021 Python is a good language for doing data analysis because of the amazing ecosystem of data-centric python packages. Pandas package is one of them and makes importing and analyzing data so much easier. Here, we will discuss how to skip rows while reading csv file. We will use read_csv() method of Pandas library for this task. Syntax: pd.read_csv(filepath_or_buffer, sep=’, ‘, delimiter=None, header=’infer’, names=None, index_col=None, usecols=None, squeeze=False, prefix=None, mangle_dupe_cols=True, dtype=None, engine=None, converters=None, true_values=None, false_values=None, skipinitialspace=False, skiprows=None, nrows=None, na_values=None, keep_default_na=True, na_filter=True, verbose=False, skip_blank_lines=True, parse_dates=False, infer_datetime_format=False, keep_date_col=False, date_parser=None, dayfirst=False, iterator=False, chunksize=None, compression=’infer’, thousands=None, decimal=b’.’, lineterminator=None, quotechar='”‘, quoting=0, escapechar=None, comment=None, encoding=None, dialect=None, tupleize_cols=None, error_bad_lines=True, warn_bad_lines=True, skipfooter=0, doublequote=True, delim_whitespace=False, low_memory=True, memory_map=False, float_precision=None) Some useful parameters are given below : For downloading the student.csv file Click Here Method 1: Skipping N rows from the starting while reading a csv file. Code: Python3 # Importing Pandas libraryimport pandas as pd # Skipping 2 rows from start in csv# and initialize it to a dataframedf = pd.read_csv("students.csv", skiprows = 2) # Show the dataframedf Output : Method 2: Skipping rows at specific positions while reading a csv file. Code: Python3 # Importing Pandas libraryimport pandas as pd # Skipping rows at specific positiondf = pd.read_csv("students.csv", skiprows = [0, 2, 5]) # Show the dataframedf Output : Method 3: Skipping N rows from the starting except column names while reading a csv file. Code: Python3 # Importing Pandas libraryimport pandas as pd # Skipping 2 rows from start# except the column namesdf = pd.read_csv("students.csv", skiprows = [i for i in range(1, 3) ]) # Show the dataframedf Output : Method 4: Skip rows based on a condition while reading a csv file. Code: Python3 # Importing Pandas libraryimport pandas as pd # function for checking and# skipping every 3rd linedef logic(index): if index % 3 == 0: return True return False # Skipping rows based on a conditiondf = pd.read_csv("students.csv", skiprows = lambda x: logic(x) ) # Show the dataframedf Output : Method 5: Skip N rows from the end while reading a csv file. Code: Python3 # Importing Pandas libraryimport pandas as pd # Skipping 2 rows from enddf = pd.read_csv("students.csv", skipfooter = 5, engine = 'python') # Show the dataframedf Output : simmytarika5 surinderdawra388 sweetyty Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Aug, 2021" }, { "code": null, "e": 229, "s": 28, "text": "Python is a good language for doing data analysis because of the amazing ecosystem of data-centric python packages. Pandas package is one of them and makes importing and analyzing data so much easier." }, { "code": null, "e": 355, "s": 229, "text": "Here, we will discuss how to skip rows while reading csv file. We will use read_csv() method of Pandas library for this task." }, { "code": null, "e": 1223, "s": 355, "text": "Syntax: pd.read_csv(filepath_or_buffer, sep=’, ‘, delimiter=None, header=’infer’, names=None, index_col=None, usecols=None, squeeze=False, prefix=None, mangle_dupe_cols=True, dtype=None, engine=None, converters=None, true_values=None, false_values=None, skipinitialspace=False, skiprows=None, nrows=None, na_values=None, keep_default_na=True, na_filter=True, verbose=False, skip_blank_lines=True, parse_dates=False, infer_datetime_format=False, keep_date_col=False, date_parser=None, dayfirst=False, iterator=False, chunksize=None, compression=’infer’, thousands=None, decimal=b’.’, lineterminator=None, quotechar='”‘, quoting=0, escapechar=None, comment=None, encoding=None, dialect=None, tupleize_cols=None, error_bad_lines=True, warn_bad_lines=True, skipfooter=0, doublequote=True, delim_whitespace=False, low_memory=True, memory_map=False, float_precision=None) " }, { "code": null, "e": 1266, "s": 1223, "text": "Some useful parameters are given below : " }, { "code": null, "e": 1314, "s": 1266, "text": "For downloading the student.csv file Click Here" }, { "code": null, "e": 1385, "s": 1314, "text": "Method 1: Skipping N rows from the starting while reading a csv file. " }, { "code": null, "e": 1393, "s": 1385, "text": "Code: " }, { "code": null, "e": 1401, "s": 1393, "text": "Python3" }, { "code": "# Importing Pandas libraryimport pandas as pd # Skipping 2 rows from start in csv# and initialize it to a dataframedf = pd.read_csv(\"students.csv\", skiprows = 2) # Show the dataframedf", "e": 1604, "s": 1401, "text": null }, { "code": null, "e": 1615, "s": 1604, "text": "Output : " }, { "code": null, "e": 1688, "s": 1615, "text": "Method 2: Skipping rows at specific positions while reading a csv file. " }, { "code": null, "e": 1695, "s": 1688, "text": "Code: " }, { "code": null, "e": 1703, "s": 1695, "text": "Python3" }, { "code": "# Importing Pandas libraryimport pandas as pd # Skipping rows at specific positiondf = pd.read_csv(\"students.csv\", skiprows = [0, 2, 5]) # Show the dataframedf", "e": 1880, "s": 1703, "text": null }, { "code": null, "e": 1891, "s": 1880, "text": "Output : " }, { "code": null, "e": 1982, "s": 1891, "text": "Method 3: Skipping N rows from the starting except column names while reading a csv file. " }, { "code": null, "e": 1990, "s": 1982, "text": "Code: " }, { "code": null, "e": 1998, "s": 1990, "text": "Python3" }, { "code": "# Importing Pandas libraryimport pandas as pd # Skipping 2 rows from start# except the column namesdf = pd.read_csv(\"students.csv\", skiprows = [i for i in range(1, 3) ]) # Show the dataframedf", "e": 2207, "s": 1998, "text": null }, { "code": null, "e": 2218, "s": 2207, "text": "Output : " }, { "code": null, "e": 2286, "s": 2218, "text": "Method 4: Skip rows based on a condition while reading a csv file. " }, { "code": null, "e": 2294, "s": 2286, "text": "Code: " }, { "code": null, "e": 2302, "s": 2294, "text": "Python3" }, { "code": "# Importing Pandas libraryimport pandas as pd # function for checking and# skipping every 3rd linedef logic(index): if index % 3 == 0: return True return False # Skipping rows based on a conditiondf = pd.read_csv(\"students.csv\", skiprows = lambda x: logic(x) ) # Show the dataframedf", "e": 2617, "s": 2302, "text": null }, { "code": null, "e": 2628, "s": 2617, "text": "Output : " }, { "code": null, "e": 2690, "s": 2628, "text": "Method 5: Skip N rows from the end while reading a csv file. " }, { "code": null, "e": 2698, "s": 2690, "text": "Code: " }, { "code": null, "e": 2706, "s": 2698, "text": "Python3" }, { "code": "# Importing Pandas libraryimport pandas as pd # Skipping 2 rows from enddf = pd.read_csv(\"students.csv\", skipfooter = 5, engine = 'python') # Show the dataframedf", "e": 2903, "s": 2706, "text": null }, { "code": null, "e": 2914, "s": 2903, "text": "Output : " }, { "code": null, "e": 2929, "s": 2916, "text": "simmytarika5" }, { "code": null, "e": 2946, "s": 2929, "text": "surinderdawra388" }, { "code": null, "e": 2955, "s": 2946, "text": "sweetyty" }, { "code": null, "e": 2979, "s": 2955, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2993, "s": 2979, "text": "Python-pandas" }, { "code": null, "e": 3000, "s": 2993, "text": "Python" }, { "code": null, "e": 3098, "s": 3000, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3130, "s": 3098, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3157, "s": 3130, "text": "Python Classes and Objects" }, { "code": null, "e": 3178, "s": 3157, "text": "Python OOPs Concepts" }, { "code": null, "e": 3201, "s": 3178, "text": "Introduction To PYTHON" }, { "code": null, "e": 3232, "s": 3201, "text": "Python | os.path.join() method" }, { "code": null, "e": 3288, "s": 3232, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 3330, "s": 3288, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 3372, "s": 3330, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3411, "s": 3372, "text": "Python | Get unique values from a list" } ]
redBus Interview Experience for Software Engineer | On-Campus 2021
05 Oct, 2021 Redbus visited our campus in the month of September 2021 for Software Engineer role. The shortlist for the online test was done on the basis of 2 parameters: Parameter 1: 10th & 12th/Diploma marks – 87% & aboveParameter 2: BE CGPA – 8.5 & above Parameter 1: 10th & 12th/Diploma marks – 87% & above Parameter 2: BE CGPA – 8.5 & above Round 1(Online Test): Test was moderate with 23 MCQs and 3 programming questions. MCQs were fine with questions on java concepts, c++ code snippets, and moderate aptitude questions. Coding was a bit tough. One of the questions that I remember is: Write a program in the language of your choice to find out how many minutes M will it take for a phone to reach from charge A to charge B (A and B are inputs, M should be the output). The rate at which it gets charged at different levels was given. For example: 0<= C <= 10 : 8 mins 11<= C <= 50 : 6 mins And so on Sample: If A= 0 and B=5 then M is 8 because in 8 minutes it reaches 10 charge which is greater than 5. Getting the output for at least 1 program along with decent performance in MCQs was sufficient to clear the test. 46 out of 211 students were shortlisted for the next round Round 2:(Technical Interview 1): Introduce yourself Coding question to solve ( first occurrence of a number, binary search (palindrome, sorting for others)) and even explain the approach used with time complexity. Questions regarding projects are mentioned in the resume. I was asked to show the code if the code is there in the system. They shared a document having 2 coding questions (divisibility by 3, 5, or 10 & print element that is in the same position in 2 unequal length lists), 2 MCQ of guess the output (pointer questions), and 2-3 logical questions (relationship, number pattern, etc) which I was asked to solve. 30 students were shortlisted for the next round. Round 3(Technical Interview 2): Introduce yourself Technical questions regarding oops concepts of java joins and normalization in DBMS etc. Questions and discussions regarding projects. Advantages of python and java over each other. Coding question on finding the minimum element appearing before the maximum element in a list. 20 students were shortlisted for the next round. Round 4(HR Round): 3rd level of discussion Technical questions like the implementation of stacks, stacks using queues or vice versa Design a database table for a bus traveling from so and so time to so and so destinations. HR questions like what was the most difficult situation encountered in life How did you handle differences between your project partner while working on the project etc? What are you passionate about in life? Which technology would you like to work on in redbus 8 students were selected for a full-time offer. Marketing On-Campus redBus Interview Experiences redBus Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Google SWE Interview Experience (Google Online Coding Challenge) 2022 Amazon Interview Experience for SDE 1 Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022 Amazon Interview Experience SDE-2 (3 Years Experienced) Write It Up: Share Your Interview Experiences TCS Ninja Interview Experience (2020 batch) Amazon Interview Experience for SDE-1 Nagarro Interview Experience | On-Campus 2021 Nagarro Interview Experience Samsung RnD Coding Round Questions
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Oct, 2021" }, { "code": null, "e": 186, "s": 28, "text": "Redbus visited our campus in the month of September 2021 for Software Engineer role. The shortlist for the online test was done on the basis of 2 parameters:" }, { "code": null, "e": 273, "s": 186, "text": "Parameter 1: 10th & 12th/Diploma marks – 87% & aboveParameter 2: BE CGPA – 8.5 & above" }, { "code": null, "e": 326, "s": 273, "text": "Parameter 1: 10th & 12th/Diploma marks – 87% & above" }, { "code": null, "e": 361, "s": 326, "text": "Parameter 2: BE CGPA – 8.5 & above" }, { "code": null, "e": 567, "s": 361, "text": "Round 1(Online Test): Test was moderate with 23 MCQs and 3 programming questions. MCQs were fine with questions on java concepts, c++ code snippets, and moderate aptitude questions. Coding was a bit tough." }, { "code": null, "e": 608, "s": 567, "text": "One of the questions that I remember is:" }, { "code": null, "e": 858, "s": 608, "text": "Write a program in the language of your choice to find out how many minutes M will it take for a phone to reach from charge A to charge B (A and B are inputs, M should be the output). The rate at which it gets charged at different levels was given. " }, { "code": null, "e": 1031, "s": 860, "text": "For example:\n0<= C <= 10 : 8 mins\n11<= C <= 50 : 6 mins\nAnd so on\n\nSample: If A= 0 and B=5 then M is 8 because in 8 minutes it reaches 10 \ncharge which is greater than 5." }, { "code": null, "e": 1145, "s": 1031, "text": "Getting the output for at least 1 program along with decent performance in MCQs was sufficient to clear the test." }, { "code": null, "e": 1204, "s": 1145, "text": "46 out of 211 students were shortlisted for the next round" }, { "code": null, "e": 1237, "s": 1204, "text": "Round 2:(Technical Interview 1):" }, { "code": null, "e": 1256, "s": 1237, "text": "Introduce yourself" }, { "code": null, "e": 1418, "s": 1256, "text": "Coding question to solve ( first occurrence of a number, binary search (palindrome, sorting for others)) and even explain the approach used with time complexity." }, { "code": null, "e": 1541, "s": 1418, "text": "Questions regarding projects are mentioned in the resume. I was asked to show the code if the code is there in the system." }, { "code": null, "e": 1829, "s": 1541, "text": "They shared a document having 2 coding questions (divisibility by 3, 5, or 10 & print element that is in the same position in 2 unequal length lists), 2 MCQ of guess the output (pointer questions), and 2-3 logical questions (relationship, number pattern, etc) which I was asked to solve." }, { "code": null, "e": 1878, "s": 1829, "text": "30 students were shortlisted for the next round." }, { "code": null, "e": 1910, "s": 1878, "text": "Round 3(Technical Interview 2):" }, { "code": null, "e": 1929, "s": 1910, "text": "Introduce yourself" }, { "code": null, "e": 2018, "s": 1929, "text": "Technical questions regarding oops concepts of java joins and normalization in DBMS etc." }, { "code": null, "e": 2064, "s": 2018, "text": "Questions and discussions regarding projects." }, { "code": null, "e": 2111, "s": 2064, "text": "Advantages of python and java over each other." }, { "code": null, "e": 2206, "s": 2111, "text": "Coding question on finding the minimum element appearing before the maximum element in a list." }, { "code": null, "e": 2255, "s": 2206, "text": "20 students were shortlisted for the next round." }, { "code": null, "e": 2299, "s": 2255, "text": "Round 4(HR Round): 3rd level of discussion " }, { "code": null, "e": 2388, "s": 2299, "text": "Technical questions like the implementation of stacks, stacks using queues or vice versa" }, { "code": null, "e": 2479, "s": 2388, "text": "Design a database table for a bus traveling from so and so time to so and so destinations." }, { "code": null, "e": 2555, "s": 2479, "text": "HR questions like what was the most difficult situation encountered in life" }, { "code": null, "e": 2649, "s": 2555, "text": "How did you handle differences between your project partner while working on the project etc?" }, { "code": null, "e": 2688, "s": 2649, "text": "What are you passionate about in life?" }, { "code": null, "e": 2741, "s": 2688, "text": "Which technology would you like to work on in redbus" }, { "code": null, "e": 2789, "s": 2741, "text": "8 students were selected for a full-time offer." }, { "code": null, "e": 2799, "s": 2789, "text": "Marketing" }, { "code": null, "e": 2809, "s": 2799, "text": "On-Campus" }, { "code": null, "e": 2816, "s": 2809, "text": "redBus" }, { "code": null, "e": 2838, "s": 2816, "text": "Interview Experiences" }, { "code": null, "e": 2845, "s": 2838, "text": "redBus" }, { "code": null, "e": 2943, "s": 2845, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3013, "s": 2943, "text": "Google SWE Interview Experience (Google Online Coding Challenge) 2022" }, { "code": null, "e": 3051, "s": 3013, "text": "Amazon Interview Experience for SDE 1" }, { "code": null, "e": 3124, "s": 3051, "text": "Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022" }, { "code": null, "e": 3180, "s": 3124, "text": "Amazon Interview Experience SDE-2 (3 Years Experienced)" }, { "code": null, "e": 3226, "s": 3180, "text": "Write It Up: Share Your Interview Experiences" }, { "code": null, "e": 3270, "s": 3226, "text": "TCS Ninja Interview Experience (2020 batch)" }, { "code": null, "e": 3308, "s": 3270, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 3354, "s": 3308, "text": "Nagarro Interview Experience | On-Campus 2021" }, { "code": null, "e": 3383, "s": 3354, "text": "Nagarro Interview Experience" } ]
Vector forEach() method in Java
17 Sep, 2018 The forEach() method of Vector is used to perform a given action for every element of the Iterable of Vector until all elements have been Processed by the method or an exception occurs. The operations are performed in the order of iteration if the order is specified by the method. Exceptions thrown by the Operation are passed to the caller. Until and unless an overriding class has specified a concurrent modification policy, the operation cannot modify the underlying source of elements so we can say that behavior of this method is unspecified. Retrieving Elements from Collection in Java. Syntax: public void forEach(Consumer<? super E> action) Parameter: This method takes a parameter action which represents the action to be performed for each element. Return Value: This method does not returns anything. Exception: This method throws NullPointerException if the specified action is null. Below programs illustrate forEach() method of Vector: Example 1: Program to demonstrate forEach() method on Vector which contains a collection of String. // Java Program Demonstrate forEach()// method of Vector import java.util.*;public class GFG { public static void main(String[] args) { // create an Vector which going to // contains a collection of Strings Vector<String> data = new Vector<String>(); // Add String to Vector data.add("Saltlake"); data.add("LakeTown"); data.add("Kestopur"); System.out.println("List of Strings data"); // forEach method of Vector and // print data data.forEach((n) -> System.out.println(n)); }} List of Strings data Saltlake LakeTown Kestopur Example 2: Program to demonstrate forEach() method on Vector which contains collection of Objects. // Java Program Demonstrate forEach()// method of Vector import java.util.*;public class GFG { public static void main(String[] args) { // create an Vector which going to // contains a collection of objects Vector<DataClass> vector = new Vector<DataClass>(); // Add objects to vector vector.add(new DataClass("Shape", "Square")); vector.add(new DataClass("Area", "2433Sqft")); vector.add(new DataClass("Radius", "25m")); // print result System.out.println("list of Objects:"); // forEach method of Vector and // print Objects vector.forEach((n) -> print(n)); } // printing object data public static void print(DataClass n) { System.out.println("****************"); System.out.println("Object Details"); System.out.println("key : " + n.key); System.out.println("value : " + n.value); }} // create a classclass DataClass { public String key; public String value; DataClass(String key, String value) { this.key = key; this.value = value; }} list of Objects: **************** Object Details key : Shape value : Square **************** Object Details key : Area value : 2433Sqft **************** Object Details key : Radius value : 25m Reference: https://docs.oracle.com/javase/10/docs/api/java/util/Vector.html#forEach(java.util.function.Consumer) Java - util package Java-Collections Java-Functions Java-Vector Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Split() String method in Java with examples Arrays.sort() in Java with examples Object Oriented Programming (OOPs) Concept in Java Reverse a string in Java For-each loop in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java
[ { "code": null, "e": 53, "s": 25, "text": "\n17 Sep, 2018" }, { "code": null, "e": 239, "s": 53, "text": "The forEach() method of Vector is used to perform a given action for every element of the Iterable of Vector until all elements have been Processed by the method or an exception occurs." }, { "code": null, "e": 396, "s": 239, "text": "The operations are performed in the order of iteration if the order is specified by the method. Exceptions thrown by the Operation are passed to the caller." }, { "code": null, "e": 602, "s": 396, "text": "Until and unless an overriding class has specified a concurrent modification policy, the operation cannot modify the underlying source of elements so we can say that behavior of this method is unspecified." }, { "code": null, "e": 647, "s": 602, "text": "Retrieving Elements from Collection in Java." }, { "code": null, "e": 655, "s": 647, "text": "Syntax:" }, { "code": null, "e": 703, "s": 655, "text": "public void forEach(Consumer<? super E> action)" }, { "code": null, "e": 813, "s": 703, "text": "Parameter: This method takes a parameter action which represents the action to be performed for each element." }, { "code": null, "e": 866, "s": 813, "text": "Return Value: This method does not returns anything." }, { "code": null, "e": 950, "s": 866, "text": "Exception: This method throws NullPointerException if the specified action is null." }, { "code": null, "e": 1004, "s": 950, "text": "Below programs illustrate forEach() method of Vector:" }, { "code": null, "e": 1104, "s": 1004, "text": "Example 1: Program to demonstrate forEach() method on Vector which contains a collection of String." }, { "code": "// Java Program Demonstrate forEach()// method of Vector import java.util.*;public class GFG { public static void main(String[] args) { // create an Vector which going to // contains a collection of Strings Vector<String> data = new Vector<String>(); // Add String to Vector data.add(\"Saltlake\"); data.add(\"LakeTown\"); data.add(\"Kestopur\"); System.out.println(\"List of Strings data\"); // forEach method of Vector and // print data data.forEach((n) -> System.out.println(n)); }}", "e": 1675, "s": 1104, "text": null }, { "code": null, "e": 1724, "s": 1675, "text": "List of Strings data\nSaltlake\nLakeTown\nKestopur\n" }, { "code": null, "e": 1823, "s": 1724, "text": "Example 2: Program to demonstrate forEach() method on Vector which contains collection of Objects." }, { "code": "// Java Program Demonstrate forEach()// method of Vector import java.util.*;public class GFG { public static void main(String[] args) { // create an Vector which going to // contains a collection of objects Vector<DataClass> vector = new Vector<DataClass>(); // Add objects to vector vector.add(new DataClass(\"Shape\", \"Square\")); vector.add(new DataClass(\"Area\", \"2433Sqft\")); vector.add(new DataClass(\"Radius\", \"25m\")); // print result System.out.println(\"list of Objects:\"); // forEach method of Vector and // print Objects vector.forEach((n) -> print(n)); } // printing object data public static void print(DataClass n) { System.out.println(\"****************\"); System.out.println(\"Object Details\"); System.out.println(\"key : \" + n.key); System.out.println(\"value : \" + n.value); }} // create a classclass DataClass { public String key; public String value; DataClass(String key, String value) { this.key = key; this.value = value; }}", "e": 2939, "s": 1823, "text": null }, { "code": null, "e": 3133, "s": 2939, "text": "list of Objects:\n****************\nObject Details\nkey : Shape\nvalue : Square\n****************\nObject Details\nkey : Area\nvalue : 2433Sqft\n****************\nObject Details\nkey : Radius\nvalue : 25m\n" }, { "code": null, "e": 3246, "s": 3133, "text": "Reference: https://docs.oracle.com/javase/10/docs/api/java/util/Vector.html#forEach(java.util.function.Consumer)" }, { "code": null, "e": 3266, "s": 3246, "text": "Java - util package" }, { "code": null, "e": 3283, "s": 3266, "text": "Java-Collections" }, { "code": null, "e": 3298, "s": 3283, "text": "Java-Functions" }, { "code": null, "e": 3310, "s": 3298, "text": "Java-Vector" }, { "code": null, "e": 3315, "s": 3310, "text": "Java" }, { "code": null, "e": 3320, "s": 3315, "text": "Java" }, { "code": null, "e": 3337, "s": 3320, "text": "Java-Collections" }, { "code": null, "e": 3435, "s": 3337, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3450, "s": 3435, "text": "Arrays in Java" }, { "code": null, "e": 3494, "s": 3450, "text": "Split() String method in Java with examples" }, { "code": null, "e": 3530, "s": 3494, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 3581, "s": 3530, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 3606, "s": 3581, "text": "Reverse a string in Java" }, { "code": null, "e": 3628, "s": 3606, "text": "For-each loop in Java" }, { "code": null, "e": 3659, "s": 3628, "text": "How to iterate any Map in Java" }, { "code": null, "e": 3678, "s": 3659, "text": "Interfaces in Java" }, { "code": null, "e": 3708, "s": 3678, "text": "HashMap in Java with Examples" } ]
How to Run Spring Boot Application?
20 Dec, 2021 Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework and making a production-ready application in it takes very little time. Following are some of the features of Spring Boot: It allows avoiding heavy configuration of XML which is present in spring It provides easy maintenance and creation of REST endpoints It includes embedded Tomcat-server Deployment is very easy, war and jar files can be easily deployed in the tomcat server For more information please refer to this article: Introduction to Spring Boot Generally, to develop a Spring Boot Application we choose Eclipse, Spring Tool Suite, and IntelliJ IDEA IDE. So in this article, we are going to run our application in these 3 IDEs. The Eclipse IDE is famous for the Java Integrated Development Environment (IDE), but it has a number of pretty cool IDEs, including the C/C++ IDE, JavaScript/TypeScript IDE, PHP IDE, and more. Step by Step Implementation: Create and set up Spring Boot project.Add the spring-web dependency in your pom.xml file.Create one package and name the package as “controller”Run the Spring Boot application Create and set up Spring Boot project. Add the spring-web dependency in your pom.xml file. Create one package and name the package as “controller” Run the Spring Boot application Step 1: Create and Setup Spring Boot Project in Eclipse IDE One should know how to create and set up Spring Boot Project in Eclipse IDE and create your first Spring Boot Application in Eclipse IDE. Step 2: Add the spring-web dependency in your pom.xml file. Go to the pom.xml file inside your project and add the following spring-web dependency. XML <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency> Step 3: In your project create one package and name the package as “controller”. In the controller package create a class and name it as DemoController. Below is the code for the DemoController.java file. Java package com.example.demo.controller; import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody; @Controllerpublic class DemoController { @RequestMapping("/hello") @ResponseBody public String helloWorld() { return "Hello World!"; }} We have used the below annotations in our controller layer. Here in this example, the URI path is /hello. @Controller: This is used to specify the controller. @RequestMapping: This is used to map to the Spring MVC controller method. @ResponseBody: Used to bind the HTTP response body with a domain object in the return type. Now, our controller is ready. Let’s run our application inside the DemoApplication.java file. There is no need to change anything inside the DemoApplication.java file. Java package com.example.demo; import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplicationpublic class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } Step 4: Run the Spring Boot Application To run the application click on the green icon as seen in the below image. After successfully running the application you can see the console as shown in the below image. Your Tomcat server started on port 8989. Try this Tomcat URL, which is running on http://localhost:8989/hello Run Spring Boot Application in IntelliJ IDEA IntelliJ IDEA is an integrated development environment(IDE) written in Java. It is used for developing computer software. This IDE is developed by Jetbrains and is available as an Apache 2 Licensed community edition and a commercial edition. It is an intelligent, context-aware IDE for working with Java and other JVM languages like Kotlin, Scala, and Groovy on all sorts of applications. Additionally, IntelliJ IDEA Ultimate can help you develop full-stack web applications, thanks to its powerful integrated tools, support for JavaScript and related technologies, and advanced support for popular frameworks like Spring, Spring Boot, Jakarta EE, Micronaut, Quarkus, Helidon. So in this article, we are going to discuss how to run your first spring boot application in IntelliJ IDEA. Prerequisite: Download and Install IntelliJ IDEA in your system. Please refer to this article Step by Step guide to install Intellij Idea to Install IntelliJ IDEA in Your System. Procedure: Create and Setup Spring Boot ProjectCreating or importing the spring boot project a file name Application.javaRun the Spring Boot ApplicationTomcat server will be started.Re-run the application again Create and Setup Spring Boot Project Creating or importing the spring boot project a file name Application.java Run the Spring Boot Application Tomcat server will be started. Re-run the application again Step 1: Create and Setup Spring Boot Project in IntelliJ IDEA You may refer to this article How to Create and Setup Spring Boot Project in IntelliJ IDEA and create your first Spring Boot Application in IntelliJ IDEA. Step 2: After successfully creating or importing the spring boot project a file name Application.java (Herre DemoApplication) will be created automatically and this is your entry point. You can consider it as the main method of a Spring Boot application. Step 3: Run the Spring Boot Application Method 1: To run this application now Right-click on the Application.java > Run “DemoApplication.main()” as shown in the below image. or you may type the shortcut key combination (Ctrl + Shift + F10) to run the application. Method 2: Directly click on the green color triangle button as shown in the below image then choose Run ‘DemoApplication.main()’. Step 4: After successfully running the application you can see the console as shown in the below image. Your Tomcat server started on port 8080. The default port of the Tomcat server is 8080 and can be changed in the application.properties file by using this following line of code. server.port=8989 Step 5: Now re-run the application again and you can see Your Tomcat server started on the port that you have given like the below image. You can access the output screen in the following URL: http://localhost:8989/. Note that at last provide your port number. Spring Tool Suite (STS) is a java IDE tailored for developing Spring-based enterprise applications. It is easier, faster, and more convenient. And most importantly it is based on Eclipse IDE. STS is free, open-source, and powered by VMware. Spring Tools 4 is the next generation of Spring tooling for the favorite coding environment. Largely rebuilt from scratch, it provides world-class support for developing Spring-based enterprise applications, whether you prefer Eclipse, Visual Studio Code, or Theia IDE. So in this article, we are going to discuss how to run your first spring boot application in STS. Prerequisite: Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE in your system. You may refer to this article: How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE? Procedure: Create Spring Boot project in Spring Tool SuiteImport the Project into STS IDEAn entry file named Application file will be created for STSRun the application on the server. Create Spring Boot project in Spring Tool Suite Import the Project into STS IDE An entry file named Application file will be created for STS Run the application on the server. Step 1: Create Your Spring Boot Project in Spring Tool Suite You may refer to this article How to Create and Setup Spring Boot Project in Spring Tool Suite and create your first Spring Boot Application. Or you may Create Your Spring Boot Project in Spring Initializer and import the project into your STS IDE. Please refer to this article to Create Spring Boot Project in Spring Initializer. Step 2: How to Import the Project into Your STS IDE? 2.1: Go to your STS IDE > File > Open Project from File System as shown in the below image. 2.2: A pop-up window will occur like the following. Here you have to choose the directory that has been generated while creating the spring boot project in Spring Initializer. And then click on the Finish button. Step 3: After successfully creating or importing the spring boot project a file name Application.java (Herre DemoApplication) will be created automatically and this is your entry point. You can consider it as the main method of a Spring Boot application. Step 4: In order to run this application now, Right-click on the Application.java > Run As > Spring Boot App as shown in the below image. Step 5: After successfully running the application you can see the console where the Tomcat server starts on default port number 8080 as shown in the below image. now geeks you must be wondering about what if we do not want it to be run on the default port number that is the default port of the Tomcat server is 8080. We can change the port number in the application.properties file by using the following line of code as follows: server.port=8989 A. Now re-run the application again and you can see Your Tomcat server started on the port that you have given like the below image. B. If you are encountered with the following error then it is highly recommended that you should change your port number. You can access the output screen in the following URL: http://localhost:8080/. Note that at last provide your port number. simmytarika5 Java-Spring-Boot Picked 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": "\n20 Dec, 2021" }, { "code": null, "e": 502, "s": 28, "text": "Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework and making a production-ready application in it takes very little time. Following are some of the features of Spring Boot:" }, { "code": null, "e": 575, "s": 502, "text": "It allows avoiding heavy configuration of XML which is present in spring" }, { "code": null, "e": 635, "s": 575, "text": "It provides easy maintenance and creation of REST endpoints" }, { "code": null, "e": 670, "s": 635, "text": "It includes embedded Tomcat-server" }, { "code": null, "e": 757, "s": 670, "text": "Deployment is very easy, war and jar files can be easily deployed in the tomcat server" }, { "code": null, "e": 836, "s": 757, "text": "For more information please refer to this article: Introduction to Spring Boot" }, { "code": null, "e": 1019, "s": 836, "text": "Generally, to develop a Spring Boot Application we choose Eclipse, Spring Tool Suite, and IntelliJ IDEA IDE. So in this article, we are going to run our application in these 3 IDEs. " }, { "code": null, "e": 1213, "s": 1019, "text": "The Eclipse IDE is famous for the Java Integrated Development Environment (IDE), but it has a number of pretty cool IDEs, including the C/C++ IDE, JavaScript/TypeScript IDE, PHP IDE, and more. " }, { "code": null, "e": 1242, "s": 1213, "text": "Step by Step Implementation:" }, { "code": null, "e": 1418, "s": 1242, "text": "Create and set up Spring Boot project.Add the spring-web dependency in your pom.xml file.Create one package and name the package as “controller”Run the Spring Boot application" }, { "code": null, "e": 1457, "s": 1418, "text": "Create and set up Spring Boot project." }, { "code": null, "e": 1509, "s": 1457, "text": "Add the spring-web dependency in your pom.xml file." }, { "code": null, "e": 1565, "s": 1509, "text": "Create one package and name the package as “controller”" }, { "code": null, "e": 1597, "s": 1565, "text": "Run the Spring Boot application" }, { "code": null, "e": 1657, "s": 1597, "text": "Step 1: Create and Setup Spring Boot Project in Eclipse IDE" }, { "code": null, "e": 1796, "s": 1657, "text": "One should know how to create and set up Spring Boot Project in Eclipse IDE and create your first Spring Boot Application in Eclipse IDE. " }, { "code": null, "e": 1944, "s": 1796, "text": "Step 2: Add the spring-web dependency in your pom.xml file. Go to the pom.xml file inside your project and add the following spring-web dependency." }, { "code": null, "e": 1948, "s": 1944, "text": "XML" }, { "code": "<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency>", "e": 2073, "s": 1948, "text": null }, { "code": null, "e": 2278, "s": 2073, "text": "Step 3: In your project create one package and name the package as “controller”. In the controller package create a class and name it as DemoController. Below is the code for the DemoController.java file." }, { "code": null, "e": 2283, "s": 2278, "text": "Java" }, { "code": "package com.example.demo.controller; import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody; @Controllerpublic class DemoController { @RequestMapping(\"/hello\") @ResponseBody public String helloWorld() { return \"Hello World!\"; }}", "e": 2651, "s": 2283, "text": null }, { "code": null, "e": 2757, "s": 2651, "text": "We have used the below annotations in our controller layer. Here in this example, the URI path is /hello." }, { "code": null, "e": 2810, "s": 2757, "text": "@Controller: This is used to specify the controller." }, { "code": null, "e": 2884, "s": 2810, "text": "@RequestMapping: This is used to map to the Spring MVC controller method." }, { "code": null, "e": 2976, "s": 2884, "text": "@ResponseBody: Used to bind the HTTP response body with a domain object in the return type." }, { "code": null, "e": 3146, "s": 2976, "text": "Now, our controller is ready. Let’s run our application inside the DemoApplication.java file. There is no need to change anything inside the DemoApplication.java file. " }, { "code": null, "e": 3151, "s": 3146, "text": "Java" }, { "code": "package com.example.demo; import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplicationpublic class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }", "e": 3460, "s": 3151, "text": null }, { "code": null, "e": 3500, "s": 3460, "text": "Step 4: Run the Spring Boot Application" }, { "code": null, "e": 3576, "s": 3500, "text": "To run the application click on the green icon as seen in the below image. " }, { "code": null, "e": 3714, "s": 3576, "text": "After successfully running the application you can see the console as shown in the below image. Your Tomcat server started on port 8989. " }, { "code": null, "e": 3784, "s": 3714, "text": "Try this Tomcat URL, which is running on http://localhost:8989/hello " }, { "code": null, "e": 3829, "s": 3784, "text": "Run Spring Boot Application in IntelliJ IDEA" }, { "code": null, "e": 4616, "s": 3829, "text": "IntelliJ IDEA is an integrated development environment(IDE) written in Java. It is used for developing computer software. This IDE is developed by Jetbrains and is available as an Apache 2 Licensed community edition and a commercial edition. It is an intelligent, context-aware IDE for working with Java and other JVM languages like Kotlin, Scala, and Groovy on all sorts of applications. Additionally, IntelliJ IDEA Ultimate can help you develop full-stack web applications, thanks to its powerful integrated tools, support for JavaScript and related technologies, and advanced support for popular frameworks like Spring, Spring Boot, Jakarta EE, Micronaut, Quarkus, Helidon. So in this article, we are going to discuss how to run your first spring boot application in IntelliJ IDEA. " }, { "code": null, "e": 4795, "s": 4616, "text": "Prerequisite: Download and Install IntelliJ IDEA in your system. Please refer to this article Step by Step guide to install Intellij Idea to Install IntelliJ IDEA in Your System." }, { "code": null, "e": 4806, "s": 4795, "text": "Procedure:" }, { "code": null, "e": 5006, "s": 4806, "text": "Create and Setup Spring Boot ProjectCreating or importing the spring boot project a file name Application.javaRun the Spring Boot ApplicationTomcat server will be started.Re-run the application again" }, { "code": null, "e": 5043, "s": 5006, "text": "Create and Setup Spring Boot Project" }, { "code": null, "e": 5118, "s": 5043, "text": "Creating or importing the spring boot project a file name Application.java" }, { "code": null, "e": 5150, "s": 5118, "text": "Run the Spring Boot Application" }, { "code": null, "e": 5181, "s": 5150, "text": "Tomcat server will be started." }, { "code": null, "e": 5210, "s": 5181, "text": "Re-run the application again" }, { "code": null, "e": 5272, "s": 5210, "text": "Step 1: Create and Setup Spring Boot Project in IntelliJ IDEA" }, { "code": null, "e": 5427, "s": 5272, "text": "You may refer to this article How to Create and Setup Spring Boot Project in IntelliJ IDEA and create your first Spring Boot Application in IntelliJ IDEA." }, { "code": null, "e": 5683, "s": 5427, "text": "Step 2: After successfully creating or importing the spring boot project a file name Application.java (Herre DemoApplication) will be created automatically and this is your entry point. You can consider it as the main method of a Spring Boot application. " }, { "code": null, "e": 5723, "s": 5683, "text": "Step 3: Run the Spring Boot Application" }, { "code": null, "e": 5948, "s": 5723, "text": "Method 1: To run this application now Right-click on the Application.java > Run “DemoApplication.main()” as shown in the below image. or you may type the shortcut key combination (Ctrl + Shift + F10) to run the application. " }, { "code": null, "e": 6079, "s": 5948, "text": "Method 2: Directly click on the green color triangle button as shown in the below image then choose Run ‘DemoApplication.main()’. " }, { "code": null, "e": 6225, "s": 6079, "text": "Step 4: After successfully running the application you can see the console as shown in the below image. Your Tomcat server started on port 8080. " }, { "code": null, "e": 6363, "s": 6225, "text": "The default port of the Tomcat server is 8080 and can be changed in the application.properties file by using this following line of code." }, { "code": null, "e": 6380, "s": 6363, "text": "server.port=8989" }, { "code": null, "e": 6518, "s": 6380, "text": "Step 5: Now re-run the application again and you can see Your Tomcat server started on the port that you have given like the below image." }, { "code": null, "e": 6643, "s": 6518, "text": "You can access the output screen in the following URL: http://localhost:8989/. Note that at last provide your port number. " }, { "code": null, "e": 7253, "s": 6643, "text": "Spring Tool Suite (STS) is a java IDE tailored for developing Spring-based enterprise applications. It is easier, faster, and more convenient. And most importantly it is based on Eclipse IDE. STS is free, open-source, and powered by VMware. Spring Tools 4 is the next generation of Spring tooling for the favorite coding environment. Largely rebuilt from scratch, it provides world-class support for developing Spring-based enterprise applications, whether you prefer Eclipse, Visual Studio Code, or Theia IDE. So in this article, we are going to discuss how to run your first spring boot application in STS. " }, { "code": null, "e": 7466, "s": 7253, "text": "Prerequisite: Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE in your system. You may refer to this article: How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE?" }, { "code": null, "e": 7477, "s": 7466, "text": "Procedure:" }, { "code": null, "e": 7650, "s": 7477, "text": "Create Spring Boot project in Spring Tool SuiteImport the Project into STS IDEAn entry file named Application file will be created for STSRun the application on the server." }, { "code": null, "e": 7698, "s": 7650, "text": "Create Spring Boot project in Spring Tool Suite" }, { "code": null, "e": 7730, "s": 7698, "text": "Import the Project into STS IDE" }, { "code": null, "e": 7791, "s": 7730, "text": "An entry file named Application file will be created for STS" }, { "code": null, "e": 7826, "s": 7791, "text": "Run the application on the server." }, { "code": null, "e": 7887, "s": 7826, "text": "Step 1: Create Your Spring Boot Project in Spring Tool Suite" }, { "code": null, "e": 8218, "s": 7887, "text": "You may refer to this article How to Create and Setup Spring Boot Project in Spring Tool Suite and create your first Spring Boot Application. Or you may Create Your Spring Boot Project in Spring Initializer and import the project into your STS IDE. Please refer to this article to Create Spring Boot Project in Spring Initializer." }, { "code": null, "e": 8271, "s": 8218, "text": "Step 2: How to Import the Project into Your STS IDE?" }, { "code": null, "e": 8364, "s": 8271, "text": "2.1: Go to your STS IDE > File > Open Project from File System as shown in the below image. " }, { "code": null, "e": 8579, "s": 8364, "text": "2.2: A pop-up window will occur like the following. Here you have to choose the directory that has been generated while creating the spring boot project in Spring Initializer. And then click on the Finish button. " }, { "code": null, "e": 8835, "s": 8579, "text": "Step 3: After successfully creating or importing the spring boot project a file name Application.java (Herre DemoApplication) will be created automatically and this is your entry point. You can consider it as the main method of a Spring Boot application. " }, { "code": null, "e": 8973, "s": 8835, "text": "Step 4: In order to run this application now, Right-click on the Application.java > Run As > Spring Boot App as shown in the below image." }, { "code": null, "e": 9137, "s": 8973, "text": "Step 5: After successfully running the application you can see the console where the Tomcat server starts on default port number 8080 as shown in the below image. " }, { "code": null, "e": 9406, "s": 9137, "text": "now geeks you must be wondering about what if we do not want it to be run on the default port number that is the default port of the Tomcat server is 8080. We can change the port number in the application.properties file by using the following line of code as follows:" }, { "code": null, "e": 9423, "s": 9406, "text": "server.port=8989" }, { "code": null, "e": 9556, "s": 9423, "text": "A. Now re-run the application again and you can see Your Tomcat server started on the port that you have given like the below image." }, { "code": null, "e": 9678, "s": 9556, "text": "B. If you are encountered with the following error then it is highly recommended that you should change your port number." }, { "code": null, "e": 9802, "s": 9678, "text": "You can access the output screen in the following URL: http://localhost:8080/. Note that at last provide your port number. " }, { "code": null, "e": 9815, "s": 9802, "text": "simmytarika5" }, { "code": null, "e": 9832, "s": 9815, "text": "Java-Spring-Boot" }, { "code": null, "e": 9839, "s": 9832, "text": "Picked" }, { "code": null, "e": 9844, "s": 9839, "text": "Java" }, { "code": null, "e": 9849, "s": 9844, "text": "Java" } ]
Difference between find and find_all in BeautifulSoup – Python
21 Apr, 2021 BeautifulSoup is one of the most common libraries in Python which is used for navigating, searching, and pulling out data from HTML or XML webpages. The most common methods used for finding anything on the webpage are find() and find_all(). However, there is a slight difference between these two, let’s discuss them in detail. The find method is used for finding out the first tag with the specified name or id and returning an object of type bs4. Syntax: find_syntax=soup.find(“#Widget Name”, {“id”:”#Id name of widget in which you want to edit”}).get_text() Example: For instance, consider this simple HTML webpage having different paragraph tags. HTML <!DOCTYPE html><html> <head> Geeks For Geeks </head> <body> <div> <p id="vinayak">King</p> <p id="vinayak1">Prince</p> <p id="vinayak2">Queen</p> </div> <p id="vinayak3">Princess</p> </body> </html> For obtaining the text King, we use find method. Python # Find example # Import the libraries BeautifulSoup# and osfrom bs4 import BeautifulSoup as bsimport os # Remove the last segment of the pathbase=os.path.dirname(os.path.abspath(__file__)) # Open the HTML in which you want to# make changeshtml=open(os.path.join(base, 'gfg.html')) # Parse HTML file in Beautiful Soupsoup=bs(html, 'html.parser') # Obtain the text from the widget after # finding itfind_example=soup.find("p", {"id":"vinayak"}).get_text() # Printing the text obtained received # in previous stepprint(find_example) Output: The find_all method is used for finding out all tags with the specified tag name or id and returning them as a list of type bs4. for word in soup.find_all(‘id’): find_all_syntax=word.get_text() print(find_all_syntax) Example: For instance, consider this simple HTML webpage having different paragraph tags. HTML <!DOCTYPE html><html> <head> Geeks For Geeks </head> <body> <div> <p id="vinayak">King</p> <p id="vinayak1">Prince</p> <p id="vinayak2">Queen</p> </div> <p id="vinayak3">Princess</p> </body> </html> For obtaining all the text, i.e., King, Prince, Queen, Princess, we use find_all method. Python # find_all example # Import the libraries BeautifulSoup# and osfrom bs4 import BeautifulSoup as bsimport os # Remove the last segment of the pathbase=os.path.dirname(os.path.abspath(__file__)) # Open the HTML in which you want to # make changeshtml=open(os.path.join(base, 'gfg.html')) # Parse HTML file in Beautiful Soupsoup=bs(html, 'html.parser') # Construct a loop to find all the# p tagsfor word in soup.find_all('p'): # Obtain the text from the received # tags find_all_example=word.get_text() # Print the text obtained received # in previous step print(find_all_example) Output: 1 find is used for returning the result when the searched element is found on the page. find_all is used for returning all the matches after scanning the entire document. 2 It is used for getting merely the first tag of the incoming HTML object for which condition is satisfied. It is used for getting all the incoming HTML objects for which condition is satisfied. 3 The return type of find is <class ‘bs4.element.Tag’>. The return type of find_all is <class ‘bs4.element.ResultSet’> 4 We can print only the first search as an output. We can print any search, I.e., second, third, last, etc. or all the searches as an output. 5 Prototype: find(tag, attributes, recursive, text, keywords) Prototype: findAll(tag, attributes, recursive, text, limit, keywords) Picked Python BeautifulSoup Difference Between Python 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 Stack vs Heap Memory Allocation Difference between Process and Thread Read JSON file using Python Python map() function Adding new column to existing DataFrame in Pandas Python Dictionary How to get column names in Pandas dataframe
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Apr, 2021" }, { "code": null, "e": 356, "s": 28, "text": "BeautifulSoup is one of the most common libraries in Python which is used for navigating, searching, and pulling out data from HTML or XML webpages. The most common methods used for finding anything on the webpage are find() and find_all(). However, there is a slight difference between these two, let’s discuss them in detail." }, { "code": null, "e": 477, "s": 356, "text": "The find method is used for finding out the first tag with the specified name or id and returning an object of type bs4." }, { "code": null, "e": 589, "s": 477, "text": "Syntax: find_syntax=soup.find(“#Widget Name”, {“id”:”#Id name of widget in which you want to edit”}).get_text()" }, { "code": null, "e": 598, "s": 589, "text": "Example:" }, { "code": null, "e": 679, "s": 598, "text": "For instance, consider this simple HTML webpage having different paragraph tags." }, { "code": null, "e": 684, "s": 679, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> Geeks For Geeks </head> <body> <div> <p id=\"vinayak\">King</p> <p id=\"vinayak1\">Prince</p> <p id=\"vinayak2\">Queen</p> </div> <p id=\"vinayak3\">Princess</p> </body> </html>", "e": 915, "s": 684, "text": null }, { "code": null, "e": 964, "s": 915, "text": "For obtaining the text King, we use find method." }, { "code": null, "e": 971, "s": 964, "text": "Python" }, { "code": "# Find example # Import the libraries BeautifulSoup# and osfrom bs4 import BeautifulSoup as bsimport os # Remove the last segment of the pathbase=os.path.dirname(os.path.abspath(__file__)) # Open the HTML in which you want to# make changeshtml=open(os.path.join(base, 'gfg.html')) # Parse HTML file in Beautiful Soupsoup=bs(html, 'html.parser') # Obtain the text from the widget after # finding itfind_example=soup.find(\"p\", {\"id\":\"vinayak\"}).get_text() # Printing the text obtained received # in previous stepprint(find_example)", "e": 1507, "s": 971, "text": null }, { "code": null, "e": 1515, "s": 1507, "text": "Output:" }, { "code": null, "e": 1644, "s": 1515, "text": "The find_all method is used for finding out all tags with the specified tag name or id and returning them as a list of type bs4." }, { "code": null, "e": 1677, "s": 1644, "text": "for word in soup.find_all(‘id’):" }, { "code": null, "e": 1714, "s": 1677, "text": " find_all_syntax=word.get_text()" }, { "code": null, "e": 1742, "s": 1714, "text": " print(find_all_syntax)" }, { "code": null, "e": 1751, "s": 1742, "text": "Example:" }, { "code": null, "e": 1832, "s": 1751, "text": "For instance, consider this simple HTML webpage having different paragraph tags." }, { "code": null, "e": 1837, "s": 1832, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> Geeks For Geeks </head> <body> <div> <p id=\"vinayak\">King</p> <p id=\"vinayak1\">Prince</p> <p id=\"vinayak2\">Queen</p> </div> <p id=\"vinayak3\">Princess</p> </body> </html>", "e": 2070, "s": 1837, "text": null }, { "code": null, "e": 2159, "s": 2070, "text": "For obtaining all the text, i.e., King, Prince, Queen, Princess, we use find_all method." }, { "code": null, "e": 2166, "s": 2159, "text": "Python" }, { "code": "# find_all example # Import the libraries BeautifulSoup# and osfrom bs4 import BeautifulSoup as bsimport os # Remove the last segment of the pathbase=os.path.dirname(os.path.abspath(__file__)) # Open the HTML in which you want to # make changeshtml=open(os.path.join(base, 'gfg.html')) # Parse HTML file in Beautiful Soupsoup=bs(html, 'html.parser') # Construct a loop to find all the# p tagsfor word in soup.find_all('p'): # Obtain the text from the received # tags find_all_example=word.get_text() # Print the text obtained received # in previous step print(find_all_example)", "e": 2772, "s": 2166, "text": null }, { "code": null, "e": 2780, "s": 2772, "text": "Output:" }, { "code": null, "e": 2782, "s": 2780, "text": "1" }, { "code": null, "e": 2869, "s": 2782, "text": "find is used for returning the result when the searched element is found on the page. " }, { "code": null, "e": 2952, "s": 2869, "text": "find_all is used for returning all the matches after scanning the entire document." }, { "code": null, "e": 2954, "s": 2952, "text": "2" }, { "code": null, "e": 3062, "s": 2954, "text": "It is used for getting merely the first tag of the incoming HTML object for which condition is satisfied. " }, { "code": null, "e": 3151, "s": 3062, "text": "It is used for getting all the incoming HTML objects for which condition is satisfied. " }, { "code": null, "e": 3153, "s": 3151, "text": "3" }, { "code": null, "e": 3207, "s": 3153, "text": "The return type of find is <class ‘bs4.element.Tag’>." }, { "code": null, "e": 3270, "s": 3207, "text": "The return type of find_all is <class ‘bs4.element.ResultSet’>" }, { "code": null, "e": 3272, "s": 3270, "text": "4" }, { "code": null, "e": 3321, "s": 3272, "text": "We can print only the first search as an output." }, { "code": null, "e": 3412, "s": 3321, "text": "We can print any search, I.e., second, third, last, etc. or all the searches as an output." }, { "code": null, "e": 3414, "s": 3412, "text": "5" }, { "code": null, "e": 3474, "s": 3414, "text": "Prototype: find(tag, attributes, recursive, text, keywords)" }, { "code": null, "e": 3544, "s": 3474, "text": "Prototype: findAll(tag, attributes, recursive, text, limit, keywords)" }, { "code": null, "e": 3551, "s": 3544, "text": "Picked" }, { "code": null, "e": 3572, "s": 3551, "text": "Python BeautifulSoup" }, { "code": null, "e": 3591, "s": 3572, "text": "Difference Between" }, { "code": null, "e": 3598, "s": 3591, "text": "Python" }, { "code": null, "e": 3696, "s": 3598, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3757, "s": 3696, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3825, "s": 3757, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 3862, "s": 3825, "text": "Differences between JDK, JRE and JVM" }, { "code": null, "e": 3894, "s": 3862, "text": "Stack vs Heap Memory Allocation" }, { "code": null, "e": 3932, "s": 3894, "text": "Difference between Process and Thread" }, { "code": null, "e": 3960, "s": 3932, "text": "Read JSON file using Python" }, { "code": null, "e": 3982, "s": 3960, "text": "Python map() function" }, { "code": null, "e": 4032, "s": 3982, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 4050, "s": 4032, "text": "Python Dictionary" } ]
How to convert a string into number in PHP?
31 Jul, 2021 Strings in PHP can be converted to numbers (float / int / double) very easily. In most use cases, it won’t be required since PHP does implicit type conversion. There are many methods to convert string into number in PHP some of them are discussed below: Method 1: Using number_format() Function. The number_format() function is used to convert string into a number. It returns the formatted number on success otherwise it gives E_WARNING on failure. Example: <?php $num = "1000.314"; // Convert string in number using // number_format(), functionecho number_format($num), "\n"; // Convert string in number using // number_format(), functionecho number_format($num, 2);?> 1,000 1,000.31 Method 2: Using type casting: Typecasting can directly convert a string into float, double or integer primitive type. This is the best way to convert a string into number without any function. Example: <?php // Number in string format$num = "1000.314"; // Type cast using intecho (int)$num, "\n"; // Type cast using floatecho (float)$num, "\n"; // Type cast using doubleecho (double)$num;?> 1000 1000.314 1000.314 Method 3: Using intval() and floatval() Function. The intval() and floatval() functions can also be used to convert the string into its corresponding integer and float values respectively. Example: <?php // Number in string format$num = "1000.314"; // intval() function to convert // string into integerecho intval($num), "\n"; // floatval() function to convert// string to floatecho floatval($num);?> 1000 1000.314 Method 4: By adding 0 or by performing mathematical operations. The string number can also be converted into an integer or float by adding 0 with the string. In PHP, performing mathematical operations, the string is converted to an integer or float implicitly. <?php // Number into string format$num = "1000.314"; // Performing mathematical operation // to implicitly type conversionecho $num + 0, "\n"; // Performing mathematical operation // to implicitly type conversionecho $num + 0.0, "\n"; // Performing mathematical operation // to implicitly type conversionecho $num + 0.1;?> 1000.314 1000.314 1000.414 PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples. Picked PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Jul, 2021" }, { "code": null, "e": 282, "s": 28, "text": "Strings in PHP can be converted to numbers (float / int / double) very easily. In most use cases, it won’t be required since PHP does implicit type conversion. There are many methods to convert string into number in PHP some of them are discussed below:" }, { "code": null, "e": 478, "s": 282, "text": "Method 1: Using number_format() Function. The number_format() function is used to convert string into a number. It returns the formatted number on success otherwise it gives E_WARNING on failure." }, { "code": null, "e": 487, "s": 478, "text": "Example:" }, { "code": "<?php $num = \"1000.314\"; // Convert string in number using // number_format(), functionecho number_format($num), \"\\n\"; // Convert string in number using // number_format(), functionecho number_format($num, 2);?>", "e": 702, "s": 487, "text": null }, { "code": null, "e": 718, "s": 702, "text": "1,000\n1,000.31\n" }, { "code": null, "e": 911, "s": 718, "text": "Method 2: Using type casting: Typecasting can directly convert a string into float, double or integer primitive type. This is the best way to convert a string into number without any function." }, { "code": null, "e": 920, "s": 911, "text": "Example:" }, { "code": "<?php // Number in string format$num = \"1000.314\"; // Type cast using intecho (int)$num, \"\\n\"; // Type cast using floatecho (float)$num, \"\\n\"; // Type cast using doubleecho (double)$num;?>", "e": 1113, "s": 920, "text": null }, { "code": null, "e": 1137, "s": 1113, "text": "1000\n1000.314\n1000.314\n" }, { "code": null, "e": 1326, "s": 1137, "text": "Method 3: Using intval() and floatval() Function. The intval() and floatval() functions can also be used to convert the string into its corresponding integer and float values respectively." }, { "code": null, "e": 1335, "s": 1326, "text": "Example:" }, { "code": "<?php // Number in string format$num = \"1000.314\"; // intval() function to convert // string into integerecho intval($num), \"\\n\"; // floatval() function to convert// string to floatecho floatval($num);?>", "e": 1542, "s": 1335, "text": null }, { "code": null, "e": 1557, "s": 1542, "text": "1000\n1000.314\n" }, { "code": null, "e": 1818, "s": 1557, "text": "Method 4: By adding 0 or by performing mathematical operations. The string number can also be converted into an integer or float by adding 0 with the string. In PHP, performing mathematical operations, the string is converted to an integer or float implicitly." }, { "code": "<?php // Number into string format$num = \"1000.314\"; // Performing mathematical operation // to implicitly type conversionecho $num + 0, \"\\n\"; // Performing mathematical operation // to implicitly type conversionecho $num + 0.0, \"\\n\"; // Performing mathematical operation // to implicitly type conversionecho $num + 0.1;?>", "e": 2149, "s": 1818, "text": null }, { "code": null, "e": 2177, "s": 2149, "text": "1000.314\n1000.314\n1000.414\n" }, { "code": null, "e": 2346, "s": 2177, "text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples." }, { "code": null, "e": 2353, "s": 2346, "text": "Picked" }, { "code": null, "e": 2357, "s": 2353, "text": "PHP" }, { "code": null, "e": 2374, "s": 2357, "text": "Web Technologies" }, { "code": null, "e": 2378, "s": 2374, "text": "PHP" } ]
Longest Increasing consecutive subsequence
08 Jun, 2022 Given N elements, write a program that prints the length of the longest increasing subsequence whose adjacent element difference is one. Examples: Input : a[] = {3, 10, 3, 11, 4, 5, 6, 7, 8, 12} Output : 6 Explanation: 3, 4, 5, 6, 7, 8 is the longest increasing subsequence whose adjacent element differs by one. Input : a[] = {6, 7, 8, 3, 4, 5, 9, 10} Output : 5 Explanation: 6, 7, 8, 9, 10 is the longest increasing subsequence Naive Approach: A normal approach will be to iterate for every element and find out the longest increasing subsequence. For any particular element, find the length of the subsequence starting from that element. Print the longest length of the subsequence thus formed. The time complexity of this approach will be O(n2). Dynamic Programming Approach: Let DP[i] store the length of the longest subsequence which ends with A[i]. For every A[i], if A[i]-1 is present in the array before i-th index, then A[i] will add to the increasing subsequence which has A[i]-1. Hence, DP[i] = DP[ index(A[i]-1) ] + 1. If A[i]-1 is not present in the array before i-th index, then DP[i]=1 since the A[i] element forms a subsequence which starts with A[i]. Hence, the relation for DP[i] is: If A[i]-1 is present before i-th index: DP[i] = DP[ index(A[i]-1) ] + 1 else: DP[i] = 1 Given below is the illustration of the above approach: C++ Java Python3 C# Javascript // CPP program to find length of the// longest increasing subsequence// whose adjacent element differ by 1#include <bits/stdc++.h>using namespace std; // function that returns the length of the// longest increasing subsequence// whose adjacent element differ by 1int longestSubsequence(int a[], int n){ // stores the index of elements unordered_map<int, int> mp; // stores the length of the longest // subsequence that ends with a[i] int dp[n]; memset(dp, 0, sizeof(dp)); int maximum = INT_MIN; // iterate for all element for (int i = 0; i < n; i++) { // if a[i]-1 is present before i-th index if (mp.find(a[i] - 1) != mp.end()) { // last index of a[i]-1 int lastIndex = mp[a[i] - 1] - 1; // relation dp[i] = 1 + dp[lastIndex]; } else dp[i] = 1; // stores the index as 1-index as we need to // check for occurrence, hence 0-th index // will not be possible to check mp[a[i]] = i + 1; // stores the longest length maximum = max(maximum, dp[i]); } return maximum;} // Driver Codeint main(){ int a[] = { 3, 10, 3, 11, 4, 5, 6, 7, 8, 12 }; int n = sizeof(a) / sizeof(a[0]); cout << longestSubsequence(a, n); return 0;} // Java program to find length of the// longest increasing subsequence// whose adjacent element differ by 1 import java.util.*;class lics { static int LongIncrConseqSubseq(int arr[], int n) { // create hashmap to save latest consequent // number as "key" and its length as "value" HashMap<Integer, Integer> map = new HashMap<>(); // put first element as "key" and its length as "value" map.put(arr[0], 1); for (int i = 1; i < n; i++) { // check if last consequent of arr[i] exist or not if (map.containsKey(arr[i] - 1)) { // put the updated consequent number // and increment its value(length) map.put(arr[i], map.get(arr[i] - 1) + 1); // remove the last consequent number map.remove(arr[i] - 1); } // if their is no last consequent of // arr[i] then put arr[i] else { map.put(arr[i], 1); } } return Collections.max(map.values()); } // driver code public static void main(String args[]) { // Take input from user Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int arr[] = new int[n]; for (int i = 0; i < n; i++) arr[i] = sc.nextInt(); System.out.println(LongIncrConseqSubseq(arr, n)); }}// This code is contributed by CrappyDoctor # python program to find length of the# longest increasing subsequence# whose adjacent element differ by 1 from collections import defaultdictimport sys # function that returns the length of the# longest increasing subsequence# whose adjacent element differ by 1 def longestSubsequence(a, n): mp = defaultdict(lambda:0) # stores the length of the longest # subsequence that ends with a[i] dp = [0 for i in range(n)] maximum = -sys.maxsize # iterate for all element for i in range(n): # if a[i]-1 is present before i-th index if a[i] - 1 in mp: # last index of a[i]-1 lastIndex = mp[a[i] - 1] - 1 # relation dp[i] = 1 + dp[lastIndex] else: dp[i] = 1 # stores the index as 1-index as we need to # check for occurrence, hence 0-th index # will not be possible to check mp[a[i]] = i + 1 # stores the longest length maximum = max(maximum, dp[i]) return maximum # Driver Codea = [3, 10, 3, 11, 4, 5, 6, 7, 8, 12]n = len(a)print(longestSubsequence(a, n)) # This code is contributed by Shrikant13 // C# program to find length of the// longest increasing subsequence// whose adjacent element differ by 1using System;using System.Collections.Generic;class GFG{ static int longIncrConseqSubseq(int []arr, int n){ // Create hashmap to save // latest consequent number // as "key" and its length // as "value" Dictionary<int, int> map = new Dictionary<int, int>(); // Put first element as "key" // and its length as "value" map.Add(arr[0], 1); for (int i = 1; i < n; i++) { // Check if last consequent // of arr[i] exist or not if (map.ContainsKey(arr[i] - 1)) { // put the updated consequent number // and increment its value(length) map.Add(arr[i], map[arr[i] - 1] + 1); // Remove the last consequent number map.Remove(arr[i] - 1); } // If their is no last consequent of // arr[i] then put arr[i] else { if(!map.ContainsKey(arr[i])) map.Add(arr[i], 1); } } int max = int.MinValue; foreach(KeyValuePair<int, int> entry in map) { if(entry.Value > max) { max = entry.Value; } } return max;} // Driver codepublic static void Main(String []args){ // Take input from user int []arr = {3, 10, 3, 11, 4, 5, 6, 7, 8, 12}; int n = arr.Length; Console.WriteLine(longIncrConseqSubseq(arr, n));}} // This code is contributed by gauravrajput1 <script> // JavaScript program to find length of the// longest increasing subsequence// whose adjacent element differ by 1 // function that returns the length of the// longest increasing subsequence// whose adjacent element differ by 1function longestSubsequence(a, n){ // stores the index of elements var mp = new Map(); // stores the length of the longest // subsequence that ends with a[i] var dp = Array(n).fill(0); var maximum = -1000000000; // iterate for all element for (var i = 0; i < n; i++) { // if a[i]-1 is present before i-th index if (mp.has(a[i] - 1)) { // last index of a[i]-1 var lastIndex = mp.get(a[i] - 1) - 1; // relation dp[i] = 1 + dp[lastIndex]; } else dp[i] = 1; // stores the index as 1-index as we need to // check for occurrence, hence 0-th index // will not be possible to check mp.set(a[i], i + 1); // stores the longest length maximum = Math.max(maximum, dp[i]); } return maximum;} // Driver Codevar a = [3, 10, 3, 11, 4, 5, 6, 7, 8, 12];var n = a.length;document.write( longestSubsequence(a, n)); </script> 6 Time Complexity: O(N), as we are using a loop to traverse N times. Auxiliary Space: O(N), as we are using extra space for dp and map m. shrikanth13 CrappyDoctor GauravRajput1 famously rohitsingh07052 cpp-unordered_map Arrays Dynamic Programming Hash Arrays Hash Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multidimensional Arrays in Java Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Introduction to Arrays K'th Smallest/Largest Element in Unsorted Array | Set 1 Subset Sum Problem | DP-25 Program for Fibonacci numbers 0-1 Knapsack Problem | DP-10 Longest Common Subsequence | DP-4 Subset Sum Problem | DP-25 Longest Palindromic Substring | Set 1
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Jun, 2022" }, { "code": null, "e": 202, "s": 54, "text": "Given N elements, write a program that prints the length of the longest increasing subsequence whose adjacent element difference is one. Examples: " }, { "code": null, "e": 486, "s": 202, "text": "Input : a[] = {3, 10, 3, 11, 4, 5, 6, 7, 8, 12} Output : 6 Explanation: 3, 4, 5, 6, 7, 8 is the longest increasing subsequence whose adjacent element differs by one. Input : a[] = {6, 7, 8, 3, 4, 5, 9, 10} Output : 5 Explanation: 6, 7, 8, 9, 10 is the longest increasing subsequence " }, { "code": null, "e": 1261, "s": 486, "text": "Naive Approach: A normal approach will be to iterate for every element and find out the longest increasing subsequence. For any particular element, find the length of the subsequence starting from that element. Print the longest length of the subsequence thus formed. The time complexity of this approach will be O(n2). Dynamic Programming Approach: Let DP[i] store the length of the longest subsequence which ends with A[i]. For every A[i], if A[i]-1 is present in the array before i-th index, then A[i] will add to the increasing subsequence which has A[i]-1. Hence, DP[i] = DP[ index(A[i]-1) ] + 1. If A[i]-1 is not present in the array before i-th index, then DP[i]=1 since the A[i] element forms a subsequence which starts with A[i]. Hence, the relation for DP[i] is: " }, { "code": null, "e": 1303, "s": 1261, "text": "If A[i]-1 is present before i-th index: " }, { "code": null, "e": 1335, "s": 1303, "text": "DP[i] = DP[ index(A[i]-1) ] + 1" }, { "code": null, "e": 1342, "s": 1335, "text": "else: " }, { "code": null, "e": 1352, "s": 1342, "text": "DP[i] = 1" }, { "code": null, "e": 1409, "s": 1352, "text": "Given below is the illustration of the above approach: " }, { "code": null, "e": 1413, "s": 1409, "text": "C++" }, { "code": null, "e": 1418, "s": 1413, "text": "Java" }, { "code": null, "e": 1426, "s": 1418, "text": "Python3" }, { "code": null, "e": 1429, "s": 1426, "text": "C#" }, { "code": null, "e": 1440, "s": 1429, "text": "Javascript" }, { "code": "// CPP program to find length of the// longest increasing subsequence// whose adjacent element differ by 1#include <bits/stdc++.h>using namespace std; // function that returns the length of the// longest increasing subsequence// whose adjacent element differ by 1int longestSubsequence(int a[], int n){ // stores the index of elements unordered_map<int, int> mp; // stores the length of the longest // subsequence that ends with a[i] int dp[n]; memset(dp, 0, sizeof(dp)); int maximum = INT_MIN; // iterate for all element for (int i = 0; i < n; i++) { // if a[i]-1 is present before i-th index if (mp.find(a[i] - 1) != mp.end()) { // last index of a[i]-1 int lastIndex = mp[a[i] - 1] - 1; // relation dp[i] = 1 + dp[lastIndex]; } else dp[i] = 1; // stores the index as 1-index as we need to // check for occurrence, hence 0-th index // will not be possible to check mp[a[i]] = i + 1; // stores the longest length maximum = max(maximum, dp[i]); } return maximum;} // Driver Codeint main(){ int a[] = { 3, 10, 3, 11, 4, 5, 6, 7, 8, 12 }; int n = sizeof(a) / sizeof(a[0]); cout << longestSubsequence(a, n); return 0;}", "e": 2734, "s": 1440, "text": null }, { "code": "// Java program to find length of the// longest increasing subsequence// whose adjacent element differ by 1 import java.util.*;class lics { static int LongIncrConseqSubseq(int arr[], int n) { // create hashmap to save latest consequent // number as \"key\" and its length as \"value\" HashMap<Integer, Integer> map = new HashMap<>(); // put first element as \"key\" and its length as \"value\" map.put(arr[0], 1); for (int i = 1; i < n; i++) { // check if last consequent of arr[i] exist or not if (map.containsKey(arr[i] - 1)) { // put the updated consequent number // and increment its value(length) map.put(arr[i], map.get(arr[i] - 1) + 1); // remove the last consequent number map.remove(arr[i] - 1); } // if their is no last consequent of // arr[i] then put arr[i] else { map.put(arr[i], 1); } } return Collections.max(map.values()); } // driver code public static void main(String args[]) { // Take input from user Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int arr[] = new int[n]; for (int i = 0; i < n; i++) arr[i] = sc.nextInt(); System.out.println(LongIncrConseqSubseq(arr, n)); }}// This code is contributed by CrappyDoctor", "e": 4211, "s": 2734, "text": null }, { "code": "# python program to find length of the# longest increasing subsequence# whose adjacent element differ by 1 from collections import defaultdictimport sys # function that returns the length of the# longest increasing subsequence# whose adjacent element differ by 1 def longestSubsequence(a, n): mp = defaultdict(lambda:0) # stores the length of the longest # subsequence that ends with a[i] dp = [0 for i in range(n)] maximum = -sys.maxsize # iterate for all element for i in range(n): # if a[i]-1 is present before i-th index if a[i] - 1 in mp: # last index of a[i]-1 lastIndex = mp[a[i] - 1] - 1 # relation dp[i] = 1 + dp[lastIndex] else: dp[i] = 1 # stores the index as 1-index as we need to # check for occurrence, hence 0-th index # will not be possible to check mp[a[i]] = i + 1 # stores the longest length maximum = max(maximum, dp[i]) return maximum # Driver Codea = [3, 10, 3, 11, 4, 5, 6, 7, 8, 12]n = len(a)print(longestSubsequence(a, n)) # This code is contributed by Shrikant13", "e": 5362, "s": 4211, "text": null }, { "code": "// C# program to find length of the// longest increasing subsequence// whose adjacent element differ by 1using System;using System.Collections.Generic;class GFG{ static int longIncrConseqSubseq(int []arr, int n){ // Create hashmap to save // latest consequent number // as \"key\" and its length // as \"value\" Dictionary<int, int> map = new Dictionary<int, int>(); // Put first element as \"key\" // and its length as \"value\" map.Add(arr[0], 1); for (int i = 1; i < n; i++) { // Check if last consequent // of arr[i] exist or not if (map.ContainsKey(arr[i] - 1)) { // put the updated consequent number // and increment its value(length) map.Add(arr[i], map[arr[i] - 1] + 1); // Remove the last consequent number map.Remove(arr[i] - 1); } // If their is no last consequent of // arr[i] then put arr[i] else { if(!map.ContainsKey(arr[i])) map.Add(arr[i], 1); } } int max = int.MinValue; foreach(KeyValuePair<int, int> entry in map) { if(entry.Value > max) { max = entry.Value; } } return max;} // Driver codepublic static void Main(String []args){ // Take input from user int []arr = {3, 10, 3, 11, 4, 5, 6, 7, 8, 12}; int n = arr.Length; Console.WriteLine(longIncrConseqSubseq(arr, n));}} // This code is contributed by gauravrajput1", "e": 6819, "s": 5362, "text": null }, { "code": "<script> // JavaScript program to find length of the// longest increasing subsequence// whose adjacent element differ by 1 // function that returns the length of the// longest increasing subsequence// whose adjacent element differ by 1function longestSubsequence(a, n){ // stores the index of elements var mp = new Map(); // stores the length of the longest // subsequence that ends with a[i] var dp = Array(n).fill(0); var maximum = -1000000000; // iterate for all element for (var i = 0; i < n; i++) { // if a[i]-1 is present before i-th index if (mp.has(a[i] - 1)) { // last index of a[i]-1 var lastIndex = mp.get(a[i] - 1) - 1; // relation dp[i] = 1 + dp[lastIndex]; } else dp[i] = 1; // stores the index as 1-index as we need to // check for occurrence, hence 0-th index // will not be possible to check mp.set(a[i], i + 1); // stores the longest length maximum = Math.max(maximum, dp[i]); } return maximum;} // Driver Codevar a = [3, 10, 3, 11, 4, 5, 6, 7, 8, 12];var n = a.length;document.write( longestSubsequence(a, n)); </script>", "e": 8023, "s": 6819, "text": null }, { "code": null, "e": 8025, "s": 8023, "text": "6" }, { "code": null, "e": 8094, "s": 8027, "text": "Time Complexity: O(N), as we are using a loop to traverse N times." }, { "code": null, "e": 8163, "s": 8094, "text": "Auxiliary Space: O(N), as we are using extra space for dp and map m." }, { "code": null, "e": 8175, "s": 8163, "text": "shrikanth13" }, { "code": null, "e": 8188, "s": 8175, "text": "CrappyDoctor" }, { "code": null, "e": 8202, "s": 8188, "text": "GauravRajput1" }, { "code": null, "e": 8211, "s": 8202, "text": "famously" }, { "code": null, "e": 8227, "s": 8211, "text": "rohitsingh07052" }, { "code": null, "e": 8245, "s": 8227, "text": "cpp-unordered_map" }, { "code": null, "e": 8252, "s": 8245, "text": "Arrays" }, { "code": null, "e": 8272, "s": 8252, "text": "Dynamic Programming" }, { "code": null, "e": 8277, "s": 8272, "text": "Hash" }, { "code": null, "e": 8284, "s": 8277, "text": "Arrays" }, { "code": null, "e": 8289, "s": 8284, "text": "Hash" }, { "code": null, "e": 8309, "s": 8289, "text": "Dynamic Programming" }, { "code": null, "e": 8407, "s": 8309, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8439, "s": 8407, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 8524, "s": 8439, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 8547, "s": 8524, "text": "Introduction to Arrays" }, { "code": null, "e": 8603, "s": 8547, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 8630, "s": 8603, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 8660, "s": 8630, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 8689, "s": 8660, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 8723, "s": 8689, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 8750, "s": 8723, "text": "Subset Sum Problem | DP-25" } ]
Internal Linkage and External Linkage in C
16 Jun, 2022 It is often quite hard to distinguish between scope and linkage, and the roles they play. This article focuses on scope and linkage, and how they are used in C language.Note: All C programs have been compiled on 64 bit GCC 4.9.2. Also, the terms “identifier” and “name” have been used interchangeably in this article. Definitions Scope : Scope of an identifier is the part of the program where the identifier may directly be accessible. In C, all identifiers are lexically (or statically) scoped. Linkage : Linkage describes how names can or can not refer to the same entity throughout the whole program or one single translation unit.The above sounds similar to Scope, but it is not so. To understand what the above means, let us dig deeper into the compilation process. Translation Unit : A translation unit is a file containing source code, header files and other dependencies. All of these sources are grouped together to form a single translation unit which can then be used by the compiler to produce one single executable object. It is important to link the sources together in a meaningful way. For example, the compiler should know that printf definition lies in stdio header file. In C and C++, a program that consists of multiple source code files is compiled one at a time. Until the compilation process, a variable can be described by it’s scope. It is only when the linking process starts, that linkage property comes into play. Thus, scope is a property handled by compiler, whereas linkage is a property handled by linker. The Linker links the resources together in the linking stage of compilation process. The Linker is a program that takes multiple machine code files as input, and produces an executable object code. It resolves symbols (i.e, fetches definition of symbols such as “+” etc..) and arranges objects in address space. Linkage is a property that describes how variables should be linked by the linker. Should a variable be available for another file to use? Should a variable be used only in the file declared? Both are decided by linkage.Linkage thus allows you to couple names together on a per file basis, scope determines visibility of those names.There are 2 types of linkage: Internal Linkage: An identifier implementing internal linkage is not accessible outside the translation unit it is declared in. Any identifier within the unit can access an identifier having internal linkage. It is implemented by the keyword static. An internally linked identifier is stored in initialized or uninitialized segment of RAM. (note: static also has a meaning in reference to scope, but that is not discussed here).Some Examples:Animals.cpp// C code to illustrate Internal Linkage#include <stdio.h> static int animals = 8;const int i = 5; int call_me(void){ printf("%d %d", i, animals);}The above code implements static linkage on identifier animals. Consider Feed.cpp is located in the same translation unit.Feed.cpp// C code to illustrate Internal Linkage#include <stdio.h> int main(){ call_me(); animals = 2; printf("%d", animals); return 0;}On compiling Animals.cpp first and then Feed.cpp, we getOutput : 5 8 2 Now, consider that Feed.cpp is located in a different translation unit. It will compile and run as above only if we use #include "Animals.cpp".Consider Wash.cpp located in a 3rd translation unit.Wash.cpp// C code to illustrate Internal Linkage#include <stdio.h>#include "animal.cpp" // note that animal is included. int main(){ call_me(); printf("\n having fun washing!"); animals = 10; printf("%d\n", animals); return 0;}On compiling, we get:Output : 5 8 having fun washing! 10 There are 3 translation units (Animals, Feed, Wash) which are using animals code.This leads us to conclude that each translation unit accesses it’s own copy of animals. That is why we have animals = 8 for Animals.cpp, animals = 2 for Feed.cpp and animals = 10 for Wash.cpp. A file. This behavior eats up memory and decreases performance.Another property of internal linkage is that it is only implemented when the variable has global scope, and all constants are by default internally linked.Usage : As we know, an internally linked variable is passed by copy. Thus, if a header file has a function fun1() and the source code in which it is included in also has fun1() but with a different definition, then the 2 functions will not clash with each other. Thus, we commonly use internal linkage to hide translation-unit-local helper functions from the global scope. For example, we might include a header file that contains a method to read input from the user, in a file that may describe another method to read input from the user. Both of these functions are independent of each other when linked.External Linkage: An identifier implementing external linkage is visible to every translation unit. Externally linked identifiers are shared between translation units and are considered to be located at the outermost level of the program. In practice, this means that you must define an identifier in a place which is visible to all, such that it has only one visible definition. It is the default linkage for globally scoped variables and functions. Thus, all instances of a particular identifier with external linkage refer to the same identifier in the program. The keyword extern implements external linkage.When we use the keyword extern, we tell the linker to look for the definition elsewhere. Thus, the declaration of an externally linked identifier does not take up any space. Extern identifiers are generally stored in initialized/uninitialized or text segment of RAM.Please do go through Understanding extern keyword in C before proceeding to the following examples.It is possible to use an extern variable in a local scope. This shall further outline the differences between linkage and scope. Consider the following code:// C code to illustrate External Linkage#include <stdio.h> void foo(){ int a; extern int b; // line 1} void bar(){ int c; c = b; // error} int main(){ foo(); bar();}Error: 'b' was not declared in this scope Explanation : The variable b has local scope in the function foo, even though it is an extern variable. Note that compilation takes place before linking; i.e scope is a concept that can be used only during compile phase. After the program is compiled there is no such concept as “scope of variable”.During compilation, scope of b is considered. It has local scope in foo(). When the compiler sees the extern declaration, it trusts that there is a definition of b somewhere and lets the linker handle the rest.However, the same compiler will go through the bar() function and try to find variable b. Since b has been declared extern, it has not been given memory yet by the compiler; it does not exist yet. The compiler will let the linker find the definition of b in the translation unit, and then the linker will assign b the value specified in definition. It is only then that b will exist and be assigned memory. However, since there is no declaration given at compile time within the scope of bar(), or even in global scope, the compiler complains with the error above.Given that it is the compiler’s job to make sure that all variables are used within their scopes, it complains when it sees b in bar(), when b has been declared in foo()‘s scope. The compiler will stop compiling and the program will not be passed to the linker.We can fix the program by declaring b as a global variable, by moving line 1 to before foo‘s definition.Let us look at another example// C code to illustrate External Linkage#include <stdio.h> int x = 10;int z = 5; int main(){ extern int y; // line 2 extern int z; printf("%d %d %d", x, y, z);} int y = 2;Output: 10 2 5 We can explain the output by observing behaviour of external linkage. We define 2 variables x and z in global scope. By default, both of them have external linkage. Now, when we declare y as extern, we tell the compiler that there exists a y with some definition within the same translation unit. Note that this is during the compile time phase, where the compiler trusts the extern keyword and compiles the rest of the program. The next line, extern int z has no effect on z, as z is externally linked by default when we declared it as a global variable outside the program. When we encounter printf line, the compiler sees 3 variables, all 3 having been declared before, and all 3 being used within their scopes (in the printf function). The program thus compiles successfully, even though the compiler does not know the definition of yThe next phase is linking. The linker goes through the compiled code and finds x and z first. As they are global variables, they are externally linked by default. The linker then updates value of x and z throughout the entire translation unit as 10 and 5. If there are any references to x and z in any other file in the translation unit, they are set to 10 and 5.Now, the linker comes to extern int y and tries to find any definition of y within the translation unit. It looks through every file in the translation unit to find definition of y. If it does not find any definition, a linker error will be thrown. In our program, we have given the definition outside main(), which has already been compiled for us. Thus, the linker finds that definition and updates y.This article is contributed by simran dhamija. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes arrow_drop_upSave Internal Linkage: An identifier implementing internal linkage is not accessible outside the translation unit it is declared in. Any identifier within the unit can access an identifier having internal linkage. It is implemented by the keyword static. An internally linked identifier is stored in initialized or uninitialized segment of RAM. (note: static also has a meaning in reference to scope, but that is not discussed here).Some Examples:Animals.cpp// C code to illustrate Internal Linkage#include <stdio.h> static int animals = 8;const int i = 5; int call_me(void){ printf("%d %d", i, animals);}The above code implements static linkage on identifier animals. Consider Feed.cpp is located in the same translation unit.Feed.cpp// C code to illustrate Internal Linkage#include <stdio.h> int main(){ call_me(); animals = 2; printf("%d", animals); return 0;}On compiling Animals.cpp first and then Feed.cpp, we getOutput : 5 8 2 Now, consider that Feed.cpp is located in a different translation unit. It will compile and run as above only if we use #include "Animals.cpp".Consider Wash.cpp located in a 3rd translation unit.Wash.cpp// C code to illustrate Internal Linkage#include <stdio.h>#include "animal.cpp" // note that animal is included. int main(){ call_me(); printf("\n having fun washing!"); animals = 10; printf("%d\n", animals); return 0;}On compiling, we get:Output : 5 8 having fun washing! 10 There are 3 translation units (Animals, Feed, Wash) which are using animals code.This leads us to conclude that each translation unit accesses it’s own copy of animals. That is why we have animals = 8 for Animals.cpp, animals = 2 for Feed.cpp and animals = 10 for Wash.cpp. A file. This behavior eats up memory and decreases performance.Another property of internal linkage is that it is only implemented when the variable has global scope, and all constants are by default internally linked.Usage : As we know, an internally linked variable is passed by copy. Thus, if a header file has a function fun1() and the source code in which it is included in also has fun1() but with a different definition, then the 2 functions will not clash with each other. Thus, we commonly use internal linkage to hide translation-unit-local helper functions from the global scope. For example, we might include a header file that contains a method to read input from the user, in a file that may describe another method to read input from the user. Both of these functions are independent of each other when linked. Animals.cpp // C code to illustrate Internal Linkage#include <stdio.h> static int animals = 8;const int i = 5; int call_me(void){ printf("%d %d", i, animals);} The above code implements static linkage on identifier animals. Consider Feed.cpp is located in the same translation unit. Feed.cpp // C code to illustrate Internal Linkage#include <stdio.h> int main(){ call_me(); animals = 2; printf("%d", animals); return 0;} On compiling Animals.cpp first and then Feed.cpp, we get Output : 5 8 2 Now, consider that Feed.cpp is located in a different translation unit. It will compile and run as above only if we use #include "Animals.cpp".Consider Wash.cpp located in a 3rd translation unit. Wash.cpp // C code to illustrate Internal Linkage#include <stdio.h>#include "animal.cpp" // note that animal is included. int main(){ call_me(); printf("\n having fun washing!"); animals = 10; printf("%d\n", animals); return 0;} On compiling, we get: Output : 5 8 having fun washing! 10 There are 3 translation units (Animals, Feed, Wash) which are using animals code.This leads us to conclude that each translation unit accesses it’s own copy of animals. That is why we have animals = 8 for Animals.cpp, animals = 2 for Feed.cpp and animals = 10 for Wash.cpp. A file. This behavior eats up memory and decreases performance. Another property of internal linkage is that it is only implemented when the variable has global scope, and all constants are by default internally linked. Usage : As we know, an internally linked variable is passed by copy. Thus, if a header file has a function fun1() and the source code in which it is included in also has fun1() but with a different definition, then the 2 functions will not clash with each other. Thus, we commonly use internal linkage to hide translation-unit-local helper functions from the global scope. For example, we might include a header file that contains a method to read input from the user, in a file that may describe another method to read input from the user. Both of these functions are independent of each other when linked. External Linkage: An identifier implementing external linkage is visible to every translation unit. Externally linked identifiers are shared between translation units and are considered to be located at the outermost level of the program. In practice, this means that you must define an identifier in a place which is visible to all, such that it has only one visible definition. It is the default linkage for globally scoped variables and functions. Thus, all instances of a particular identifier with external linkage refer to the same identifier in the program. The keyword extern implements external linkage.When we use the keyword extern, we tell the linker to look for the definition elsewhere. Thus, the declaration of an externally linked identifier does not take up any space. Extern identifiers are generally stored in initialized/uninitialized or text segment of RAM.Please do go through Understanding extern keyword in C before proceeding to the following examples.It is possible to use an extern variable in a local scope. This shall further outline the differences between linkage and scope. Consider the following code:// C code to illustrate External Linkage#include <stdio.h> void foo(){ int a; extern int b; // line 1} void bar(){ int c; c = b; // error} int main(){ foo(); bar();}Error: 'b' was not declared in this scope Explanation : The variable b has local scope in the function foo, even though it is an extern variable. Note that compilation takes place before linking; i.e scope is a concept that can be used only during compile phase. After the program is compiled there is no such concept as “scope of variable”.During compilation, scope of b is considered. It has local scope in foo(). When the compiler sees the extern declaration, it trusts that there is a definition of b somewhere and lets the linker handle the rest.However, the same compiler will go through the bar() function and try to find variable b. Since b has been declared extern, it has not been given memory yet by the compiler; it does not exist yet. The compiler will let the linker find the definition of b in the translation unit, and then the linker will assign b the value specified in definition. It is only then that b will exist and be assigned memory. However, since there is no declaration given at compile time within the scope of bar(), or even in global scope, the compiler complains with the error above.Given that it is the compiler’s job to make sure that all variables are used within their scopes, it complains when it sees b in bar(), when b has been declared in foo()‘s scope. The compiler will stop compiling and the program will not be passed to the linker.We can fix the program by declaring b as a global variable, by moving line 1 to before foo‘s definition.Let us look at another example// C code to illustrate External Linkage#include <stdio.h> int x = 10;int z = 5; int main(){ extern int y; // line 2 extern int z; printf("%d %d %d", x, y, z);} int y = 2;Output: 10 2 5 We can explain the output by observing behaviour of external linkage. We define 2 variables x and z in global scope. By default, both of them have external linkage. Now, when we declare y as extern, we tell the compiler that there exists a y with some definition within the same translation unit. Note that this is during the compile time phase, where the compiler trusts the extern keyword and compiles the rest of the program. The next line, extern int z has no effect on z, as z is externally linked by default when we declared it as a global variable outside the program. When we encounter printf line, the compiler sees 3 variables, all 3 having been declared before, and all 3 being used within their scopes (in the printf function). The program thus compiles successfully, even though the compiler does not know the definition of yThe next phase is linking. The linker goes through the compiled code and finds x and z first. As they are global variables, they are externally linked by default. The linker then updates value of x and z throughout the entire translation unit as 10 and 5. If there are any references to x and z in any other file in the translation unit, they are set to 10 and 5.Now, the linker comes to extern int y and tries to find any definition of y within the translation unit. It looks through every file in the translation unit to find definition of y. If it does not find any definition, a linker error will be thrown. In our program, we have given the definition outside main(), which has already been compiled for us. Thus, the linker finds that definition and updates y.This article is contributed by simran dhamija. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes arrow_drop_upSave When we use the keyword extern, we tell the linker to look for the definition elsewhere. Thus, the declaration of an externally linked identifier does not take up any space. Extern identifiers are generally stored in initialized/uninitialized or text segment of RAM. Please do go through Understanding extern keyword in C before proceeding to the following examples.It is possible to use an extern variable in a local scope. This shall further outline the differences between linkage and scope. Consider the following code: // C code to illustrate External Linkage#include <stdio.h> void foo(){ int a; extern int b; // line 1} void bar(){ int c; c = b; // error} int main(){ foo(); bar();} Error: 'b' was not declared in this scope Explanation : The variable b has local scope in the function foo, even though it is an extern variable. Note that compilation takes place before linking; i.e scope is a concept that can be used only during compile phase. After the program is compiled there is no such concept as “scope of variable”. During compilation, scope of b is considered. It has local scope in foo(). When the compiler sees the extern declaration, it trusts that there is a definition of b somewhere and lets the linker handle the rest. However, the same compiler will go through the bar() function and try to find variable b. Since b has been declared extern, it has not been given memory yet by the compiler; it does not exist yet. The compiler will let the linker find the definition of b in the translation unit, and then the linker will assign b the value specified in definition. It is only then that b will exist and be assigned memory. However, since there is no declaration given at compile time within the scope of bar(), or even in global scope, the compiler complains with the error above. Given that it is the compiler’s job to make sure that all variables are used within their scopes, it complains when it sees b in bar(), when b has been declared in foo()‘s scope. The compiler will stop compiling and the program will not be passed to the linker. We can fix the program by declaring b as a global variable, by moving line 1 to before foo‘s definition. Let us look at another example // C code to illustrate External Linkage#include <stdio.h> int x = 10;int z = 5; int main(){ extern int y; // line 2 extern int z; printf("%d %d %d", x, y, z);} int y = 2; Output: 10 2 5 We can explain the output by observing behaviour of external linkage. We define 2 variables x and z in global scope. By default, both of them have external linkage. Now, when we declare y as extern, we tell the compiler that there exists a y with some definition within the same translation unit. Note that this is during the compile time phase, where the compiler trusts the extern keyword and compiles the rest of the program. The next line, extern int z has no effect on z, as z is externally linked by default when we declared it as a global variable outside the program. When we encounter printf line, the compiler sees 3 variables, all 3 having been declared before, and all 3 being used within their scopes (in the printf function). The program thus compiles successfully, even though the compiler does not know the definition of y The next phase is linking. The linker goes through the compiled code and finds x and z first. As they are global variables, they are externally linked by default. The linker then updates value of x and z throughout the entire translation unit as 10 and 5. If there are any references to x and z in any other file in the translation unit, they are set to 10 and 5. Now, the linker comes to extern int y and tries to find any definition of y within the translation unit. It looks through every file in the translation unit to find definition of y. If it does not find any definition, a linker error will be thrown. In our program, we have given the definition outside main(), which has already been compiled for us. Thus, the linker finds that definition and updates y. This article is contributed by simran dhamija. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. BitsPlease sriparnxnw7 C-Variable Declaration and Scope C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Functions that cannot be overloaded in C++ Switch Statement in C/C++ Substring in C++ std::string class in C++ Different Methods to Reverse a String in C++ Structures in C Function Pointer in C Functions in C/C++ Enumeration (or enum) in C C Language Introduction
[ { "code": null, "e": 52, "s": 24, "text": "\n16 Jun, 2022" }, { "code": null, "e": 370, "s": 52, "text": "It is often quite hard to distinguish between scope and linkage, and the roles they play. This article focuses on scope and linkage, and how they are used in C language.Note: All C programs have been compiled on 64 bit GCC 4.9.2. Also, the terms “identifier” and “name” have been used interchangeably in this article." }, { "code": null, "e": 382, "s": 370, "text": "Definitions" }, { "code": null, "e": 549, "s": 382, "text": "Scope : Scope of an identifier is the part of the program where the identifier may directly be accessible. In C, all identifiers are lexically (or statically) scoped." }, { "code": null, "e": 824, "s": 549, "text": "Linkage : Linkage describes how names can or can not refer to the same entity throughout the whole program or one single translation unit.The above sounds similar to Scope, but it is not so. To understand what the above means, let us dig deeper into the compilation process." }, { "code": null, "e": 1243, "s": 824, "text": "Translation Unit : A translation unit is a file containing source code, header files and other dependencies. All of these sources are grouped together to form a single translation unit which can then be used by the compiler to produce one single executable object. It is important to link the sources together in a meaningful way. For example, the compiler should know that printf definition lies in stdio header file." }, { "code": null, "e": 1591, "s": 1243, "text": "In C and C++, a program that consists of multiple source code files is compiled one at a time. Until the compilation process, a variable can be described by it’s scope. It is only when the linking process starts, that linkage property comes into play. Thus, scope is a property handled by compiler, whereas linkage is a property handled by linker." }, { "code": null, "e": 1903, "s": 1591, "text": "The Linker links the resources together in the linking stage of compilation process. The Linker is a program that takes multiple machine code files as input, and produces an executable object code. It resolves symbols (i.e, fetches definition of symbols such as “+” etc..) and arranges objects in address space." }, { "code": null, "e": 2266, "s": 1903, "text": "Linkage is a property that describes how variables should be linked by the linker. Should a variable be available for another file to use? Should a variable be used only in the file declared? Both are decided by linkage.Linkage thus allows you to couple names together on a per file basis, scope determines visibility of those names.There are 2 types of linkage:" }, { "code": null, "e": 9898, "s": 2266, "text": "Internal Linkage: An identifier implementing internal linkage is not accessible outside the translation unit it is declared in. Any identifier within the unit can access an identifier having internal linkage. It is implemented by the keyword static. An internally linked identifier is stored in initialized or uninitialized segment of RAM. (note: static also has a meaning in reference to scope, but that is not discussed here).Some Examples:Animals.cpp// C code to illustrate Internal Linkage#include <stdio.h> static int animals = 8;const int i = 5; int call_me(void){ printf(\"%d %d\", i, animals);}The above code implements static linkage on identifier animals. Consider Feed.cpp is located in the same translation unit.Feed.cpp// C code to illustrate Internal Linkage#include <stdio.h> int main(){ call_me(); animals = 2; printf(\"%d\", animals); return 0;}On compiling Animals.cpp first and then Feed.cpp, we getOutput : 5 8 2\nNow, consider that Feed.cpp is located in a different translation unit. It will compile and run as above only if we use #include \"Animals.cpp\".Consider Wash.cpp located in a 3rd translation unit.Wash.cpp// C code to illustrate Internal Linkage#include <stdio.h>#include \"animal.cpp\" // note that animal is included. int main(){ call_me(); printf(\"\\n having fun washing!\"); animals = 10; printf(\"%d\\n\", animals); return 0;}On compiling, we get:Output : 5 8\nhaving fun washing!\n10\nThere are 3 translation units (Animals, Feed, Wash) which are using animals code.This leads us to conclude that each translation unit accesses it’s own copy of animals. That is why we have animals = 8 for Animals.cpp, animals = 2 for Feed.cpp and animals = 10 for Wash.cpp. A file. This behavior eats up memory and decreases performance.Another property of internal linkage is that it is only implemented when the variable has global scope, and all constants are by default internally linked.Usage : As we know, an internally linked variable is passed by copy. Thus, if a header file has a function fun1() and the source code in which it is included in also has fun1() but with a different definition, then the 2 functions will not clash with each other. Thus, we commonly use internal linkage to hide translation-unit-local helper functions from the global scope. For example, we might include a header file that contains a method to read input from the user, in a file that may describe another method to read input from the user. Both of these functions are independent of each other when linked.External Linkage: An identifier implementing external linkage is visible to every translation unit. Externally linked identifiers are shared between translation units and are considered to be located at the outermost level of the program. In practice, this means that you must define an identifier in a place which is visible to all, such that it has only one visible definition. It is the default linkage for globally scoped variables and functions. Thus, all instances of a particular identifier with external linkage refer to the same identifier in the program. The keyword extern implements external linkage.When we use the keyword extern, we tell the linker to look for the definition elsewhere. Thus, the declaration of an externally linked identifier does not take up any space. Extern identifiers are generally stored in initialized/uninitialized or text segment of RAM.Please do go through Understanding extern keyword in C before proceeding to the following examples.It is possible to use an extern variable in a local scope. This shall further outline the differences between linkage and scope. Consider the following code:// C code to illustrate External Linkage#include <stdio.h> void foo(){ int a; extern int b; // line 1} void bar(){ int c; c = b; // error} int main(){ foo(); bar();}Error: 'b' was not declared in this scope\nExplanation : The variable b has local scope in the function foo, even though it is an extern variable. Note that compilation takes place before linking; i.e scope is a concept that can be used only during compile phase. After the program is compiled there is no such concept as “scope of variable”.During compilation, scope of b is considered. It has local scope in foo(). When the compiler sees the extern declaration, it trusts that there is a definition of b somewhere and lets the linker handle the rest.However, the same compiler will go through the bar() function and try to find variable b. Since b has been declared extern, it has not been given memory yet by the compiler; it does not exist yet. The compiler will let the linker find the definition of b in the translation unit, and then the linker will assign b the value specified in definition. It is only then that b will exist and be assigned memory. However, since there is no declaration given at compile time within the scope of bar(), or even in global scope, the compiler complains with the error above.Given that it is the compiler’s job to make sure that all variables are used within their scopes, it complains when it sees b in bar(), when b has been declared in foo()‘s scope. The compiler will stop compiling and the program will not be passed to the linker.We can fix the program by declaring b as a global variable, by moving line 1 to before foo‘s definition.Let us look at another example// C code to illustrate External Linkage#include <stdio.h> int x = 10;int z = 5; int main(){ extern int y; // line 2 extern int z; printf(\"%d %d %d\", x, y, z);} int y = 2;Output: 10 2 5\nWe can explain the output by observing behaviour of external linkage. We define 2 variables x and z in global scope. By default, both of them have external linkage. Now, when we declare y as extern, we tell the compiler that there exists a y with some definition within the same translation unit. Note that this is during the compile time phase, where the compiler trusts the extern keyword and compiles the rest of the program. The next line, extern int z has no effect on z, as z is externally linked by default when we declared it as a global variable outside the program. When we encounter printf line, the compiler sees 3 variables, all 3 having been declared before, and all 3 being used within their scopes (in the printf function). The program thus compiles successfully, even though the compiler does not know the definition of yThe next phase is linking. The linker goes through the compiled code and finds x and z first. As they are global variables, they are externally linked by default. The linker then updates value of x and z throughout the entire translation unit as 10 and 5. If there are any references to x and z in any other file in the translation unit, they are set to 10 and 5.Now, the linker comes to extern int y and tries to find any definition of y within the translation unit. It looks through every file in the translation unit to find definition of y. If it does not find any definition, a linker error will be thrown. In our program, we have given the definition outside main(), which has already been compiled for us. Thus, the linker finds that definition and updates y.This article is contributed by simran dhamija. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 12440, "s": 9898, "text": "Internal Linkage: An identifier implementing internal linkage is not accessible outside the translation unit it is declared in. Any identifier within the unit can access an identifier having internal linkage. It is implemented by the keyword static. An internally linked identifier is stored in initialized or uninitialized segment of RAM. (note: static also has a meaning in reference to scope, but that is not discussed here).Some Examples:Animals.cpp// C code to illustrate Internal Linkage#include <stdio.h> static int animals = 8;const int i = 5; int call_me(void){ printf(\"%d %d\", i, animals);}The above code implements static linkage on identifier animals. Consider Feed.cpp is located in the same translation unit.Feed.cpp// C code to illustrate Internal Linkage#include <stdio.h> int main(){ call_me(); animals = 2; printf(\"%d\", animals); return 0;}On compiling Animals.cpp first and then Feed.cpp, we getOutput : 5 8 2\nNow, consider that Feed.cpp is located in a different translation unit. It will compile and run as above only if we use #include \"Animals.cpp\".Consider Wash.cpp located in a 3rd translation unit.Wash.cpp// C code to illustrate Internal Linkage#include <stdio.h>#include \"animal.cpp\" // note that animal is included. int main(){ call_me(); printf(\"\\n having fun washing!\"); animals = 10; printf(\"%d\\n\", animals); return 0;}On compiling, we get:Output : 5 8\nhaving fun washing!\n10\nThere are 3 translation units (Animals, Feed, Wash) which are using animals code.This leads us to conclude that each translation unit accesses it’s own copy of animals. That is why we have animals = 8 for Animals.cpp, animals = 2 for Feed.cpp and animals = 10 for Wash.cpp. A file. This behavior eats up memory and decreases performance.Another property of internal linkage is that it is only implemented when the variable has global scope, and all constants are by default internally linked.Usage : As we know, an internally linked variable is passed by copy. Thus, if a header file has a function fun1() and the source code in which it is included in also has fun1() but with a different definition, then the 2 functions will not clash with each other. Thus, we commonly use internal linkage to hide translation-unit-local helper functions from the global scope. For example, we might include a header file that contains a method to read input from the user, in a file that may describe another method to read input from the user. Both of these functions are independent of each other when linked." }, { "code": null, "e": 12452, "s": 12440, "text": "Animals.cpp" }, { "code": "// C code to illustrate Internal Linkage#include <stdio.h> static int animals = 8;const int i = 5; int call_me(void){ printf(\"%d %d\", i, animals);}", "e": 12605, "s": 12452, "text": null }, { "code": null, "e": 12728, "s": 12605, "text": "The above code implements static linkage on identifier animals. Consider Feed.cpp is located in the same translation unit." }, { "code": null, "e": 12737, "s": 12728, "text": "Feed.cpp" }, { "code": "// C code to illustrate Internal Linkage#include <stdio.h> int main(){ call_me(); animals = 2; printf(\"%d\", animals); return 0;}", "e": 12879, "s": 12737, "text": null }, { "code": null, "e": 12936, "s": 12879, "text": "On compiling Animals.cpp first and then Feed.cpp, we get" }, { "code": null, "e": 12952, "s": 12936, "text": "Output : 5 8 2\n" }, { "code": null, "e": 13148, "s": 12952, "text": "Now, consider that Feed.cpp is located in a different translation unit. It will compile and run as above only if we use #include \"Animals.cpp\".Consider Wash.cpp located in a 3rd translation unit." }, { "code": null, "e": 13157, "s": 13148, "text": "Wash.cpp" }, { "code": "// C code to illustrate Internal Linkage#include <stdio.h>#include \"animal.cpp\" // note that animal is included. int main(){ call_me(); printf(\"\\n having fun washing!\"); animals = 10; printf(\"%d\\n\", animals); return 0;}", "e": 13393, "s": 13157, "text": null }, { "code": null, "e": 13415, "s": 13393, "text": "On compiling, we get:" }, { "code": null, "e": 13452, "s": 13415, "text": "Output : 5 8\nhaving fun washing!\n10\n" }, { "code": null, "e": 13790, "s": 13452, "text": "There are 3 translation units (Animals, Feed, Wash) which are using animals code.This leads us to conclude that each translation unit accesses it’s own copy of animals. That is why we have animals = 8 for Animals.cpp, animals = 2 for Feed.cpp and animals = 10 for Wash.cpp. A file. This behavior eats up memory and decreases performance." }, { "code": null, "e": 13946, "s": 13790, "text": "Another property of internal linkage is that it is only implemented when the variable has global scope, and all constants are by default internally linked." }, { "code": null, "e": 14554, "s": 13946, "text": "Usage : As we know, an internally linked variable is passed by copy. Thus, if a header file has a function fun1() and the source code in which it is included in also has fun1() but with a different definition, then the 2 functions will not clash with each other. Thus, we commonly use internal linkage to hide translation-unit-local helper functions from the global scope. For example, we might include a header file that contains a method to read input from the user, in a file that may describe another method to read input from the user. Both of these functions are independent of each other when linked." }, { "code": null, "e": 19645, "s": 14554, "text": "External Linkage: An identifier implementing external linkage is visible to every translation unit. Externally linked identifiers are shared between translation units and are considered to be located at the outermost level of the program. In practice, this means that you must define an identifier in a place which is visible to all, such that it has only one visible definition. It is the default linkage for globally scoped variables and functions. Thus, all instances of a particular identifier with external linkage refer to the same identifier in the program. The keyword extern implements external linkage.When we use the keyword extern, we tell the linker to look for the definition elsewhere. Thus, the declaration of an externally linked identifier does not take up any space. Extern identifiers are generally stored in initialized/uninitialized or text segment of RAM.Please do go through Understanding extern keyword in C before proceeding to the following examples.It is possible to use an extern variable in a local scope. This shall further outline the differences between linkage and scope. Consider the following code:// C code to illustrate External Linkage#include <stdio.h> void foo(){ int a; extern int b; // line 1} void bar(){ int c; c = b; // error} int main(){ foo(); bar();}Error: 'b' was not declared in this scope\nExplanation : The variable b has local scope in the function foo, even though it is an extern variable. Note that compilation takes place before linking; i.e scope is a concept that can be used only during compile phase. After the program is compiled there is no such concept as “scope of variable”.During compilation, scope of b is considered. It has local scope in foo(). When the compiler sees the extern declaration, it trusts that there is a definition of b somewhere and lets the linker handle the rest.However, the same compiler will go through the bar() function and try to find variable b. Since b has been declared extern, it has not been given memory yet by the compiler; it does not exist yet. The compiler will let the linker find the definition of b in the translation unit, and then the linker will assign b the value specified in definition. It is only then that b will exist and be assigned memory. However, since there is no declaration given at compile time within the scope of bar(), or even in global scope, the compiler complains with the error above.Given that it is the compiler’s job to make sure that all variables are used within their scopes, it complains when it sees b in bar(), when b has been declared in foo()‘s scope. The compiler will stop compiling and the program will not be passed to the linker.We can fix the program by declaring b as a global variable, by moving line 1 to before foo‘s definition.Let us look at another example// C code to illustrate External Linkage#include <stdio.h> int x = 10;int z = 5; int main(){ extern int y; // line 2 extern int z; printf(\"%d %d %d\", x, y, z);} int y = 2;Output: 10 2 5\nWe can explain the output by observing behaviour of external linkage. We define 2 variables x and z in global scope. By default, both of them have external linkage. Now, when we declare y as extern, we tell the compiler that there exists a y with some definition within the same translation unit. Note that this is during the compile time phase, where the compiler trusts the extern keyword and compiles the rest of the program. The next line, extern int z has no effect on z, as z is externally linked by default when we declared it as a global variable outside the program. When we encounter printf line, the compiler sees 3 variables, all 3 having been declared before, and all 3 being used within their scopes (in the printf function). The program thus compiles successfully, even though the compiler does not know the definition of yThe next phase is linking. The linker goes through the compiled code and finds x and z first. As they are global variables, they are externally linked by default. The linker then updates value of x and z throughout the entire translation unit as 10 and 5. If there are any references to x and z in any other file in the translation unit, they are set to 10 and 5.Now, the linker comes to extern int y and tries to find any definition of y within the translation unit. It looks through every file in the translation unit to find definition of y. If it does not find any definition, a linker error will be thrown. In our program, we have given the definition outside main(), which has already been compiled for us. Thus, the linker finds that definition and updates y.This article is contributed by simran dhamija. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 19912, "s": 19645, "text": "When we use the keyword extern, we tell the linker to look for the definition elsewhere. Thus, the declaration of an externally linked identifier does not take up any space. Extern identifiers are generally stored in initialized/uninitialized or text segment of RAM." }, { "code": null, "e": 20169, "s": 19912, "text": "Please do go through Understanding extern keyword in C before proceeding to the following examples.It is possible to use an extern variable in a local scope. This shall further outline the differences between linkage and scope. Consider the following code:" }, { "code": "// C code to illustrate External Linkage#include <stdio.h> void foo(){ int a; extern int b; // line 1} void bar(){ int c; c = b; // error} int main(){ foo(); bar();}", "e": 20356, "s": 20169, "text": null }, { "code": null, "e": 20399, "s": 20356, "text": "Error: 'b' was not declared in this scope\n" }, { "code": null, "e": 20699, "s": 20399, "text": "Explanation : The variable b has local scope in the function foo, even though it is an extern variable. Note that compilation takes place before linking; i.e scope is a concept that can be used only during compile phase. After the program is compiled there is no such concept as “scope of variable”." }, { "code": null, "e": 20910, "s": 20699, "text": "During compilation, scope of b is considered. It has local scope in foo(). When the compiler sees the extern declaration, it trusts that there is a definition of b somewhere and lets the linker handle the rest." }, { "code": null, "e": 21475, "s": 20910, "text": "However, the same compiler will go through the bar() function and try to find variable b. Since b has been declared extern, it has not been given memory yet by the compiler; it does not exist yet. The compiler will let the linker find the definition of b in the translation unit, and then the linker will assign b the value specified in definition. It is only then that b will exist and be assigned memory. However, since there is no declaration given at compile time within the scope of bar(), or even in global scope, the compiler complains with the error above." }, { "code": null, "e": 21737, "s": 21475, "text": "Given that it is the compiler’s job to make sure that all variables are used within their scopes, it complains when it sees b in bar(), when b has been declared in foo()‘s scope. The compiler will stop compiling and the program will not be passed to the linker." }, { "code": null, "e": 21842, "s": 21737, "text": "We can fix the program by declaring b as a global variable, by moving line 1 to before foo‘s definition." }, { "code": null, "e": 21873, "s": 21842, "text": "Let us look at another example" }, { "code": "// C code to illustrate External Linkage#include <stdio.h> int x = 10;int z = 5; int main(){ extern int y; // line 2 extern int z; printf(\"%d %d %d\", x, y, z);} int y = 2;", "e": 22059, "s": 21873, "text": null }, { "code": null, "e": 22075, "s": 22059, "text": "Output: 10 2 5\n" }, { "code": null, "e": 22914, "s": 22075, "text": "We can explain the output by observing behaviour of external linkage. We define 2 variables x and z in global scope. By default, both of them have external linkage. Now, when we declare y as extern, we tell the compiler that there exists a y with some definition within the same translation unit. Note that this is during the compile time phase, where the compiler trusts the extern keyword and compiles the rest of the program. The next line, extern int z has no effect on z, as z is externally linked by default when we declared it as a global variable outside the program. When we encounter printf line, the compiler sees 3 variables, all 3 having been declared before, and all 3 being used within their scopes (in the printf function). The program thus compiles successfully, even though the compiler does not know the definition of y" }, { "code": null, "e": 23278, "s": 22914, "text": "The next phase is linking. The linker goes through the compiled code and finds x and z first. As they are global variables, they are externally linked by default. The linker then updates value of x and z throughout the entire translation unit as 10 and 5. If there are any references to x and z in any other file in the translation unit, they are set to 10 and 5." }, { "code": null, "e": 23682, "s": 23278, "text": "Now, the linker comes to extern int y and tries to find any definition of y within the translation unit. It looks through every file in the translation unit to find definition of y. If it does not find any definition, a linker error will be thrown. In our program, we have given the definition outside main(), which has already been compiled for us. Thus, the linker finds that definition and updates y." }, { "code": null, "e": 23980, "s": 23682, "text": "This article is contributed by simran dhamija. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 24105, "s": 23980, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 24116, "s": 24105, "text": "BitsPlease" }, { "code": null, "e": 24128, "s": 24116, "text": "sriparnxnw7" }, { "code": null, "e": 24161, "s": 24128, "text": "C-Variable Declaration and Scope" }, { "code": null, "e": 24172, "s": 24161, "text": "C Language" }, { "code": null, "e": 24270, "s": 24172, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24313, "s": 24270, "text": "Functions that cannot be overloaded in C++" }, { "code": null, "e": 24339, "s": 24313, "text": "Switch Statement in C/C++" }, { "code": null, "e": 24356, "s": 24339, "text": "Substring in C++" }, { "code": null, "e": 24381, "s": 24356, "text": "std::string class in C++" }, { "code": null, "e": 24426, "s": 24381, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 24442, "s": 24426, "text": "Structures in C" }, { "code": null, "e": 24464, "s": 24442, "text": "Function Pointer in C" }, { "code": null, "e": 24483, "s": 24464, "text": "Functions in C/C++" }, { "code": null, "e": 24510, "s": 24483, "text": "Enumeration (or enum) in C" } ]
RTRIM() Function in MySQL
06 Oct, 2020 RTRIM() :It is the function in MySQL that is used to remove trailing spaces from a string. Syntax : RTRIM(str) Parameter :RTRIM() function accepts one parameter as mentioned above and described below. str –The string from which we want to remove trailing spaces. Returns :It returns a string after truncating all trailing spaces. Example-1 :Removing all the trailing spaces of a given string using RTRIM Function. SELECT RTRIM ('geeksforgeeks') AS RightTrimmedString; Output : +----------------------+--------------------+ | geeksforgeeks | RightTrimmedString | +----------------------+--------------------+ | geeksforgeeks | geeksforgeeks | +----------------------+--------------------+ Example-2 :Removing all the trailing spaces of a given string using RTRIM Function. SELECT 'MySQL' AS String, RTRIM ('MySQL') AS Tstring; Output : +----------------------+---------+ | String | Tstring | +----------------------+---------+ | MySQL | MySQL | +----------------------+---------+ Example-3 :RTRIM Function can also be used to remove all the trailing spaces of column data. To demonstrate create a table named Student. CREATE TABLE Student ( Student_id INT AUTO_INCREMENT, Student_name VARCHAR(100) NOT NULL, Student_Class VARCHAR(20) NOT NULL, PRIMARY KEY(Student_id ) ); Inserting some data to the Student table : INSERT INTO Student (Student_name, Student_Class ) VALUES ('Ananya Majumdar ', 'IX'), ('Anushka Samanta ', 'X' ), ('Aniket Sharma ', 'XI' ), ('Anik Das ', 'X' ), ('Riya Jain ', 'IX' ), ('Tapan Samanta ', 'X' ), ('Deepak Sharma ', 'X' ), ('Ankana Jana ', 'XII'), ('Shreya Ghosh ', 'X') ; So, the Student Table is as follows. mysql> select * from Student; Output : +------------+----------------------+---------------+ | Student_id | Student_name | Student_Class | +------------+----------------------+---------------+ | 1 | Ananya Majumdar | IX | | 2 | Anushka Samanta | X | | 3 | Aniket Sharma | XI | | 4 | Anik Das | X | | 5 | Riya Jain | IX | | 6 | Tapan Samanta | X | | 7 | Deepak Sharma | X | | 8 | Ankana Jana | XII | | 9 | Shreya Ghosh | X | +------------+----------------------+---------------+ Now, we are going to remove all trailing spaces from the Student_name column. SELECT Student_id, Student_name, RTRIM( Student_name) AS TrimmedSname FROM Student ; Output : +------------+----------------------+-----------------+ | Student_id | Student_name | TrimmedSname | +------------+----------------------+-----------------+ | 1 | Ananya Majumdar | Ananya Majumdar | | 2 | Anushka Samanta | Anushka Samanta | | 3 | Aniket Sharma | Aniket Sharma | | 4 | Anik Das | Anik Das | | 5 | Riya Jain | Riya Jain | | 6 | Tapan Samanta | Tapan Samanta | | 7 | Deepak Sharma | Deepak Sharma | | 8 | Ankana Jana | Ankana Jana | | 9 | Shreya Ghosh | Shreya Ghosh | +------------+----------------------+-----------------+ DBMS-SQL mysql SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? Window functions in SQL What is Temporary Table in SQL? SQL using Python SQL | Sub queries in From Clause SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter RANK() Function in SQL Server SQL Query to Convert VARCHAR to INT SQL Query to Compare Two Dates SQL | DROP, TRUNCATE
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Oct, 2020" }, { "code": null, "e": 119, "s": 28, "text": "RTRIM() :It is the function in MySQL that is used to remove trailing spaces from a string." }, { "code": null, "e": 128, "s": 119, "text": "Syntax :" }, { "code": null, "e": 139, "s": 128, "text": "RTRIM(str)" }, { "code": null, "e": 229, "s": 139, "text": "Parameter :RTRIM() function accepts one parameter as mentioned above and described below." }, { "code": null, "e": 291, "s": 229, "text": "str –The string from which we want to remove trailing spaces." }, { "code": null, "e": 358, "s": 291, "text": "Returns :It returns a string after truncating all trailing spaces." }, { "code": null, "e": 442, "s": 358, "text": "Example-1 :Removing all the trailing spaces of a given string using RTRIM Function." }, { "code": null, "e": 500, "s": 442, "text": "SELECT RTRIM ('geeksforgeeks') \nAS RightTrimmedString; \n" }, { "code": null, "e": 509, "s": 500, "text": "Output :" }, { "code": null, "e": 740, "s": 509, "text": "+----------------------+--------------------+\n| geeksforgeeks | RightTrimmedString |\n+----------------------+--------------------+\n| geeksforgeeks | geeksforgeeks |\n+----------------------+--------------------+\n" }, { "code": null, "e": 824, "s": 740, "text": "Example-2 :Removing all the trailing spaces of a given string using RTRIM Function." }, { "code": null, "e": 880, "s": 824, "text": "SELECT 'MySQL' AS String, RTRIM ('MySQL') \nAS Tstring;\n" }, { "code": null, "e": 889, "s": 880, "text": "Output :" }, { "code": null, "e": 1065, "s": 889, "text": "+----------------------+---------+\n| String | Tstring |\n+----------------------+---------+\n| MySQL | MySQL |\n+----------------------+---------+\n" }, { "code": null, "e": 1203, "s": 1065, "text": "Example-3 :RTRIM Function can also be used to remove all the trailing spaces of column data. To demonstrate create a table named Student." }, { "code": null, "e": 1369, "s": 1203, "text": "CREATE TABLE Student\n(\n Student_id INT AUTO_INCREMENT, \n Student_name VARCHAR(100) NOT NULL,\n Student_Class VARCHAR(20) NOT NULL,\n PRIMARY KEY(Student_id )\n\n);\n" }, { "code": null, "e": 1412, "s": 1369, "text": "Inserting some data to the Student table :" }, { "code": null, "e": 1748, "s": 1412, "text": "INSERT INTO Student\n(Student_name, Student_Class )\nVALUES\n ('Ananya Majumdar ', 'IX'),\n ('Anushka Samanta ', 'X' ),\n ('Aniket Sharma ', 'XI' ),\n ('Anik Das ', 'X' ),\n ('Riya Jain ', 'IX' ),\n ('Tapan Samanta ', 'X' ),\n ('Deepak Sharma ', 'X' ),\n ('Ankana Jana ', 'XII'),\n ('Shreya Ghosh ', 'X') ;\n" }, { "code": null, "e": 1785, "s": 1748, "text": "So, the Student Table is as follows." }, { "code": null, "e": 1816, "s": 1785, "text": "mysql> select * from Student;\n" }, { "code": null, "e": 1825, "s": 1816, "text": "Output :" }, { "code": null, "e": 2528, "s": 1825, "text": "+------------+----------------------+---------------+\n| Student_id | Student_name | Student_Class |\n+------------+----------------------+---------------+\n| 1 | Ananya Majumdar | IX |\n| 2 | Anushka Samanta | X |\n| 3 | Aniket Sharma | XI |\n| 4 | Anik Das | X |\n| 5 | Riya Jain | IX |\n| 6 | Tapan Samanta | X |\n| 7 | Deepak Sharma | X |\n| 8 | Ankana Jana | XII |\n| 9 | Shreya Ghosh | X |\n+------------+----------------------+---------------+\n" }, { "code": null, "e": 2606, "s": 2528, "text": "Now, we are going to remove all trailing spaces from the Student_name column." }, { "code": null, "e": 2708, "s": 2606, "text": " SELECT \n Student_id, Student_name,\n RTRIM( Student_name) AS TrimmedSname \n FROM Student ; \n" }, { "code": null, "e": 2717, "s": 2708, "text": "Output :" }, { "code": null, "e": 3446, "s": 2717, "text": "+------------+----------------------+-----------------+\n| Student_id | Student_name | TrimmedSname |\n+------------+----------------------+-----------------+\n| 1 | Ananya Majumdar | Ananya Majumdar |\n| 2 | Anushka Samanta | Anushka Samanta |\n| 3 | Aniket Sharma | Aniket Sharma |\n| 4 | Anik Das | Anik Das |\n| 5 | Riya Jain | Riya Jain |\n| 6 | Tapan Samanta | Tapan Samanta |\n| 7 | Deepak Sharma | Deepak Sharma |\n| 8 | Ankana Jana | Ankana Jana |\n| 9 | Shreya Ghosh | Shreya Ghosh |\n+------------+----------------------+-----------------+\n" }, { "code": null, "e": 3455, "s": 3446, "text": "DBMS-SQL" }, { "code": null, "e": 3461, "s": 3455, "text": "mysql" }, { "code": null, "e": 3465, "s": 3461, "text": "SQL" }, { "code": null, "e": 3469, "s": 3465, "text": "SQL" }, { "code": null, "e": 3567, "s": 3469, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3633, "s": 3567, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 3657, "s": 3633, "text": "Window functions in SQL" }, { "code": null, "e": 3689, "s": 3657, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 3706, "s": 3689, "text": "SQL using Python" }, { "code": null, "e": 3739, "s": 3706, "text": "SQL | Sub queries in From Clause" }, { "code": null, "e": 3817, "s": 3739, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 3847, "s": 3817, "text": "RANK() Function in SQL Server" }, { "code": null, "e": 3883, "s": 3847, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 3914, "s": 3883, "text": "SQL Query to Compare Two Dates" } ]
ConcurrentMap Interface in java
17 Sep, 2020 ConcurrentMap is an interface and it is a member of the Java Collections Framework, which is introduced in JDK 1.5 represents a Map that is capable of handling concurrent access to it without affecting the consistency of entries in a map. ConcurrentMap interface present in java.util.concurrent package. It provides some extra methods apart from what it inherits from the SuperInterface i.e. java.util.Map. It has inherited the Nested Interface Map.Entry<K, V>. HashMap operations are not synchronized, while Hashtable provides synchronization. Though Hashtable is a thread-safe, it is not very efficient. To solve this issue, the Java Collections Framework introduced ConcurrentMap in Java 1.5. The Hierarchy of ConcurrentMap Declaration: public interface ConcurrentMap<K,V> extends Map<K,V> Here, K is the type of key Object and V is the type of value Object. It extends the Map interface in Java. ConcurrentNavigableMap<K,V> is the SubInterface. ConcurrentMap is implemented by ConcurrentHashMap, ConcurrentSkipListMap classes. ConcurrentMap is known as a synchronized Map. Since it belongs to java.util.concurrent package, we must import is using import java.util.concurrent.ConcurrentMap or import java.util.concurrent.* The ConcurrentMap has two implementing classes which are ConcurrentSkipListMap and ConcurrentHashMap. The ConcurrentSkipListMap is a scalable implementation of the ConcurrentNavigableMap interface which extends ConcurrentMap interface. The keys in ConcurrentSkipListMap are sorted by natural order or by using a Comparator at the time of construction of the object. The ConcurrentSkipListMap has the expected time cost of log(n) for insertion, deletion, and searching operations. It is a thread-safe class, therefore, all basic operations can be accomplished concurrently. Syntax: // ConcurrentMap implementation by ConcurrentHashMap CocurrentMap<K, V> numbers = new ConcurrentHashMap<K, V>(); // ConcurrentMap implementation by ConcurrentSkipListMap ConcurrentMap< ? , ? > objectName = new ConcurrentSkipListMap< ? , ? >(); Example: Java // Java Program to illustrate methods// of ConcurrentMap interfaceimport java.util.concurrent.*; class ConcurrentMapDemo { public static void main(String[] args) { // Since ConcurrentMap is an interface, // we create instance using ConcurrentHashMap ConcurrentMap<Integer, String> m = new ConcurrentHashMap<Integer, String>(); m.put(100, "Geeks"); m.put(101, "For"); m.put(102, "Geeks"); // Here we cant add Hello because 101 key // is already present m.putIfAbsent(101, "Hello"); // We can remove entry because 101 key // is associated with For value m.remove(101, "For"); // Now we can add Hello m.putIfAbsent(101, "Hello"); // We can replace Hello with For m.replace(101, "Hello", "For"); System.out.println("Map contents : " + m); }} Map contents : {100=Geeks, 101=For, 102=Geeks} 1. Add Elements The put() method of ConcurrentSkipListMap is an in-built function in Java which associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced. Java // Java Program to demonstrate adding// elements import java.util.concurrent.*; class AddingElementsExample { public static void main(String[] args) { // Instantiate an object // Since ConcurrentMap // is an interface so We use // ConcurrentSkipListMap ConcurrentMap<Integer, Integer> mpp = new ConcurrentSkipListMap<Integer, Integer>(); // Adding elements to this map // using put() method for (int i = 1; i <= 5; i++) mpp.put(i, i); // Print map to the console System.out.println("After put(): " + mpp); }} After put(): {1=1, 2=2, 3=3, 4=4, 5=5} 2. Remove Elements The remove() method of ConcurrentSkipListMap is an in-built function in Java which removes the mapping for the specified key from this map. The method returns null if there is no mapping for that particular key. After this method is performed the size of the map is reduced. Java // Java Program to demonstrate removing// elements import java.util.concurrent.*; class RemovingElementsExample { public static void main(String[] args) { // Instantiate an object // Since ConcurrentMap // is an interface so We use // ConcurrentSkipListMap ConcurrentMap<Integer, Integer> mpp = new ConcurrentSkipListMap<Integer, Integer>(); // Adding elements to this map // using put method for (int i = 1; i <= 5; i++) mpp.put(i, i); // remove() mapping associated // with key 1 mpp.remove(1); System.out.println("After remove(): " + mpp); }} After remove(): {2=2, 3=3, 4=4, 5=5} 3. Accessing the Elements We can access the elements of a ConcurrentSkipListMap using the get() method, the example of this is given below. Java // Java Program to demonstrate accessing// elements import java.util.concurrent.*; class AccessingElementsExample { public static void main(String[] args) { // Instantiate an object // Since ConcurrentMap // is an interface so We use // ConcurrentSkipListMap ConcurrentMap<Integer, String> chm = new ConcurrentSkipListMap<Integer, String>(); // insert mappings using put method chm.put(100, "Geeks"); chm.put(101, "for"); chm.put(102, "Geeks"); chm.put(103, "Contribute"); // Displaying the HashMap System.out.println("The Mappings are: "); System.out.println(chm); // Display the value of 100 System.out.println("The Value associated to " + "100 is : " + chm.get(100)); // Getting the value of 103 System.out.println("The Value associated to " + "103 is : " + chm.get(103)); }} The Mappings are: {100=Geeks, 101=for, 102=Geeks, 103=Contribute} The Value associated to 100 is : Geeks The Value associated to 103 is : Contribute 4. Traversing We can use the Iterator interface to traverse over any structure of the Collection Framework. Since Iterators work with one type of data we use Entry< ? , ? > to resolve the two separate types into a compatible format. Then using the next() method we print the elements of the ConcurrentSkipListMap. Java import java.util.concurrent.*;import java.util.*; public class TraversingExample { public static void main(String[] args) { // Instantiate an object // Since ConcurrentMap // is an interface so We use // ConcurrentSkipListMap ConcurrentMap<Integer, String> chmap = new ConcurrentSkipListMap<Integer, String>(); // Add elements using put() chmap.put(8, "Third"); chmap.put(6, "Second"); chmap.put(3, "First"); chmap.put(11, "Fourth"); // Create an Iterator over the // ConcurrentSkipListMap Iterator<ConcurrentSkipListMap .Entry<Integer, String> > itr = chmap.entrySet().iterator(); // The hasNext() method is used to check if there is // a next element The next() method is used to // retrieve the next element while (itr.hasNext()) { ConcurrentSkipListMap .Entry<Integer, String> entry = itr.next(); System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); } }} Key = 3, Value = First Key = 6, Value = Second Key = 8, Value = Third Key = 11, Value = Fourth K – The type of the keys in the map. V – The type of values mapped in the map. METHOD DESCRIPTION compute​(K key, BiFunction<? super K,? super V,? extends V> remappingFunction) METHOD DESCRIPTION Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/ConcurrentMap.html Ganeshchowdharysadanala Java-Collections Java-HashMap Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n17 Sep, 2020" }, { "code": null, "e": 516, "s": 53, "text": "ConcurrentMap is an interface and it is a member of the Java Collections Framework, which is introduced in JDK 1.5 represents a Map that is capable of handling concurrent access to it without affecting the consistency of entries in a map. ConcurrentMap interface present in java.util.concurrent package. It provides some extra methods apart from what it inherits from the SuperInterface i.e. java.util.Map. It has inherited the Nested Interface Map.Entry<K, V>. " }, { "code": null, "e": 750, "s": 516, "text": "HashMap operations are not synchronized, while Hashtable provides synchronization. Though Hashtable is a thread-safe, it is not very efficient. To solve this issue, the Java Collections Framework introduced ConcurrentMap in Java 1.5." }, { "code": null, "e": 782, "s": 750, "text": "The Hierarchy of ConcurrentMap " }, { "code": null, "e": 795, "s": 782, "text": "Declaration:" }, { "code": null, "e": 849, "s": 795, "text": "public interface ConcurrentMap<K,V> extends Map<K,V>\n" }, { "code": null, "e": 918, "s": 849, "text": "Here, K is the type of key Object and V is the type of value Object." }, { "code": null, "e": 956, "s": 918, "text": "It extends the Map interface in Java." }, { "code": null, "e": 1005, "s": 956, "text": "ConcurrentNavigableMap<K,V> is the SubInterface." }, { "code": null, "e": 1087, "s": 1005, "text": "ConcurrentMap is implemented by ConcurrentHashMap, ConcurrentSkipListMap classes." }, { "code": null, "e": 1133, "s": 1087, "text": "ConcurrentMap is known as a synchronized Map." }, { "code": null, "e": 1207, "s": 1133, "text": "Since it belongs to java.util.concurrent package, we must import is using" }, { "code": null, "e": 1299, "s": 1207, "text": "import java.util.concurrent.ConcurrentMap\n or\nimport java.util.concurrent.*\n" }, { "code": null, "e": 1872, "s": 1299, "text": "The ConcurrentMap has two implementing classes which are ConcurrentSkipListMap and ConcurrentHashMap. The ConcurrentSkipListMap is a scalable implementation of the ConcurrentNavigableMap interface which extends ConcurrentMap interface. The keys in ConcurrentSkipListMap are sorted by natural order or by using a Comparator at the time of construction of the object. The ConcurrentSkipListMap has the expected time cost of log(n) for insertion, deletion, and searching operations. It is a thread-safe class, therefore, all basic operations can be accomplished concurrently." }, { "code": null, "e": 1880, "s": 1872, "text": "Syntax:" }, { "code": null, "e": 2126, "s": 1880, "text": "// ConcurrentMap implementation by ConcurrentHashMap\nCocurrentMap<K, V> numbers = new ConcurrentHashMap<K, V>();\n\n// ConcurrentMap implementation by ConcurrentSkipListMap\nConcurrentMap< ? , ? > objectName = new ConcurrentSkipListMap< ? , ? >();\n" }, { "code": null, "e": 2136, "s": 2126, "text": "Example: " }, { "code": null, "e": 2141, "s": 2136, "text": "Java" }, { "code": "// Java Program to illustrate methods// of ConcurrentMap interfaceimport java.util.concurrent.*; class ConcurrentMapDemo { public static void main(String[] args) { // Since ConcurrentMap is an interface, // we create instance using ConcurrentHashMap ConcurrentMap<Integer, String> m = new ConcurrentHashMap<Integer, String>(); m.put(100, \"Geeks\"); m.put(101, \"For\"); m.put(102, \"Geeks\"); // Here we cant add Hello because 101 key // is already present m.putIfAbsent(101, \"Hello\"); // We can remove entry because 101 key // is associated with For value m.remove(101, \"For\"); // Now we can add Hello m.putIfAbsent(101, \"Hello\"); // We can replace Hello with For m.replace(101, \"Hello\", \"For\"); System.out.println(\"Map contents : \" + m); }}", "e": 3018, "s": 2141, "text": null }, { "code": null, "e": 3065, "s": 3018, "text": "Map contents : {100=Geeks, 101=For, 102=Geeks}" }, { "code": null, "e": 3084, "s": 3068, "text": "1. Add Elements" }, { "code": null, "e": 3313, "s": 3084, "text": "The put() method of ConcurrentSkipListMap is an in-built function in Java which associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced." }, { "code": null, "e": 3318, "s": 3313, "text": "Java" }, { "code": "// Java Program to demonstrate adding// elements import java.util.concurrent.*; class AddingElementsExample { public static void main(String[] args) { // Instantiate an object // Since ConcurrentMap // is an interface so We use // ConcurrentSkipListMap ConcurrentMap<Integer, Integer> mpp = new ConcurrentSkipListMap<Integer, Integer>(); // Adding elements to this map // using put() method for (int i = 1; i <= 5; i++) mpp.put(i, i); // Print map to the console System.out.println(\"After put(): \" + mpp); }}", "e": 3925, "s": 3318, "text": null }, { "code": null, "e": 3964, "s": 3925, "text": "After put(): {1=1, 2=2, 3=3, 4=4, 5=5}" }, { "code": null, "e": 3983, "s": 3964, "text": "2. Remove Elements" }, { "code": null, "e": 4258, "s": 3983, "text": "The remove() method of ConcurrentSkipListMap is an in-built function in Java which removes the mapping for the specified key from this map. The method returns null if there is no mapping for that particular key. After this method is performed the size of the map is reduced." }, { "code": null, "e": 4263, "s": 4258, "text": "Java" }, { "code": "// Java Program to demonstrate removing// elements import java.util.concurrent.*; class RemovingElementsExample { public static void main(String[] args) { // Instantiate an object // Since ConcurrentMap // is an interface so We use // ConcurrentSkipListMap ConcurrentMap<Integer, Integer> mpp = new ConcurrentSkipListMap<Integer, Integer>(); // Adding elements to this map // using put method for (int i = 1; i <= 5; i++) mpp.put(i, i); // remove() mapping associated // with key 1 mpp.remove(1); System.out.println(\"After remove(): \" + mpp); }}", "e": 4921, "s": 4263, "text": null }, { "code": null, "e": 4958, "s": 4921, "text": "After remove(): {2=2, 3=3, 4=4, 5=5}" }, { "code": null, "e": 4984, "s": 4958, "text": "3. Accessing the Elements" }, { "code": null, "e": 5098, "s": 4984, "text": "We can access the elements of a ConcurrentSkipListMap using the get() method, the example of this is given below." }, { "code": null, "e": 5103, "s": 5098, "text": "Java" }, { "code": "// Java Program to demonstrate accessing// elements import java.util.concurrent.*; class AccessingElementsExample { public static void main(String[] args) { // Instantiate an object // Since ConcurrentMap // is an interface so We use // ConcurrentSkipListMap ConcurrentMap<Integer, String> chm = new ConcurrentSkipListMap<Integer, String>(); // insert mappings using put method chm.put(100, \"Geeks\"); chm.put(101, \"for\"); chm.put(102, \"Geeks\"); chm.put(103, \"Contribute\"); // Displaying the HashMap System.out.println(\"The Mappings are: \"); System.out.println(chm); // Display the value of 100 System.out.println(\"The Value associated to \" + \"100 is : \" + chm.get(100)); // Getting the value of 103 System.out.println(\"The Value associated to \" + \"103 is : \" + chm.get(103)); }}", "e": 6076, "s": 5103, "text": null }, { "code": null, "e": 6226, "s": 6076, "text": "The Mappings are: \n{100=Geeks, 101=for, 102=Geeks, 103=Contribute}\nThe Value associated to 100 is : Geeks\nThe Value associated to 103 is : Contribute" }, { "code": null, "e": 6240, "s": 6226, "text": "4. Traversing" }, { "code": null, "e": 6540, "s": 6240, "text": "We can use the Iterator interface to traverse over any structure of the Collection Framework. Since Iterators work with one type of data we use Entry< ? , ? > to resolve the two separate types into a compatible format. Then using the next() method we print the elements of the ConcurrentSkipListMap." }, { "code": null, "e": 6545, "s": 6540, "text": "Java" }, { "code": "import java.util.concurrent.*;import java.util.*; public class TraversingExample { public static void main(String[] args) { // Instantiate an object // Since ConcurrentMap // is an interface so We use // ConcurrentSkipListMap ConcurrentMap<Integer, String> chmap = new ConcurrentSkipListMap<Integer, String>(); // Add elements using put() chmap.put(8, \"Third\"); chmap.put(6, \"Second\"); chmap.put(3, \"First\"); chmap.put(11, \"Fourth\"); // Create an Iterator over the // ConcurrentSkipListMap Iterator<ConcurrentSkipListMap .Entry<Integer, String> > itr = chmap.entrySet().iterator(); // The hasNext() method is used to check if there is // a next element The next() method is used to // retrieve the next element while (itr.hasNext()) { ConcurrentSkipListMap .Entry<Integer, String> entry = itr.next(); System.out.println(\"Key = \" + entry.getKey() + \", Value = \" + entry.getValue()); } }}", "e": 7721, "s": 6545, "text": null }, { "code": null, "e": 7816, "s": 7721, "text": "Key = 3, Value = First\nKey = 6, Value = Second\nKey = 8, Value = Third\nKey = 11, Value = Fourth" }, { "code": null, "e": 7853, "s": 7816, "text": "K – The type of the keys in the map." }, { "code": null, "e": 7895, "s": 7853, "text": "V – The type of values mapped in the map." }, { "code": null, "e": 7902, "s": 7895, "text": "METHOD" }, { "code": null, "e": 7914, "s": 7902, "text": "DESCRIPTION" }, { "code": null, "e": 7959, "s": 7914, "text": "compute​(K key, BiFunction<? super K,? super" }, { "code": null, "e": 7994, "s": 7959, "text": " V,? extends V> remappingFunction)" }, { "code": null, "e": 8001, "s": 7994, "text": "METHOD" }, { "code": null, "e": 8013, "s": 8001, "text": "DESCRIPTION" }, { "code": null, "e": 8125, "s": 8013, "text": "Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/ConcurrentMap.html" }, { "code": null, "e": 8149, "s": 8125, "text": "Ganeshchowdharysadanala" }, { "code": null, "e": 8166, "s": 8149, "text": "Java-Collections" }, { "code": null, "e": 8179, "s": 8166, "text": "Java-HashMap" }, { "code": null, "e": 8184, "s": 8179, "text": "Java" }, { "code": null, "e": 8189, "s": 8184, "text": "Java" }, { "code": null, "e": 8206, "s": 8189, "text": "Java-Collections" } ]
HTML | Marquee loop attribute
14 Jan, 2022 The Marquee loop attribute in HTML is used to define the number of time marquee should loop. The default value of loop is INFINITE.Syntax: <marquee loop="number" > Attribute value: number: Specify the number of loop. Example: html <!DOCTYPE html><html> <head> <title>HTML Marquee loop attribute</title> <style> .main { text-align: center; font-family: "Times New Roman"; } .marq { padding-top: 30px; padding-bottom: 30px; } .geek1 { font-size: 36px; font-weight: bold; color: white; text-align: center; } .geek2 { text-align: center; } </style></head> <body> <div class="main"> <marquee class="marq" bgcolor="Green" direction="up" loop="1"> <div class="geek1">GeeksforGeeks</div> <div class="geek2"> A computer science portal for geeks </div> </marquee> <marquee class="marq" bgcolor="Green" direction="up" loop="2"> <div class="geek1">GeeksforGeeks</div> <div class="geek2"> A computer science portal for geeks </div> </marquee> </div></body> </html> Output: Supported Browsers: The browsers supported by HTML Marquee loop attribute are listed below: Google Chrome Internet Explorer Firefox Apple Safari Opera ManasChhabra2 HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) HTTP headers | Content-Type Design a Tribute Page using HTML & CSS How to Insert Form Data into Database using PHP ? How to position a div at the bottom of its container using CSS? Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Jan, 2022" }, { "code": null, "e": 169, "s": 28, "text": "The Marquee loop attribute in HTML is used to define the number of time marquee should loop. The default value of loop is INFINITE.Syntax: " }, { "code": null, "e": 194, "s": 169, "text": "<marquee loop=\"number\" >" }, { "code": null, "e": 213, "s": 194, "text": "Attribute value: " }, { "code": null, "e": 249, "s": 213, "text": "number: Specify the number of loop." }, { "code": null, "e": 260, "s": 249, "text": "Example: " }, { "code": null, "e": 265, "s": 260, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>HTML Marquee loop attribute</title> <style> .main { text-align: center; font-family: \"Times New Roman\"; } .marq { padding-top: 30px; padding-bottom: 30px; } .geek1 { font-size: 36px; font-weight: bold; color: white; text-align: center; } .geek2 { text-align: center; } </style></head> <body> <div class=\"main\"> <marquee class=\"marq\" bgcolor=\"Green\" direction=\"up\" loop=\"1\"> <div class=\"geek1\">GeeksforGeeks</div> <div class=\"geek2\"> A computer science portal for geeks </div> </marquee> <marquee class=\"marq\" bgcolor=\"Green\" direction=\"up\" loop=\"2\"> <div class=\"geek1\">GeeksforGeeks</div> <div class=\"geek2\"> A computer science portal for geeks </div> </marquee> </div></body> </html>", "e": 1417, "s": 265, "text": null }, { "code": null, "e": 1427, "s": 1417, "text": "Output: " }, { "code": null, "e": 1521, "s": 1427, "text": "Supported Browsers: The browsers supported by HTML Marquee loop attribute are listed below: " }, { "code": null, "e": 1535, "s": 1521, "text": "Google Chrome" }, { "code": null, "e": 1553, "s": 1535, "text": "Internet Explorer" }, { "code": null, "e": 1561, "s": 1553, "text": "Firefox" }, { "code": null, "e": 1574, "s": 1561, "text": "Apple Safari" }, { "code": null, "e": 1580, "s": 1574, "text": "Opera" }, { "code": null, "e": 1596, "s": 1582, "text": "ManasChhabra2" }, { "code": null, "e": 1612, "s": 1596, "text": "HTML-Attributes" }, { "code": null, "e": 1617, "s": 1612, "text": "HTML" }, { "code": null, "e": 1634, "s": 1617, "text": "Web Technologies" }, { "code": null, "e": 1639, "s": 1634, "text": "HTML" }, { "code": null, "e": 1737, "s": 1639, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1761, "s": 1737, "text": "REST API (Introduction)" }, { "code": null, "e": 1789, "s": 1761, "text": "HTTP headers | Content-Type" }, { "code": null, "e": 1828, "s": 1789, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 1878, "s": 1828, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 1942, "s": 1878, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 1975, "s": 1942, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2036, "s": 1975, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2079, "s": 2036, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 2151, "s": 2079, "text": "Differences between Functional Components and Class Components in React" } ]
NLP | WordNet for tagging
18 Dec, 2019 WordNet is the lexical database i.e. dictionary for the English language, specifically designed for natural language processing. Code #1 : Creating class to look up words in WordNet. from nltk.tag import SequentialBackoffTaggerfrom nltk.corpus import wordnetfrom nltk.probability import FreqDist class WordNetTagger(SequentialBackoffTagger): ''' >>> wt = WordNetTagger() >>> wt.tag(['food', 'is', 'great']) [('food', 'NN'), ('is', 'VB'), ('great', 'JJ')] ''' def __init__(self, *args, **kwargs): SequentialBackoffTagger.__init__(self, *args, **kwargs) self.wordnet_tag_map = { 'n': 'NN', 's': 'JJ', 'a': 'JJ', 'r': 'RB', 'v': 'VB' } def choose_tag(self, tokens, index, history): word = tokens[index] fd = FreqDist() for synset in wordnet.synsets(word): fd[synset.pos()] += 1 return self.wordnet_tag_map.get(fd.max()) This WordNetTagger class will count the no. of each POS tag found in the Synsets for a word and then, the most common tag is to treebank tag using internal mapping. Code #2 : Using a simple WordNetTagger() from taggers import WordNetTaggerfrom nltk.corpus import treebank # Initializingdefault_tag = DefaultTagger('NN') # initializing training and testing set train_data = treebank.tagged_sents()[:3000]test_data = treebank.tagged_sents()[3000:] wn_tagging = WordNetTagger()a = wn_tagger.evaluate(test_data) print ("Accuracy of WordNetTagger : ", a) Output : Accuracy of WordNetTagger : 0.17914876598160262 Using Code 3, we can improve the accuracy.Code #3 : WordNetTagger class at the end of an NgramTagger backoff chain from taggers import WordNetTaggerfrom nltk.corpus import treebankfrom tag_util import backoff_taggerfrom nltk.tag import UnigramTagger, BigramTagger, TrigramTagger # Initializingdefault_tag = DefaultTagger('NN') # initializing training and testing set train_data = treebank.tagged_sents()[:3000]test_data = treebank.tagged_sents()[3000:] tagger = backoff_tagger(train_data, [UnigramTagger, BigramTagger, TrigramTagger], backoff = wn_tagger) a = tagger.evaluate(test_data) print ("Accuracy : ", a) Output : Accuracy : 0.8848262464925534 shubham_singh Natural-language-processing Python-nltk Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Dec, 2019" }, { "code": null, "e": 157, "s": 28, "text": "WordNet is the lexical database i.e. dictionary for the English language, specifically designed for natural language processing." }, { "code": null, "e": 211, "s": 157, "text": "Code #1 : Creating class to look up words in WordNet." }, { "code": "from nltk.tag import SequentialBackoffTaggerfrom nltk.corpus import wordnetfrom nltk.probability import FreqDist class WordNetTagger(SequentialBackoffTagger): ''' >>> wt = WordNetTagger() >>> wt.tag(['food', 'is', 'great']) [('food', 'NN'), ('is', 'VB'), ('great', 'JJ')] ''' def __init__(self, *args, **kwargs): SequentialBackoffTagger.__init__(self, *args, **kwargs) self.wordnet_tag_map = { 'n': 'NN', 's': 'JJ', 'a': 'JJ', 'r': 'RB', 'v': 'VB' } def choose_tag(self, tokens, index, history): word = tokens[index] fd = FreqDist() for synset in wordnet.synsets(word): fd[synset.pos()] += 1 return self.wordnet_tag_map.get(fd.max())", "e": 1006, "s": 211, "text": null }, { "code": null, "e": 1171, "s": 1006, "text": "This WordNetTagger class will count the no. of each POS tag found in the Synsets for a word and then, the most common tag is to treebank tag using internal mapping." }, { "code": null, "e": 1212, "s": 1171, "text": "Code #2 : Using a simple WordNetTagger()" }, { "code": "from taggers import WordNetTaggerfrom nltk.corpus import treebank # Initializingdefault_tag = DefaultTagger('NN') # initializing training and testing set train_data = treebank.tagged_sents()[:3000]test_data = treebank.tagged_sents()[3000:] wn_tagging = WordNetTagger()a = wn_tagger.evaluate(test_data) print (\"Accuracy of WordNetTagger : \", a)", "e": 1563, "s": 1212, "text": null }, { "code": null, "e": 1572, "s": 1563, "text": "Output :" }, { "code": null, "e": 1621, "s": 1572, "text": "Accuracy of WordNetTagger : 0.17914876598160262\n" }, { "code": null, "e": 1736, "s": 1621, "text": "Using Code 3, we can improve the accuracy.Code #3 : WordNetTagger class at the end of an NgramTagger backoff chain" }, { "code": "from taggers import WordNetTaggerfrom nltk.corpus import treebankfrom tag_util import backoff_taggerfrom nltk.tag import UnigramTagger, BigramTagger, TrigramTagger # Initializingdefault_tag = DefaultTagger('NN') # initializing training and testing set train_data = treebank.tagged_sents()[:3000]test_data = treebank.tagged_sents()[3000:] tagger = backoff_tagger(train_data, [UnigramTagger, BigramTagger, TrigramTagger], backoff = wn_tagger) a = tagger.evaluate(test_data) print (\"Accuracy : \", a)", "e": 2292, "s": 1736, "text": null }, { "code": null, "e": 2301, "s": 2292, "text": "Output :" }, { "code": null, "e": 2332, "s": 2301, "text": "Accuracy : 0.8848262464925534\n" }, { "code": null, "e": 2346, "s": 2332, "text": "shubham_singh" }, { "code": null, "e": 2374, "s": 2346, "text": "Natural-language-processing" }, { "code": null, "e": 2386, "s": 2374, "text": "Python-nltk" }, { "code": null, "e": 2393, "s": 2386, "text": "Python" } ]
Prime number of set bits | Practice | GeeksforGeeks
Given two integers L and R, write a program that finds the count of numbers having prime number of set bits in their binary representation in the range [L, R]. Example 1: Input: L = 6, R = 10 Output: 4 Explanation: 6, 7, 9, 10 having prime set bits between 6 and 10. Example 2: Input: L = 10, R = 15 Output: 5 Explanation: 10, 11, 12, 13, 14 having prime set bits between 10 and 15. Your Task: You dont need to read input or print anything. Complete the function primeSetBits() which takes L and R as input parameter and returns the count of numbers having prime number of set bits in their binary representation. Expected Time Complexity: O(nlog(n)sqrt(n)) Expected Auxiliary Space: O(1) Constraints: 1 <= L <= R <=1000 0 60mqcs20shivamyadavin 1 hour #Pyhton solution def primeSetBits(self, L, R): # code here l = 1001 siv = [0] * l siv[0] = 1 siv[1] = 1 for i in range(2,int(math.sqrt(l))+1): if siv[i]==0: for j in range(2*i,l,i): siv[j] = 1 count =0 for i in range(L,R+1): m = i c =0 while m !=0: m = m & m-1 c +=1 if siv[c]==0: count +=1 return count 0 vermaashitiit1 month ago Execution Time:0.00 int i,j,n=R+1; bool isprime[n]; fill_n(isprime,n,true); isprime[0]=isprime[1]=false; for(i=2;i<n;i++){ if(isprime[i]==true){ for(j=2*i;j<n;j+=i){ isprime[j]=false; } } } int ans=0; for(i=L;i<=R;i++){ int c=0; j=i; while(j){ c++; j=j&(j-1); } if(isprime[c]==true) ans++; } return ans; 0 aman44113 months ago public int primeSetBits(int L, int R) { int ans = 0; for(int i=L;i<=R;i++){ String binary = Integer.toBinaryString(i); int setBits = 0; for(char c : binary.toCharArray()){ if(c == '1'){ setBits++; } } if(isPrime(setBits)){ ans++; } } return ans; } public static boolean isPrime(int num){ if(num == 0 || num == 1){ return false; } for(int i=2;i<=Math.sqrt(num);i++){ if(num%i == 0){ return false; } } return true; } 0 Aakarshak arora10 months ago Aakarshak arora Python3 def primeSetBits(self, L, R): count, co = 0, 0 def prime(c): if c == 2: return True if c % 2 == 0 or c == 1: return False for i in range(3, int(c / 3) + 1, 2): if c % i == 0: return False return True for i in range(L, R + 1): x = bin(i)[2:] for j in x: if j == '1': count += 1 if prime(count): co += 1 count = 0 return co 0 ahmar11 months ago ahmar Status :Passedtechnique Used : prime no logic.Lang : Javapre requisites: School level of stack.Code : https://ide.geeksforgeeks.o... 0 Bhanu1 year ago Bhanu The time complexity is O(nlog(k)+nsqrt(log(k)))space complexity is O(1) class Solution:def primeSetBits(self, L, R): tot = 0 for i in range(L, R+1): tSetbits = self.noOfSetBits(i) if self.isPrime(tSetbits): tot += 1 return tot def noOfSetBits(self, num): tot = 0 if num%2: tot += 1 while num: num >>= 1 if num%2: tot += 1 return tot def isPrime(self, num): if num == 1: return 0 if num == 2: return 1 for i in range(2, int(num**0.5)+2): if num%i == 0: return 0 return 1 0 Annanya Mathur1 year ago Annanya Mathur bool isprime(int n) { if (n<2) return false; for(int i=2;i*i<=n;i++) { if(n%i==0) return false; } return true; } int primeSetBits(int L, int R){ int c=0; for(int i=L;i<=R;i++) { int p=__builtin_popcount(i); if(isprime(p)) c++; } return c; } 0 Kausar Ahamed1 year ago Kausar Ahamed ET-0.48 0 mihir vaghela2 years ago mihir vaghela JAVA SOLUTION import java.util.*;import java.lang.*;import java.io.*; class GFG {public static void main (String[] args) {//codeScanner obj = new Scanner(System.in);int T = obj.nextInt();int cnt=0;while(T-->0){ int L = obj.nextInt(); int R = obj.nextInt(); for(int i = L ; i<= R ; i++) { if(isPrime(Integer.bitCount(i))) cnt++; } System.out.println(cnt); cnt=0;} }public static boolean isPrime(int num){ if(num == 0 || num == 1) return(false); if(num != 2 && num %2 ==0) return(false); for(int i = 2 ; i*i <= num ; i++) { if(num % i == 0) return(false); } return(true);}} 0 Lakshya Khandelwal2 years ago Lakshya Khandelwal using buitin function of gcc compiler:#include<bits stdc++.h="">using namespace std;bool check(int k){ if(k==1)return false;if(k==2)return true; for(int i=2;i<=sqrt(k);i++) {if(k%i==0) return false;} return true;}int main() {int t;cin>>t; while(t--) { int l,r;cin>>l>>r;int p=0;for(int i=l;i<=r;i++) {int k=__builtin_popcount(i);if(check(k))p++;}cout< 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": 398, "s": 226, "text": "Given two integers L and R, write a program that finds the count of numbers having prime number of set bits in their binary representation in the range [L, R].\n\nExample 1:" }, { "code": null, "e": 496, "s": 398, "text": "Input: L = 6, R = 10\nOutput: 4\nExplanation: 6, 7, 9, 10 having\nprime set bits between 6 and 10. \n" }, { "code": null, "e": 508, "s": 496, "text": "\nExample 2:" }, { "code": null, "e": 613, "s": 508, "text": "Input: L = 10, R = 15\nOutput: 5\nExplanation: 10, 11, 12, 13, 14 having\nprime set bits between 10 and 15." }, { "code": null, "e": 956, "s": 613, "text": "\nYour Task: \nYou dont need to read input or print anything. Complete the function primeSetBits() which takes L and R as input parameter and returns the count of numbers having prime number of set bits in their binary representation.\n\nExpected Time Complexity: O(nlog(n)sqrt(n))\nExpected Auxiliary Space: O(1)\n\nConstraints:\n1 <= L <= R <=1000" }, { "code": null, "e": 958, "s": 956, "text": "0" }, { "code": null, "e": 987, "s": 958, "text": "60mqcs20shivamyadavin 1 hour" }, { "code": null, "e": 1004, "s": 987, "text": "#Pyhton solution" }, { "code": null, "e": 1355, "s": 1004, "text": "def primeSetBits(self, L, R): # code here l = 1001 siv = [0] * l siv[0] = 1 siv[1] = 1 for i in range(2,int(math.sqrt(l))+1): if siv[i]==0: for j in range(2*i,l,i): siv[j] = 1 count =0 for i in range(L,R+1): m = i c =0 while m !=0: m = m & m-1 c +=1 if siv[c]==0: count +=1 return count" }, { "code": null, "e": 1357, "s": 1355, "text": "0" }, { "code": null, "e": 1382, "s": 1357, "text": "vermaashitiit1 month ago" }, { "code": null, "e": 1402, "s": 1382, "text": "Execution Time:0.00" }, { "code": null, "e": 1886, "s": 1402, "text": "int i,j,n=R+1; bool isprime[n]; fill_n(isprime,n,true); isprime[0]=isprime[1]=false; for(i=2;i<n;i++){ if(isprime[i]==true){ for(j=2*i;j<n;j+=i){ isprime[j]=false; } } } int ans=0; for(i=L;i<=R;i++){ int c=0; j=i; while(j){ c++; j=j&(j-1); } if(isprime[c]==true) ans++; } return ans;" }, { "code": null, "e": 1888, "s": 1886, "text": "0" }, { "code": null, "e": 1909, "s": 1888, "text": "aman44113 months ago" }, { "code": null, "e": 2560, "s": 1909, "text": "public int primeSetBits(int L, int R) { int ans = 0; for(int i=L;i<=R;i++){ String binary = Integer.toBinaryString(i); int setBits = 0; for(char c : binary.toCharArray()){ if(c == '1'){ setBits++; } } if(isPrime(setBits)){ ans++; } } return ans; } public static boolean isPrime(int num){ if(num == 0 || num == 1){ return false; } for(int i=2;i<=Math.sqrt(num);i++){ if(num%i == 0){ return false; } } return true; }" }, { "code": null, "e": 2562, "s": 2560, "text": "0" }, { "code": null, "e": 2591, "s": 2562, "text": "Aakarshak arora10 months ago" }, { "code": null, "e": 2607, "s": 2591, "text": "Aakarshak arora" }, { "code": null, "e": 2615, "s": 2607, "text": "Python3" }, { "code": null, "e": 2673, "s": 2615, "text": " def primeSetBits(self, L, R): count, co = 0, 0" }, { "code": null, "e": 2942, "s": 2673, "text": " def prime(c): if c == 2: return True if c % 2 == 0 or c == 1: return False for i in range(3, int(c / 3) + 1, 2): if c % i == 0: return False return True" }, { "code": null, "e": 3002, "s": 2942, "text": " for i in range(L, R + 1): x = bin(i)[2:]" }, { "code": null, "e": 3084, "s": 3002, "text": " for j in x: if j == '1': count += 1" }, { "code": null, "e": 3174, "s": 3084, "text": " if prime(count): co += 1 count = 0 return co" }, { "code": null, "e": 3176, "s": 3174, "text": "0" }, { "code": null, "e": 3195, "s": 3176, "text": "ahmar11 months ago" }, { "code": null, "e": 3201, "s": 3195, "text": "ahmar" }, { "code": null, "e": 3334, "s": 3201, "text": "Status :Passedtechnique Used : prime no logic.Lang : Javapre requisites: School level of stack.Code : https://ide.geeksforgeeks.o..." }, { "code": null, "e": 3336, "s": 3334, "text": "0" }, { "code": null, "e": 3352, "s": 3336, "text": "Bhanu1 year ago" }, { "code": null, "e": 3358, "s": 3352, "text": "Bhanu" }, { "code": null, "e": 3431, "s": 3358, "text": "The time complexity is O(nlog(k)+nsqrt(log(k)))space complexity is O(1)" }, { "code": null, "e": 3620, "s": 3431, "text": "class Solution:def primeSetBits(self, L, R): tot = 0 for i in range(L, R+1): tSetbits = self.noOfSetBits(i) if self.isPrime(tSetbits): tot += 1 return tot" }, { "code": null, "e": 3781, "s": 3620, "text": "def noOfSetBits(self, num): tot = 0 if num%2: tot += 1 while num: num >>= 1 if num%2: tot += 1 return tot" }, { "code": null, "e": 3998, "s": 3781, "text": " def isPrime(self, num): if num == 1: return 0 if num == 2: return 1 for i in range(2, int(num**0.5)+2): if num%i == 0: return 0 return 1" }, { "code": null, "e": 4000, "s": 3998, "text": "0" }, { "code": null, "e": 4025, "s": 4000, "text": "Annanya Mathur1 year ago" }, { "code": null, "e": 4040, "s": 4025, "text": "Annanya Mathur" }, { "code": null, "e": 4321, "s": 4040, "text": "bool isprime(int n) { if (n<2) return false; for(int i=2;i*i<=n;i++) { if(n%i==0) return false; } return true; } int primeSetBits(int L, int R){ int c=0; for(int i=L;i<=R;i++) { int p=__builtin_popcount(i);" }, { "code": null, "e": 4387, "s": 4321, "text": " if(isprime(p)) c++; } return c; }" }, { "code": null, "e": 4389, "s": 4387, "text": "0" }, { "code": null, "e": 4413, "s": 4389, "text": "Kausar Ahamed1 year ago" }, { "code": null, "e": 4427, "s": 4413, "text": "Kausar Ahamed" }, { "code": null, "e": 4435, "s": 4427, "text": "ET-0.48" }, { "code": null, "e": 4437, "s": 4435, "text": "0" }, { "code": null, "e": 4462, "s": 4437, "text": "mihir vaghela2 years ago" }, { "code": null, "e": 4476, "s": 4462, "text": "mihir vaghela" }, { "code": null, "e": 4490, "s": 4476, "text": "JAVA SOLUTION" }, { "code": null, "e": 4546, "s": 4490, "text": "import java.util.*;import java.lang.*;import java.io.*;" }, { "code": null, "e": 4918, "s": 4546, "text": "class GFG {public static void main (String[] args) {//codeScanner obj = new Scanner(System.in);int T = obj.nextInt();int cnt=0;while(T-->0){ int L = obj.nextInt(); int R = obj.nextInt(); for(int i = L ; i<= R ; i++) { if(isPrime(Integer.bitCount(i))) cnt++; } System.out.println(cnt); cnt=0;}" }, { "code": null, "e": 5176, "s": 4918, "text": "}public static boolean isPrime(int num){ if(num == 0 || num == 1) return(false); if(num != 2 && num %2 ==0) return(false); for(int i = 2 ; i*i <= num ; i++) { if(num % i == 0) return(false); } return(true);}}" }, { "code": null, "e": 5178, "s": 5176, "text": "0" }, { "code": null, "e": 5208, "s": 5178, "text": "Lakshya Khandelwal2 years ago" }, { "code": null, "e": 5227, "s": 5208, "text": "Lakshya Khandelwal" }, { "code": null, "e": 5591, "s": 5227, "text": "using buitin function of gcc compiler:#include<bits stdc++.h=\"\">using namespace std;bool check(int k){ if(k==1)return false;if(k==2)return true; for(int i=2;i<=sqrt(k);i++) {if(k%i==0) return false;} return true;}int main() {int t;cin>>t; while(t--) { int l,r;cin>>l>>r;int p=0;for(int i=l;i<=r;i++) {int k=__builtin_popcount(i);if(check(k))p++;}cout<" }, { "code": null, "e": 5737, "s": 5591, "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": 5773, "s": 5737, "text": " Login to access your submissions. " }, { "code": null, "e": 5783, "s": 5773, "text": "\nProblem\n" }, { "code": null, "e": 5793, "s": 5783, "text": "\nContest\n" }, { "code": null, "e": 5856, "s": 5793, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6004, "s": 5856, "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": 6212, "s": 6004, "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": 6318, "s": 6212, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Remove One to Make Average k in Python
Suppose we have a list of numbers called nums and an integer k, we have to check whether we can remove exactly one element from the list to make the average equal to exactly k. Now we have to keep in mind that, there are some constraints − 2 ≤ n ≤ 1,000 where n is number of elements of nums list nums[i], k ≤ 1,000,000 So, if the input is like [5,3,2,4,6,10], k = 4, then the output will be True as if we remove 10, then the average of elements will be (5+3+2+4+6)/5 = 4, this is same as k. To solve this, we will follow these steps − s:= total sum of all elements in nums t := k*(size of nums - 1) for each i in nums, doif s-i is same as t, thenreturn True if s-i is same as t, thenreturn True return True return False Let us see the following implementation to get better understanding − Live Demo class Solution: def solve(self, nums, k): s=sum(nums) t = k*(len(nums)-1) for i in nums: if s-i == t: return True return False ob = Solution() nums = [5,3,2,4,6,10] k = 4 print(ob.solve(nums, k)) [5,3,2,4,6,10], 4 True
[ { "code": null, "e": 1302, "s": 1062, "text": "Suppose we have a list of numbers called nums and an integer k, we have to check whether we\ncan remove exactly one element from the list to make the average equal to exactly k. Now we\nhave to keep in mind that, there are some constraints −" }, { "code": null, "e": 1359, "s": 1302, "text": "2 ≤ n ≤ 1,000 where n is number of elements of nums list" }, { "code": null, "e": 1382, "s": 1359, "text": "nums[i], k ≤ 1,000,000" }, { "code": null, "e": 1554, "s": 1382, "text": "So, if the input is like [5,3,2,4,6,10], k = 4, then the output will be True as if we remove 10, then\nthe average of elements will be (5+3+2+4+6)/5 = 4, this is same as k." }, { "code": null, "e": 1598, "s": 1554, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1636, "s": 1598, "text": "s:= total sum of all elements in nums" }, { "code": null, "e": 1662, "s": 1636, "text": "t := k*(size of nums - 1)" }, { "code": null, "e": 1721, "s": 1662, "text": "for each i in nums, doif s-i is same as t, thenreturn True" }, { "code": null, "e": 1758, "s": 1721, "text": "if s-i is same as t, thenreturn True" }, { "code": null, "e": 1770, "s": 1758, "text": "return True" }, { "code": null, "e": 1783, "s": 1770, "text": "return False" }, { "code": null, "e": 1853, "s": 1783, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1864, "s": 1853, "text": " Live Demo" }, { "code": null, "e": 2108, "s": 1864, "text": "class Solution:\n def solve(self, nums, k):\n s=sum(nums)\n t = k*(len(nums)-1)\n for i in nums:\n if s-i == t:\n return True\n return False\nob = Solution()\nnums = [5,3,2,4,6,10]\nk = 4\nprint(ob.solve(nums, k))" }, { "code": null, "e": 2126, "s": 2108, "text": "[5,3,2,4,6,10], 4" }, { "code": null, "e": 2131, "s": 2126, "text": "True" } ]
How to subset rows of data frame without NA using dplyr in R?
To subset rows of data frame without NA using dplyr in R, we can follow the below steps − First of all, create a data frame. Then, use filter function of dplyr package to subset the rows with !is.na. Let's create a data frame as shown below − Live Demo x<-sample(c(NA,1,2),20,replace=TRUE) df<-data.frame(x) df On executing, the above script generates the below output(this output will vary on your system due to randomization) − x 1 2 2 2 3 1 4 1 5 1 6 NA 7 1 8 NA 9 NA 10 1 11 1 12 1 13 2 14 1 15 NA 16 2 17 2 18 2 19 NA 20 1 Using filter function of dplyr package to subset the rows of df with !is.na as shown below − x<-sample(c(NA,1,2),20,replace=TRUE) df<-data.frame(x) library(dplyr) df %>% filter(!is.na(x)) x 1 2 2 2 3 1 4 1 5 1 6 1 7 1 8 1 9 1 10 2 11 1 12 2 13 2 14 2 15 1
[ { "code": null, "e": 1152, "s": 1062, "text": "To subset rows of data frame without NA using dplyr in R, we can follow the below steps −" }, { "code": null, "e": 1187, "s": 1152, "text": "First of all, create a data frame." }, { "code": null, "e": 1262, "s": 1187, "text": "Then, use filter function of dplyr package to subset the rows with !is.na." }, { "code": null, "e": 1305, "s": 1262, "text": "Let's create a data frame as shown below −" }, { "code": null, "e": 1316, "s": 1305, "text": " Live Demo" }, { "code": null, "e": 1374, "s": 1316, "text": "x<-sample(c(NA,1,2),20,replace=TRUE)\ndf<-data.frame(x)\ndf" }, { "code": null, "e": 1493, "s": 1374, "text": "On executing, the above script generates the below output(this output will vary on your system due to randomization) −" }, { "code": null, "e": 1593, "s": 1493, "text": " x\n1 2\n2 2\n3 1\n4 1\n5 1\n6 NA\n7 1\n8 NA\n9 NA\n10 1\n11 1\n12 1\n13 2\n14 1\n15 NA\n16 2\n17 2\n18 2\n19 NA\n20 1" }, { "code": null, "e": 1686, "s": 1593, "text": "Using filter function of dplyr package to subset the rows of df with !is.na as shown below −" }, { "code": null, "e": 1781, "s": 1686, "text": "x<-sample(c(NA,1,2),20,replace=TRUE)\ndf<-data.frame(x)\nlibrary(dplyr)\ndf %>% filter(!is.na(x))" }, { "code": null, "e": 1851, "s": 1781, "text": " x\n1 2\n2 2\n3 1\n4 1\n5 1\n6 1\n7 1\n8 1\n9 1\n10 2\n11 1\n12 2\n13 2\n14 2\n15 1" } ]
How to sort array according to age in JavaScript?
We are required to write a JavaScript function that takes in an array of numbers representing ages of some people. Then the function should bring all the ages less than 18 to the front of the array without using any extra memory. The code for this will be − const ages = [23, 56, 56, 3, 67, 8, 4, 34, 23, 12, 67, 16, 47]; const sorter = (a, b) => { if (a < 18) { return -1; }; if (b < 18) { return 1; }; return 0; } const sortByAdults = arr => { arr.sort(sorter); }; sortByAdults(ages); console.log(ages); The output in the console − [ 16, 12, 4, 8, 3, 23, 56, 56, 67, 34, 23, 67, 47 ]
[ { "code": null, "e": 1177, "s": 1062, "text": "We are required to write a JavaScript function that takes in an array of numbers representing\nages of some people." }, { "code": null, "e": 1292, "s": 1177, "text": "Then the function should bring all the ages less than 18 to the front of the array without using any extra memory." }, { "code": null, "e": 1320, "s": 1292, "text": "The code for this will be −" }, { "code": null, "e": 1598, "s": 1320, "text": "const ages = [23, 56, 56, 3, 67, 8, 4, 34, 23, 12, 67, 16, 47];\nconst sorter = (a, b) => {\n if (a < 18) {\n return -1;\n };\n if (b < 18) {\n return 1;\n };\n return 0;\n}\nconst sortByAdults = arr => {\n arr.sort(sorter);\n};\nsortByAdults(ages);\nconsole.log(ages);" }, { "code": null, "e": 1626, "s": 1598, "text": "The output in the console −" }, { "code": null, "e": 1684, "s": 1626, "text": "[\n 16, 12, 4, 8, 3, 23, 56,\n 56, 67, 34, 23, 67, 47\n]" } ]
Python - Itertools.Product() - GeeksforGeeks
04 Sep, 2021 In the terms of Mathematics Cartesian Product of two sets is defined as the set of all ordered pairs (a, b) where a belongs to A and b belongs to B. Consider the below example for better understanding.Examples: Input : arr1 = [1, 2, 3] arr2 = [5, 6, 7] Output : [(1, 5), (1, 6), (1, 7), (2, 5), (2, 6), (2, 7), (3, 5), (3, 6), (3, 7)] Input : arr1 = [10, 12] arr2 = [8, 9, 10] Output : [(10, 8), (10, 9), (10, 10), (12, 8), (12, 9), (12, 10)] The above solution can be done by looping but we will use a special Python library itertools.product() for finding the Cartesian Product. Let’s go through the working and use cases of this Python library. Python Itertools is a library in Python which consists of multiple methods that are used in various iterators to compute a fast and code efficient solution. itertools.product() falls under the category called Combinatoric iterators of the Python itertools library. Note: For more information, refer to Python Itertools itertools.product() is used to find the cartesian product from the given iterator, output is lexicographic ordered. The itertools.product() can used in two different ways: itertools.product(*iterables, repeat=1):It returns the cartesian product of the provided iterable with itself for the number of times specified by the optional keyword “repeat”. For example, product(arr, repeat=3) means the same as product(arr, arr, arr). itertools.product(*iterables):It returns the cartesian product of all the iterable provided as the argument. For example, product(arr1, arr2, arr3). Example: Python3 from itertools import product def cartesian_product(arr1, arr2): # return the list of all the computed tuple # using the product() method return list(product(arr1, arr2)) # Driver Functionif __name__ == "__main__": arr1 = [1, 2, 3] arr2 = [5, 6, 7] print(cartesian_product(arr1, arr2)) Output: [(1, 5), (1, 6), (1, 7), (2, 5), (2, 6), (2, 7), (3, 5), (3, 6), (3, 7)] sooda367 gabaa406 Python-itertools Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Python program to convert a list to string Reading and Writing to text files in Python sum() function in Python *args and **kwargs in Python
[ { "code": null, "e": 24510, "s": 24482, "text": "\n04 Sep, 2021" }, { "code": null, "e": 24721, "s": 24510, "text": "In the terms of Mathematics Cartesian Product of two sets is defined as the set of all ordered pairs (a, b) where a belongs to A and b belongs to B. Consider the below example for better understanding.Examples:" }, { "code": null, "e": 24955, "s": 24721, "text": "Input : arr1 = [1, 2, 3] arr2 = [5, 6, 7] Output : [(1, 5), (1, 6), (1, 7), (2, 5), (2, 6), (2, 7), (3, 5), (3, 6), (3, 7)] Input : arr1 = [10, 12] arr2 = [8, 9, 10] Output : [(10, 8), (10, 9), (10, 10), (12, 8), (12, 9), (12, 10)] " }, { "code": null, "e": 25161, "s": 24955, "text": "The above solution can be done by looping but we will use a special Python library itertools.product() for finding the Cartesian Product. Let’s go through the working and use cases of this Python library. " }, { "code": null, "e": 25319, "s": 25161, "text": "Python Itertools is a library in Python which consists of multiple methods that are used in various iterators to compute a fast and code efficient solution. " }, { "code": null, "e": 25427, "s": 25319, "text": "itertools.product() falls under the category called Combinatoric iterators of the Python itertools library." }, { "code": null, "e": 25482, "s": 25427, "text": "Note: For more information, refer to Python Itertools " }, { "code": null, "e": 25654, "s": 25482, "text": "itertools.product() is used to find the cartesian product from the given iterator, output is lexicographic ordered. The itertools.product() can used in two different ways:" }, { "code": null, "e": 25910, "s": 25654, "text": "itertools.product(*iterables, repeat=1):It returns the cartesian product of the provided iterable with itself for the number of times specified by the optional keyword “repeat”. For example, product(arr, repeat=3) means the same as product(arr, arr, arr)." }, { "code": null, "e": 26059, "s": 25910, "text": "itertools.product(*iterables):It returns the cartesian product of all the iterable provided as the argument. For example, product(arr1, arr2, arr3)." }, { "code": null, "e": 26068, "s": 26059, "text": "Example:" }, { "code": null, "e": 26076, "s": 26068, "text": "Python3" }, { "code": "from itertools import product def cartesian_product(arr1, arr2): # return the list of all the computed tuple # using the product() method return list(product(arr1, arr2)) # Driver Functionif __name__ == \"__main__\": arr1 = [1, 2, 3] arr2 = [5, 6, 7] print(cartesian_product(arr1, arr2))", "e": 26383, "s": 26076, "text": null }, { "code": null, "e": 26391, "s": 26383, "text": "Output:" }, { "code": null, "e": 26465, "s": 26391, "text": "[(1, 5), (1, 6), (1, 7), (2, 5), (2, 6), (2, 7), (3, 5), (3, 6), (3, 7)] " }, { "code": null, "e": 26474, "s": 26465, "text": "sooda367" }, { "code": null, "e": 26483, "s": 26474, "text": "gabaa406" }, { "code": null, "e": 26500, "s": 26483, "text": "Python-itertools" }, { "code": null, "e": 26507, "s": 26500, "text": "Python" }, { "code": null, "e": 26605, "s": 26507, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26623, "s": 26605, "text": "Python Dictionary" }, { "code": null, "e": 26658, "s": 26623, "text": "Read a file line by line in Python" }, { "code": null, "e": 26690, "s": 26658, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26732, "s": 26690, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26758, "s": 26732, "text": "Python String | replace()" }, { "code": null, "e": 26795, "s": 26758, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 26838, "s": 26795, "text": "Python program to convert a list to string" }, { "code": null, "e": 26882, "s": 26838, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 26907, "s": 26882, "text": "sum() function in Python" } ]
How to delete child element in BeautifulSoup? - GeeksforGeeks
03 Mar, 2021 Beautifulsoup is a Python library used for web scraping. This powerful python tool can also be used to modify html webpages. This article depicts how beautifulsoup can be employed to delete child element. For this, various methods of the module is used. Methods Used: clear(): Tag.clear() deletes the tag from the tree of a given HTML document. decompose(): Tag.decompose() removes a tag from the tree of a given HTML document, then completely destroys it and its contents. replace(): Tag.replace() replaces a particular tag with a new tag. Approach: Import module. Scrap data from webpage. Parse the string scraped to html. Find the tag whose child element to be deleted. Use any of the methods: clear(), decompose() or replace(). Print replaced content. Example 1: Python3 # importing modulefrom bs4 import BeautifulSoup markup = """ <!DOCTYPE><html> <head><title>Example</title></head> <body> <div id="parent"> <p> This is child of div with id = "parent". <span>Child of "P"</span> </p> <div> Another Child of div with id = "parent". </div> </div> <p> Piyush </p> </body></html>""" # parsering string to HTMLsoup = BeautifulSoup(markup, 'html.parser') # finding tag whose child to be deleteddiv_bs4 = soup.find('div') # delete the child elementdiv_bs4.clear() print(div_bs4) Output: <div id="parent"></div> Example 2: Python3 # importing modulefrom bs4 import BeautifulSoup markup = """ <!DOCTYPE><html> <head><title>Example</title></head> <body> <div id="parent"> <p> This is child of div with id = "parent". <span>Child of "P"</span> </p> <div> Another Child of div with id = "parent". </div> </div> <p> Piyush </p> </body></html>""" # parsering string to HTMLsoup = BeautifulSoup(markup, 'html.parser') # finding tag whose child to be deleteddiv_bs4 = soup.find('div') # delete the child elementdiv_bs4.decompose() print(div_bs4) Output: <None></None> Example 3: Python3 # importing modulefrom bs4 import BeautifulSoup markup = """ <!DOCTYPE><html> <head><title>Example</title></head> <body> <div id="parent"> <p> This is child of div with id = "parent". <span>Child of "P"</span> </p> <div> Another Child of div with id = "parent". </div> </div> <p> Piyush </p> </body></html>""" # parsering string to HTMLsoup = BeautifulSoup(markup, 'html.parser') # finding tag whose child to be deleteddiv_bs4 = soup.find('div') # delete the child elementdiv_bs4.replaceWith('') print(div_bs4) Output: <div id="parent"> <p> This is child of div with id = "parent". <span>Child of "P"</span> </p> <div> Another Child of div with id = "parent". </div> </div> Picked Python BeautifulSoup Python bs4-Exercises 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 ? Selecting rows in pandas DataFrame based on conditions How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Defaultdict in Python Python OOPs Concepts Python | os.path.join() method Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n03 Mar, 2021" }, { "code": null, "e": 24546, "s": 24292, "text": "Beautifulsoup is a Python library used for web scraping. This powerful python tool can also be used to modify html webpages. This article depicts how beautifulsoup can be employed to delete child element. For this, various methods of the module is used." }, { "code": null, "e": 24560, "s": 24546, "text": "Methods Used:" }, { "code": null, "e": 24637, "s": 24560, "text": "clear(): Tag.clear() deletes the tag from the tree of a given HTML document." }, { "code": null, "e": 24766, "s": 24637, "text": "decompose(): Tag.decompose() removes a tag from the tree of a given HTML document, then completely destroys it and its contents." }, { "code": null, "e": 24833, "s": 24766, "text": "replace(): Tag.replace() replaces a particular tag with a new tag." }, { "code": null, "e": 24843, "s": 24833, "text": "Approach:" }, { "code": null, "e": 24858, "s": 24843, "text": "Import module." }, { "code": null, "e": 24883, "s": 24858, "text": "Scrap data from webpage." }, { "code": null, "e": 24917, "s": 24883, "text": "Parse the string scraped to html." }, { "code": null, "e": 24965, "s": 24917, "text": "Find the tag whose child element to be deleted." }, { "code": null, "e": 25024, "s": 24965, "text": "Use any of the methods: clear(), decompose() or replace()." }, { "code": null, "e": 25048, "s": 25024, "text": "Print replaced content." }, { "code": null, "e": 25059, "s": 25048, "text": "Example 1:" }, { "code": null, "e": 25067, "s": 25059, "text": "Python3" }, { "code": "# importing modulefrom bs4 import BeautifulSoup markup = \"\"\" <!DOCTYPE><html> <head><title>Example</title></head> <body> <div id=\"parent\"> <p> This is child of div with id = \"parent\". <span>Child of \"P\"</span> </p> <div> Another Child of div with id = \"parent\". </div> </div> <p> Piyush </p> </body></html>\"\"\" # parsering string to HTMLsoup = BeautifulSoup(markup, 'html.parser') # finding tag whose child to be deleteddiv_bs4 = soup.find('div') # delete the child elementdiv_bs4.clear() print(div_bs4)", "e": 25626, "s": 25067, "text": null }, { "code": null, "e": 25634, "s": 25626, "text": "Output:" }, { "code": null, "e": 25658, "s": 25634, "text": "<div id=\"parent\"></div>" }, { "code": null, "e": 25669, "s": 25658, "text": "Example 2:" }, { "code": null, "e": 25677, "s": 25669, "text": "Python3" }, { "code": "# importing modulefrom bs4 import BeautifulSoup markup = \"\"\" <!DOCTYPE><html> <head><title>Example</title></head> <body> <div id=\"parent\"> <p> This is child of div with id = \"parent\". <span>Child of \"P\"</span> </p> <div> Another Child of div with id = \"parent\". </div> </div> <p> Piyush </p> </body></html>\"\"\" # parsering string to HTMLsoup = BeautifulSoup(markup, 'html.parser') # finding tag whose child to be deleteddiv_bs4 = soup.find('div') # delete the child elementdiv_bs4.decompose() print(div_bs4)", "e": 26240, "s": 25677, "text": null }, { "code": null, "e": 26248, "s": 26240, "text": "Output:" }, { "code": null, "e": 26262, "s": 26248, "text": "<None></None>" }, { "code": null, "e": 26273, "s": 26262, "text": "Example 3:" }, { "code": null, "e": 26281, "s": 26273, "text": "Python3" }, { "code": "# importing modulefrom bs4 import BeautifulSoup markup = \"\"\" <!DOCTYPE><html> <head><title>Example</title></head> <body> <div id=\"parent\"> <p> This is child of div with id = \"parent\". <span>Child of \"P\"</span> </p> <div> Another Child of div with id = \"parent\". </div> </div> <p> Piyush </p> </body></html>\"\"\" # parsering string to HTMLsoup = BeautifulSoup(markup, 'html.parser') # finding tag whose child to be deleteddiv_bs4 = soup.find('div') # delete the child elementdiv_bs4.replaceWith('') print(div_bs4)", "e": 26848, "s": 26281, "text": null }, { "code": null, "e": 26856, "s": 26848, "text": "Output:" }, { "code": null, "e": 27023, "s": 26856, "text": "<div id=\"parent\">\n<p>\n This is child of div with id = \"parent\".\n <span>Child of \"P\"</span>\n</p>\n<div>\n Another Child of div with id = \"parent\".\n </div>\n</div>" }, { "code": null, "e": 27030, "s": 27023, "text": "Picked" }, { "code": null, "e": 27051, "s": 27030, "text": "Python BeautifulSoup" }, { "code": null, "e": 27072, "s": 27051, "text": "Python bs4-Exercises" }, { "code": null, "e": 27079, "s": 27072, "text": "Python" }, { "code": null, "e": 27177, "s": 27079, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27186, "s": 27177, "text": "Comments" }, { "code": null, "e": 27199, "s": 27186, "text": "Old Comments" }, { "code": null, "e": 27231, "s": 27199, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27286, "s": 27231, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 27342, "s": 27286, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27384, "s": 27342, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27426, "s": 27384, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27465, "s": 27426, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27487, "s": 27465, "text": "Defaultdict in Python" }, { "code": null, "e": 27508, "s": 27487, "text": "Python OOPs Concepts" }, { "code": null, "e": 27539, "s": 27508, "text": "Python | os.path.join() method" } ]
Java String codePointCount() Method
❮ String Methods Return the number of Unicode values found in a string: String myStr = "Hello"; int result = myStr.codePointCount(0, 5); System.out.println(result); Try it Yourself » The codePointCount() method returns the number of Unicode values found in a string. Use the startIndex and endIndex parameters to specify where to begin and end the search. The index of the first character is 0, the second character is 1, and so on. public int codePointCount(int startIndex, int endIndex) We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 19, "s": 0, "text": "\n❮ String Methods\n" }, { "code": null, "e": 74, "s": 19, "text": "Return the number of Unicode values found in a string:" }, { "code": null, "e": 167, "s": 74, "text": "String myStr = \"Hello\";\nint result = myStr.codePointCount(0, 5);\nSystem.out.println(result);" }, { "code": null, "e": 187, "s": 167, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 272, "s": 187, "text": "The codePointCount() method returns the \nnumber of Unicode values found in a string." }, { "code": null, "e": 362, "s": 272, "text": "Use the startIndex and endIndex parameters to specify where \nto begin and end the search." }, { "code": null, "e": 439, "s": 362, "text": "The index of the first character is 0, the second character is 1, and so on." }, { "code": null, "e": 496, "s": 439, "text": "public int codePointCount(int startIndex, int endIndex)\n" }, { "code": null, "e": 529, "s": 496, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 571, "s": 529, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 678, "s": 571, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 697, "s": 678, "text": "help@w3schools.com" } ]
Display the minimum and maximum value of primitive data types in Java
Every data type in Java has a minimum as well as maximum range, for example, for Float. Min = 1.4E-45 Max = 3.4028235E38 Let’s say for Float, if the value extends the maximum range displayed above, it leads to Overflow. However, if the value is less than the minimum range displayed above, it leads to Underflow. The following is the Java Program to display the minimum and maximum value of primitive data types. Live Demo public class Demo { public static void main(String[] args) { System.out.println("Integer Datatype values..."); System.out.println("Min = " + Integer.MIN_VALUE); System.out.println("Max = " + Integer.MAX_VALUE); System.out.println("Float Datatype values..."); System.out.println("Min = " + Float.MIN_VALUE); System.out.println("Max = " + Float.MAX_VALUE); System.out.println("Double Datatype values..."); System.out.println("Min = " + Double.MIN_VALUE); System.out.println("Max = " + Double.MAX_VALUE); System.out.println("Byte Datatype values..."); System.out.println("Min = " + Byte.MIN_VALUE); System.out.println("Max = " + Byte.MAX_VALUE); System.out.println("Short Datatype values..."); System.out.println("Min = " + Short.MIN_VALUE); System.out.println("Max = " + Short.MAX_VALUE); } } Integer Datatype values... Min = -2147483648 Max = 2147483647 Float Datatype values... Min = 1.4E-45 Max = 3.4028235E38 Double Datatype values... Min = 4.9E-324 Max = 1.7976931348623157E308 Byte Datatype values... Min = -128 Max = 127 Short Datatype values... Min = -32768 Max = 32767 In the above program, we have taken each datatype one by one and used the following properties to get the minimum and maximum values. For example, datatype Short. Short.MIN_VALUE; Short.MAX_VALUE The above returns the minimum and maximum value of Short datatype. In the same way, it works for other datatypes. Min = -32768 Max = 32767
[ { "code": null, "e": 1150, "s": 1062, "text": "Every data type in Java has a minimum as well as maximum range, for example, for Float." }, { "code": null, "e": 1183, "s": 1150, "text": "Min = 1.4E-45\nMax = 3.4028235E38" }, { "code": null, "e": 1282, "s": 1183, "text": "Let’s say for Float, if the value extends the maximum range displayed above, it leads to Overflow." }, { "code": null, "e": 1375, "s": 1282, "text": "However, if the value is less than the minimum range displayed above, it leads to Underflow." }, { "code": null, "e": 1475, "s": 1375, "text": "The following is the Java Program to display the minimum and maximum value of primitive data types." }, { "code": null, "e": 1486, "s": 1475, "text": " Live Demo" }, { "code": null, "e": 2377, "s": 1486, "text": "public class Demo {\n public static void main(String[] args) {\n System.out.println(\"Integer Datatype values...\");\n System.out.println(\"Min = \" + Integer.MIN_VALUE);\n System.out.println(\"Max = \" + Integer.MAX_VALUE);\n\n System.out.println(\"Float Datatype values...\");\n System.out.println(\"Min = \" + Float.MIN_VALUE);\n System.out.println(\"Max = \" + Float.MAX_VALUE);\n\n System.out.println(\"Double Datatype values...\");\n System.out.println(\"Min = \" + Double.MIN_VALUE);\n System.out.println(\"Max = \" + Double.MAX_VALUE);\n\n System.out.println(\"Byte Datatype values...\");\n System.out.println(\"Min = \" + Byte.MIN_VALUE);\n System.out.println(\"Max = \" + Byte.MAX_VALUE);\n\n System.out.println(\"Short Datatype values...\");\n System.out.println(\"Min = \" + Short.MIN_VALUE);\n System.out.println(\"Max = \" + Short.MAX_VALUE);\n }\n}" }, { "code": null, "e": 2662, "s": 2377, "text": "Integer Datatype values...\nMin = -2147483648\nMax = 2147483647\nFloat Datatype values...\nMin = 1.4E-45\nMax = 3.4028235E38\nDouble Datatype values...\nMin = 4.9E-324\nMax = 1.7976931348623157E308\nByte Datatype values...\nMin = -128\nMax = 127\nShort Datatype values...\nMin = -32768\nMax = 32767" }, { "code": null, "e": 2825, "s": 2662, "text": "In the above program, we have taken each datatype one by one and used the following properties to get the minimum and maximum values. For example, datatype Short." }, { "code": null, "e": 2858, "s": 2825, "text": "Short.MIN_VALUE;\nShort.MAX_VALUE" }, { "code": null, "e": 2972, "s": 2858, "text": "The above returns the minimum and maximum value of Short datatype. In the same way, it works for other datatypes." }, { "code": null, "e": 2997, "s": 2972, "text": "Min = -32768\nMax = 32767" } ]
UNet. Introducing Symmetry in Segmentation | by Heet Sankesara | Towards Data Science
Vision is one of the most important senses humans possess. But have you ever wondered about the complexity of the task? The ability to capture the reflected light rays and get meaning out of it is a very convoluted task and yet we do it so easily. We developed it due to millions of years of evolution. So how can we give machines the same ability in a very small period of time? For computers, these images are nothing but matrices and understanding the nuances behind these matrices has been an obsession for many mathematicians for years. But after the emergence of artificial intelligence and particularly CNN architectures, the research has made progress like never before. Many problems which are previously considered untouchable are now showing astounding results. One such problem is the image segmentation. In Image Segmentation, the machine has to partition the image into different segments, each of them representing a different entity. As you can see above, how the image turned into two segments, one represents the cat and the other background. Image segmentation is useful in many fields from self-driving cars to satellites. Perhaps the most important of them all is medical imaging. The subtleties in medical images are quite complex and sometimes even challenging for trained physicians. A machine that can understand these nuances and can identify necessary areas can make a profound impact in medical care. Convolutional Neural Networks gave decent results in easier image segmentation problems but it hasn't made any good progress on complex ones. That’s where UNet comes in the picture. UNet was first designed especially for medical image segmentation. It showed such good results that it used in many other fields after. In this article, we’ll talk about why and how UNet works. If you don’t know intuition behind CNN, please read this first. You can check out UNet in action here. The main idea behind CNN is to learn the feature mapping of an image and exploit it to make more nuanced feature mapping. This works well in classification problems as the image is converted into a vector which used further for classification. But in image segmentation, we not only need to convert feature map into a vector but also reconstruct an image from this vector. This is a mammoth task because it’s a lot tougher to convert a vector into an image than vice versa. The whole idea of UNet is revolved around this problem. While converting an image into a vector, we already learned the feature mapping of the image so why not use the same mapping to convert it again to image. This is the recipe behind UNet. Use the same feature maps that are used for contraction to expand a vector to a segmented image. This would preserve the structural integrity of the image which would reduce distortion enormously. Let’s understand the architecture more briefly. The architecture looks like a ‘U’ which justifies its name. This architecture consists of three sections: The contraction, The bottleneck, and the expansion section. The contraction section is made of many contraction blocks. Each block takes an input applies two 3X3 convolution layers followed by a 2X2 max pooling. The number of kernels or feature maps after each block doubles so that architecture can learn the complex structures effectively. The bottommost layer mediates between the contraction layer and the expansion layer. It uses two 3X3 CNN layers followed by 2X2 up convolution layer. But the heart of this architecture lies in the expansion section. Similar to contraction layer, it also consists of several expansion blocks. Each block passes the input to two 3X3 CNN layers followed by a 2X2 upsampling layer. Also after each block number of feature maps used by convolutional layer get half to maintain symmetry. However, every time the input is also get appended by feature maps of the corresponding contraction layer. This action would ensure that the features that are learned while contracting the image will be used to reconstruct it. The number of expansion blocks is as same as the number of contraction block. After that, the resultant mapping passes through another 3X3 CNN layer with the number of feature maps equal to the number of segments desired. What kind of loss one would use in such an intrinsic image segmentation? Well, it is defined simply in the paper itself. The energy function is computed by a pixel-wise soft-max over the final feature map combined with the cross-entropy loss function UNet uses a rather novel loss weighting scheme for each pixel such that there is a higher weight at the border of segmented objects. This loss weighting scheme helped the U-Net model segment cells in biomedical images in a discontinuous fashion such that individual cells may be easily identified within the binary segmentation map. First of all pixel-wise softmax applied on the resultant image which is followed by cross-entropy loss function. So we are classifying each pixel into one of the classes. The idea is that even in segmentation every pixel have to lie in some category and we just need to make sure that they do. So we just converted a segmentation problem into a multiclass classification one and it performed very well as compared to the traditional loss functions. I implemented the UNet model using Pytorch framework. You can check out the UNet module here. Images for segmentation of optical coherence tomography images with diabetic macular edema are used. You can checkout UNet in action here. The UNet module in the above code represents the whole architecture of UNet. contraction_block and expansive_block are used to create the contraction section and the expansion section respectively. The function crop_and_concat appends the output of contraction layer with the new expansion layer input. The training part can be written as unet = Unet(in_channel=1,out_channel=2)#out_channel represents number of segments desiredcriterion = torch.nn.CrossEntropyLoss()optimizer = torch.optim.SGD(unet.parameters(), lr = 0.01, momentum=0.99)optimizer.zero_grad() outputs = unet(inputs)# permute such that number of desired segments would be on 4th dimensionoutputs = outputs.permute(0, 2, 3, 1)m = outputs.shape[0]# Resizing the outputs and label to caculate pixel wise softmax lossoutputs = outputs.resize(m*width_out*height_out, 2)labels = labels.resize(m*width_out*height_out)loss = criterion(outputs, labels)loss.backward()optimizer.step() Image segmentation is an important problem and every day some new research papers are published. UNet contributed significantly in such research. Many new architectures are inspired by UNet. But still, there is so much to explore. There are so many variants of this architecture in the industry and hence it is necessary to understand the first one to understand them better. So if you have any doubts please comment below or refer to the resources page. UNet original paper UNet Pytorch implementation UNet Tensorflow implementation More about Semantic Segmentation Practical Image Segmentation This tutorial is the second article in my series of DeepResearch articles. If you like this tutorial please let me know in comments and if you don’t please let me know in comments more briefly. If you have any doubts or any criticism just flood the comments with it. I’ll reply as soon as I can. If you like this tutorial please share it with your peers.
[ { "code": null, "e": 945, "s": 172, "text": "Vision is one of the most important senses humans possess. But have you ever wondered about the complexity of the task? The ability to capture the reflected light rays and get meaning out of it is a very convoluted task and yet we do it so easily. We developed it due to millions of years of evolution. So how can we give machines the same ability in a very small period of time? For computers, these images are nothing but matrices and understanding the nuances behind these matrices has been an obsession for many mathematicians for years. But after the emergence of artificial intelligence and particularly CNN architectures, the research has made progress like never before. Many problems which are previously considered untouchable are now showing astounding results." }, { "code": null, "e": 1122, "s": 945, "text": "One such problem is the image segmentation. In Image Segmentation, the machine has to partition the image into different segments, each of them representing a different entity." }, { "code": null, "e": 1601, "s": 1122, "text": "As you can see above, how the image turned into two segments, one represents the cat and the other background. Image segmentation is useful in many fields from self-driving cars to satellites. Perhaps the most important of them all is medical imaging. The subtleties in medical images are quite complex and sometimes even challenging for trained physicians. A machine that can understand these nuances and can identify necessary areas can make a profound impact in medical care." }, { "code": null, "e": 2080, "s": 1601, "text": "Convolutional Neural Networks gave decent results in easier image segmentation problems but it hasn't made any good progress on complex ones. That’s where UNet comes in the picture. UNet was first designed especially for medical image segmentation. It showed such good results that it used in many other fields after. In this article, we’ll talk about why and how UNet works. If you don’t know intuition behind CNN, please read this first. You can check out UNet in action here." }, { "code": null, "e": 2610, "s": 2080, "text": "The main idea behind CNN is to learn the feature mapping of an image and exploit it to make more nuanced feature mapping. This works well in classification problems as the image is converted into a vector which used further for classification. But in image segmentation, we not only need to convert feature map into a vector but also reconstruct an image from this vector. This is a mammoth task because it’s a lot tougher to convert a vector into an image than vice versa. The whole idea of UNet is revolved around this problem." }, { "code": null, "e": 3042, "s": 2610, "text": "While converting an image into a vector, we already learned the feature mapping of the image so why not use the same mapping to convert it again to image. This is the recipe behind UNet. Use the same feature maps that are used for contraction to expand a vector to a segmented image. This would preserve the structural integrity of the image which would reduce distortion enormously. Let’s understand the architecture more briefly." }, { "code": null, "e": 3640, "s": 3042, "text": "The architecture looks like a ‘U’ which justifies its name. This architecture consists of three sections: The contraction, The bottleneck, and the expansion section. The contraction section is made of many contraction blocks. Each block takes an input applies two 3X3 convolution layers followed by a 2X2 max pooling. The number of kernels or feature maps after each block doubles so that architecture can learn the complex structures effectively. The bottommost layer mediates between the contraction layer and the expansion layer. It uses two 3X3 CNN layers followed by 2X2 up convolution layer." }, { "code": null, "e": 4421, "s": 3640, "text": "But the heart of this architecture lies in the expansion section. Similar to contraction layer, it also consists of several expansion blocks. Each block passes the input to two 3X3 CNN layers followed by a 2X2 upsampling layer. Also after each block number of feature maps used by convolutional layer get half to maintain symmetry. However, every time the input is also get appended by feature maps of the corresponding contraction layer. This action would ensure that the features that are learned while contracting the image will be used to reconstruct it. The number of expansion blocks is as same as the number of contraction block. After that, the resultant mapping passes through another 3X3 CNN layer with the number of feature maps equal to the number of segments desired." }, { "code": null, "e": 4542, "s": 4421, "text": "What kind of loss one would use in such an intrinsic image segmentation? Well, it is defined simply in the paper itself." }, { "code": null, "e": 4672, "s": 4542, "text": "The energy function is computed by a pixel-wise soft-max over the final feature map combined with the cross-entropy loss function" }, { "code": null, "e": 5005, "s": 4672, "text": "UNet uses a rather novel loss weighting scheme for each pixel such that there is a higher weight at the border of segmented objects. This loss weighting scheme helped the U-Net model segment cells in biomedical images in a discontinuous fashion such that individual cells may be easily identified within the binary segmentation map." }, { "code": null, "e": 5454, "s": 5005, "text": "First of all pixel-wise softmax applied on the resultant image which is followed by cross-entropy loss function. So we are classifying each pixel into one of the classes. The idea is that even in segmentation every pixel have to lie in some category and we just need to make sure that they do. So we just converted a segmentation problem into a multiclass classification one and it performed very well as compared to the traditional loss functions." }, { "code": null, "e": 5687, "s": 5454, "text": "I implemented the UNet model using Pytorch framework. You can check out the UNet module here. Images for segmentation of optical coherence tomography images with diabetic macular edema are used. You can checkout UNet in action here." }, { "code": null, "e": 6026, "s": 5687, "text": "The UNet module in the above code represents the whole architecture of UNet. contraction_block and expansive_block are used to create the contraction section and the expansion section respectively. The function crop_and_concat appends the output of contraction layer with the new expansion layer input. The training part can be written as" }, { "code": null, "e": 6635, "s": 6026, "text": "unet = Unet(in_channel=1,out_channel=2)#out_channel represents number of segments desiredcriterion = torch.nn.CrossEntropyLoss()optimizer = torch.optim.SGD(unet.parameters(), lr = 0.01, momentum=0.99)optimizer.zero_grad() outputs = unet(inputs)# permute such that number of desired segments would be on 4th dimensionoutputs = outputs.permute(0, 2, 3, 1)m = outputs.shape[0]# Resizing the outputs and label to caculate pixel wise softmax lossoutputs = outputs.resize(m*width_out*height_out, 2)labels = labels.resize(m*width_out*height_out)loss = criterion(outputs, labels)loss.backward()optimizer.step()" }, { "code": null, "e": 7090, "s": 6635, "text": "Image segmentation is an important problem and every day some new research papers are published. UNet contributed significantly in such research. Many new architectures are inspired by UNet. But still, there is so much to explore. There are so many variants of this architecture in the industry and hence it is necessary to understand the first one to understand them better. So if you have any doubts please comment below or refer to the resources page." }, { "code": null, "e": 7110, "s": 7090, "text": "UNet original paper" }, { "code": null, "e": 7138, "s": 7110, "text": "UNet Pytorch implementation" }, { "code": null, "e": 7169, "s": 7138, "text": "UNet Tensorflow implementation" }, { "code": null, "e": 7202, "s": 7169, "text": "More about Semantic Segmentation" }, { "code": null, "e": 7231, "s": 7202, "text": "Practical Image Segmentation" } ]
Learning by Implementing: Gaussian Naive Bayes | by Dr. Robert Kübler | Towards Data Science
I think this is a classic at the beginning of each data science career: the Naive Bayes Classifier. Or I should rather say the family of naive Bayes classifiers, as they come in many flavors. For example, there is a multinomial naive Bayes, a Bernoulli naive Bayes, and also a Gaussian naive Bayes classifier, each different in only one small detail, as we will find out. The naive Bayes algorithms are quite simple in design but proved useful in many complex real-world situations. In this article, you can learn how the naive Bayes classifiers work, why it makes sense to define them the way they are and how to implement them in Python using NumPy. You can find the code on my Github. It might help a bit to check out my primer on Bayesian statistics A gentle Introduction to Bayesian Inference to get used to the Bayes formula. As we will implement the classifier in a scikit learn-conform way, it’s also worthwhile to check out my article Build your own custom scikit-learn Regression. However, the scikit-learn overhead is quite small and you should be able to follow along anyway. We will start exploring the astonishingly simple theory of naive Bayes classification and then turn to the implementation. What are we really interested in when classifying? What are we actually doing, what is the input and the output? The answer is simple: Given a data point x, what is the probability of x belonging to some class c? That’s all we want to answer with any classification. You can directly model this statement as a conditional probability: p(c|x). For example, if there are 3 classes c1, c2, c3, and x consists of 2 features x1, x2, the result of a classifier could be something like p(c1|x1, x2)=0.3, p(c2|x1, x2)=0.5 and p(c3|x1, x2)=0.2. If we care for a single label as the output, we would choose the one with the highest probability, i.e. c2 with a probability of 50% here. The naive Bayes classifier tries to compute these probabilities directly. Ok, so given a data point x, we want to compute p(c|x) for all classes c and then output the c with the highest probability. In formulas you often see this as Note: max p(c|x) returns the maximum probability while argmax p(c|x) returns the c with this highest probability. But before we can optimize p(c|x), we have to be able to compute it. For this, we use Bayes’ theorem: This is the Bayes part of naive Bayes. But now, we have the following problem: What are p(x|c) and p(c)? This is what the training of a naive Bayes classifier is all about. To illustrate everything, let us use a toy dataset with two real features x1, x2, and three classes c1, c2, c3 in the following. You can create this exact dataset via from sklearn.datasets import make_blobsX, y = make_blobs(n_samples=20, centers=[(0,0), (5,5), (-5, 5)], random_state=0) Let us start with the class probability p(c), the probability that some class c is observed in the labeled dataset. The simplest way to estimate this is to just compute the relative frequencies of the classes and use them as the probabilities. We can use our dataset to see what this means exactly. There are 7 out of 20 points labeled class c1 (blue) in the dataset, therefore we say p(c1)=7/20. We have 7 points for class c2 (red) as well, therefore we set p(c2)=7/20. The last class c3 (yellow) has only 6 points, hence p(c3)=6/20. This simple calculation of the class probabilities resembles a maximum likelihood approach. You can, however, also use another prior distribution, if you like. For example, if you know that this dataset is not representative of the true population because class c3 should appear in 50% of the cases, then you set p(c1)=0.25, p(c2)=0.25 and p(c3)=0.5. Whatever helps you improving the performance on the test set. We now turn to the likelihood p(x|c)=p(x1, x2|c). One approach to calculate this likelihood is to filter the dataset for samples with label c and then try to find a distribution (e.g. a 2-dimensional Gaussian) that captures the features x1, x2. Unfortunately, usually, we don’t have enough samples per class to do a proper estimation of the likelihood. To be able to build a more robust model, we make the naive assumption that the features x1, x2 are stochastically independent, given c. This is just a fancy way of making the math easier via for every class c. This is where the naive part of naive Bayes comes from because this equation does not hold in general. Still, even then the naive Bayes yields good, sometimes outstanding results in practice. Especially for NLP problems with bag-of-words features, the multinomial naive Bayes shines. The arguments given above are the same for any naive Bayes classifier you can find. Now it just depends on how you model p(x1|c1), p(x2|c1), p(x1|c2), p(x2|c2), p(x1|c3) and p(x2|c3). If your features are 0 and 1 only, you could use a Bernoulli distribution. If they are integers, a Multinomial distribution. However, we have real feature values and decide for a Gaussian distribution, hence the name Gaussian naive Bayes. We assume the following form where μi,j is the mean and σi,j is the standard deviation that we have to estimate from the data. This means that we get one mean for each feature i coupled with a class cj, in our case 2*3=6 means. The same goes for the standard deviations. This calls for an example. Let us try to estimate μ2,1 and σ2,1. Because j=1, we are only interested in class c1, let us only keep samples with this label. The following samples remain: # samples with label = c_1array([[ 0.14404357, 1.45427351], [ 0.97873798, 2.2408932 ], [ 1.86755799, -0.97727788], [ 1.76405235, 0.40015721], [ 0.76103773, 0.12167502], [-0.10321885, 0.4105985 ], [ 0.95008842, -0.15135721]]) Now, because of i=2 we only have to consider the second column. μ2,1 is the mean and σ2,1 the standard deviation for this column, i.e. μ2,1=0.49985176 and σ2,1=0.9789976. These numbers make sense if you look at the scatter plot from above again. The features x2 of the samples from class c1 are around 0.5, as you can see from the picture. We compute this now for the other five combinations and we are done! 😃 In Python, you can do it like this: from sklearn.datasets import make_blobsimport numpy as np# Create the data. The classes are c_1=0, c_2=1 and c_3=2.X, y = make_blobs(n_samples=20, centers=[(0,0), (5,5), (-5, 5)], random_state=0)# The class probabilities.# np.bincounts counts the occurence of each label.prior = np.bincount(y) / len(y)# np.where(y==i) returns all indices where the y==i.# This is the filtering step.means = np.array([X[np.where(y==i)].mean(axis=0) for i in range(3)])stds = np.array([X[np.where(y==i)].std(axis=0) for i in range(3)]) We receive # priorsarray([0.35, 0.35, 0.3 ])# means array([[ 0.90889988, 0.49985176], [ 5.4111385 , 4.6491892 ], [-4.7841679 , 5.15385848]])# stdsarray([[0.6853714 , 0.9789976 ], [1.40218915, 0.67078568], [0.88192625, 1.12879666]]) This is the result of the training of a Gaussian naive Bayes classifier. The complete prediction formula is Let’s assume a new data point x*=(-2, 5) comes in. To see which class it belongs to, let us compute p(c|x*) for all classes. From the picture, it should belong to class c3=2, but let’s see. Let us ignore the denominator p(x) for a second. Using the following loop computed the nominators for j=1, 2, 3. x_new = np.array([-2, 5])for j in range(3): print(f'Probability for class {j}: {(1/np.sqrt(2*np.pi*stds[j]**2)*np.exp(-0.5*((x_new-means[j])/stds[j])**2)).prod()*p[j]:.12f}') We receive Probability for class 0: 0.000000000263Probability for class 1: 0.000000044359Probability for class 2: 0.000325643718 Of course, these probabilities (we shouldn’t call them that way) don’t add up to one since we ignored the denominator. However, this is no problem since we can just take these unnormalized probabilities and divide them by their sum, then they will add up to one. So, dividing these three values by their sum of about 0.00032569, we get A clear winner, as we expected. Now, let us implement it! This implementation is by far not efficient, not numerically stable, it only serves an educational purpose. We have discussed most of the things, so it should be easy to follow along now. You can ignore all the check functions, or read my article Build your own custom scikit-learn if you are interested in what they exactly do. Just note that I implemented a predict_proba method first to compute probabilities. The method predict just calls this method and returns the index (=class) with the highest probability using an argmax function (there it is again!). The class awaits classes from 0 to k-1, where k is the number of classes. import numpy as npfrom sklearn.base import BaseEstimator, ClassifierMixinfrom sklearn.utils.validation import check_X_y, check_array, check_is_fittedclass GaussianNaiveBayesClassifier(BaseEstimator, ClassifierMixin): def fit(self, X, y): X, y = check_X_y(X, y) self.priors_ = np.bincount(y) / len(y) self.n_classes_ = np.max(y) + 1 self.means_ = np.array([X[np.where(y==i)].mean(axis=0) for i in range(self.n_classes_)]) self.stds_ = np.array([X[np.where(y==i)].std(axis=0) for i in range(self.n_classes_)]) return self def predict_proba(self, X): check_is_fitted(self) X = check_array(X) res = [] for i in range(len(X)): probas = [] for j in range(self.n_classes_): probas.append((1/np.sqrt(2*np.pi*self.stds_[j]**2)*np.exp(-0.5*((X[i]-self.means_[j])/self.stds_[j])**2)).prod()*self.priors_[j]) probas = np.array(probas) res.append(probas / probas.sum()) return np.array(res) def predict(self, X): check_is_fitted(self) X = check_array(X) res = self.predict_proba(X) return res.argmax(axis=1) While the code is quite short it is still too long to be completely sure that we didn’t do any mistakes. So, let us check how it fares against the scikit-learn GaussianNB classifier. my_gauss = GaussianNaiveBayesClassifier()my_gauss.fit(X, y)my_gauss.predict_proba([[-2, 5], [0,0], [6, -0.3]]) outputs array([[8.06313823e-07, 1.36201957e-04, 9.99862992e-01], [1.00000000e+00, 4.23258691e-14, 1.92051255e-11], [4.30879705e-01, 5.69120295e-01, 9.66618838e-27]]) The predictions using the predict method are # my_gauss.predict([[-2, 5], [0,0], [6, -0.3]])array([2, 0, 1]) Now, let us use scikit-learn. Throwing in some code from sklearn.naive_bayes import GaussianNBgnb = GaussianNB()gnb.fit(X, y)gnb.predict_proba([[-2, 5], [0,0], [6, -0.3]]) yields array([[8.06314158e-07, 1.36201959e-04, 9.99862992e-01], [1.00000000e+00, 4.23259111e-14, 1.92051343e-11], [4.30879698e-01, 5.69120302e-01, 9.66619630e-27]]) The numbers look kind of similar to the ones of our classifier, but they are a little bit off in the last few displayed digits. Did we do anything wrong? No. The scikit-learn version just merely uses another hyperparameter var_smoothing=1e-09 . If we set this one to zero, we get exactly our numbers. Perfect! Have a look at the decision regions of our classifier. I also marked the three points we used for testing. That one point close to the border has only a 56.9% chance to belong to the red class, as you can see from the predict_proba outputs. The other two points are classified with much higher confidence. In this article, we have learned how the Gaussian naive Bayes classifier works and gave an intuition on why it was designed that way — it is a direct approach to model the probability of interest. Compare this with Logistic regression: there, the probability is modeled using a linear function with a sigmoid function applied on top of it. It’s still an easy model, but it does not feel as natural as a naive Bayes classifier. We continued by calculating a few examples and collecting some useful pieces of code on the way. Finally, we have implemented a complete Gaussian naive Bayes classifier in a way that works well with scikit-learn. That means you can use it in pipelines or grid search, for example. In the end, we did a small sanity check by importing scikit-learns own Gaussian naive Bayes classifier and testing if both, our and scikit-learn’s classifier yield the same result. This test was successful. 😎 I hope that you learned something new, interesting, and useful today. Thanks for reading! As the last point, if you want to support me in writing more about machine learning andplan to get a Medium subscription anyway, want to support me in writing more about machine learning and plan to get a Medium subscription anyway, why not do it via this link? This would help me a lot! 😊 To be transparent, the price for you does not change, but about half of the subscription fees go directly to me. Thanks a lot, if you consider supporting me! If you have any questions, write me on LinkedIn!
[ { "code": null, "e": 654, "s": 171, "text": "I think this is a classic at the beginning of each data science career: the Naive Bayes Classifier. Or I should rather say the family of naive Bayes classifiers, as they come in many flavors. For example, there is a multinomial naive Bayes, a Bernoulli naive Bayes, and also a Gaussian naive Bayes classifier, each different in only one small detail, as we will find out. The naive Bayes algorithms are quite simple in design but proved useful in many complex real-world situations." }, { "code": null, "e": 685, "s": 654, "text": "In this article, you can learn" }, { "code": null, "e": 723, "s": 685, "text": "how the naive Bayes classifiers work," }, { "code": null, "e": 778, "s": 723, "text": "why it makes sense to define them the way they are and" }, { "code": null, "e": 823, "s": 778, "text": "how to implement them in Python using NumPy." }, { "code": null, "e": 859, "s": 823, "text": "You can find the code on my Github." }, { "code": null, "e": 1259, "s": 859, "text": "It might help a bit to check out my primer on Bayesian statistics A gentle Introduction to Bayesian Inference to get used to the Bayes formula. As we will implement the classifier in a scikit learn-conform way, it’s also worthwhile to check out my article Build your own custom scikit-learn Regression. However, the scikit-learn overhead is quite small and you should be able to follow along anyway." }, { "code": null, "e": 1382, "s": 1259, "text": "We will start exploring the astonishingly simple theory of naive Bayes classification and then turn to the implementation." }, { "code": null, "e": 1517, "s": 1382, "text": "What are we really interested in when classifying? What are we actually doing, what is the input and the output? The answer is simple:" }, { "code": null, "e": 1595, "s": 1517, "text": "Given a data point x, what is the probability of x belonging to some class c?" }, { "code": null, "e": 1725, "s": 1595, "text": "That’s all we want to answer with any classification. You can directly model this statement as a conditional probability: p(c|x)." }, { "code": null, "e": 1751, "s": 1725, "text": "For example, if there are" }, { "code": null, "e": 1777, "s": 1751, "text": "3 classes c1, c2, c3, and" }, { "code": null, "e": 1810, "s": 1777, "text": "x consists of 2 features x1, x2," }, { "code": null, "e": 2057, "s": 1810, "text": "the result of a classifier could be something like p(c1|x1, x2)=0.3, p(c2|x1, x2)=0.5 and p(c3|x1, x2)=0.2. If we care for a single label as the output, we would choose the one with the highest probability, i.e. c2 with a probability of 50% here." }, { "code": null, "e": 2131, "s": 2057, "text": "The naive Bayes classifier tries to compute these probabilities directly." }, { "code": null, "e": 2290, "s": 2131, "text": "Ok, so given a data point x, we want to compute p(c|x) for all classes c and then output the c with the highest probability. In formulas you often see this as" }, { "code": null, "e": 2404, "s": 2290, "text": "Note: max p(c|x) returns the maximum probability while argmax p(c|x) returns the c with this highest probability." }, { "code": null, "e": 2506, "s": 2404, "text": "But before we can optimize p(c|x), we have to be able to compute it. For this, we use Bayes’ theorem:" }, { "code": null, "e": 2611, "s": 2506, "text": "This is the Bayes part of naive Bayes. But now, we have the following problem: What are p(x|c) and p(c)?" }, { "code": null, "e": 2679, "s": 2611, "text": "This is what the training of a naive Bayes classifier is all about." }, { "code": null, "e": 2808, "s": 2679, "text": "To illustrate everything, let us use a toy dataset with two real features x1, x2, and three classes c1, c2, c3 in the following." }, { "code": null, "e": 2846, "s": 2808, "text": "You can create this exact dataset via" }, { "code": null, "e": 2966, "s": 2846, "text": "from sklearn.datasets import make_blobsX, y = make_blobs(n_samples=20, centers=[(0,0), (5,5), (-5, 5)], random_state=0)" }, { "code": null, "e": 3265, "s": 2966, "text": "Let us start with the class probability p(c), the probability that some class c is observed in the labeled dataset. The simplest way to estimate this is to just compute the relative frequencies of the classes and use them as the probabilities. We can use our dataset to see what this means exactly." }, { "code": null, "e": 3501, "s": 3265, "text": "There are 7 out of 20 points labeled class c1 (blue) in the dataset, therefore we say p(c1)=7/20. We have 7 points for class c2 (red) as well, therefore we set p(c2)=7/20. The last class c3 (yellow) has only 6 points, hence p(c3)=6/20." }, { "code": null, "e": 3914, "s": 3501, "text": "This simple calculation of the class probabilities resembles a maximum likelihood approach. You can, however, also use another prior distribution, if you like. For example, if you know that this dataset is not representative of the true population because class c3 should appear in 50% of the cases, then you set p(c1)=0.25, p(c2)=0.25 and p(c3)=0.5. Whatever helps you improving the performance on the test set." }, { "code": null, "e": 4159, "s": 3914, "text": "We now turn to the likelihood p(x|c)=p(x1, x2|c). One approach to calculate this likelihood is to filter the dataset for samples with label c and then try to find a distribution (e.g. a 2-dimensional Gaussian) that captures the features x1, x2." }, { "code": null, "e": 4267, "s": 4159, "text": "Unfortunately, usually, we don’t have enough samples per class to do a proper estimation of the likelihood." }, { "code": null, "e": 4458, "s": 4267, "text": "To be able to build a more robust model, we make the naive assumption that the features x1, x2 are stochastically independent, given c. This is just a fancy way of making the math easier via" }, { "code": null, "e": 4761, "s": 4458, "text": "for every class c. This is where the naive part of naive Bayes comes from because this equation does not hold in general. Still, even then the naive Bayes yields good, sometimes outstanding results in practice. Especially for NLP problems with bag-of-words features, the multinomial naive Bayes shines." }, { "code": null, "e": 4945, "s": 4761, "text": "The arguments given above are the same for any naive Bayes classifier you can find. Now it just depends on how you model p(x1|c1), p(x2|c1), p(x1|c2), p(x2|c2), p(x1|c3) and p(x2|c3)." }, { "code": null, "e": 5213, "s": 4945, "text": "If your features are 0 and 1 only, you could use a Bernoulli distribution. If they are integers, a Multinomial distribution. However, we have real feature values and decide for a Gaussian distribution, hence the name Gaussian naive Bayes. We assume the following form" }, { "code": null, "e": 5482, "s": 5213, "text": "where μi,j is the mean and σi,j is the standard deviation that we have to estimate from the data. This means that we get one mean for each feature i coupled with a class cj, in our case 2*3=6 means. The same goes for the standard deviations. This calls for an example." }, { "code": null, "e": 5641, "s": 5482, "text": "Let us try to estimate μ2,1 and σ2,1. Because j=1, we are only interested in class c1, let us only keep samples with this label. The following samples remain:" }, { "code": null, "e": 5907, "s": 5641, "text": "# samples with label = c_1array([[ 0.14404357, 1.45427351], [ 0.97873798, 2.2408932 ], [ 1.86755799, -0.97727788], [ 1.76405235, 0.40015721], [ 0.76103773, 0.12167502], [-0.10321885, 0.4105985 ], [ 0.95008842, -0.15135721]])" }, { "code": null, "e": 6078, "s": 5907, "text": "Now, because of i=2 we only have to consider the second column. μ2,1 is the mean and σ2,1 the standard deviation for this column, i.e. μ2,1=0.49985176 and σ2,1=0.9789976." }, { "code": null, "e": 6247, "s": 6078, "text": "These numbers make sense if you look at the scatter plot from above again. The features x2 of the samples from class c1 are around 0.5, as you can see from the picture." }, { "code": null, "e": 6318, "s": 6247, "text": "We compute this now for the other five combinations and we are done! 😃" }, { "code": null, "e": 6354, "s": 6318, "text": "In Python, you can do it like this:" }, { "code": null, "e": 6872, "s": 6354, "text": "from sklearn.datasets import make_blobsimport numpy as np# Create the data. The classes are c_1=0, c_2=1 and c_3=2.X, y = make_blobs(n_samples=20, centers=[(0,0), (5,5), (-5, 5)], random_state=0)# The class probabilities.# np.bincounts counts the occurence of each label.prior = np.bincount(y) / len(y)# np.where(y==i) returns all indices where the y==i.# This is the filtering step.means = np.array([X[np.where(y==i)].mean(axis=0) for i in range(3)])stds = np.array([X[np.where(y==i)].std(axis=0) for i in range(3)])" }, { "code": null, "e": 6883, "s": 6872, "text": "We receive" }, { "code": null, "e": 7131, "s": 6883, "text": "# priorsarray([0.35, 0.35, 0.3 ])# means array([[ 0.90889988, 0.49985176], [ 5.4111385 , 4.6491892 ], [-4.7841679 , 5.15385848]])# stdsarray([[0.6853714 , 0.9789976 ], [1.40218915, 0.67078568], [0.88192625, 1.12879666]])" }, { "code": null, "e": 7204, "s": 7131, "text": "This is the result of the training of a Gaussian naive Bayes classifier." }, { "code": null, "e": 7239, "s": 7204, "text": "The complete prediction formula is" }, { "code": null, "e": 7290, "s": 7239, "text": "Let’s assume a new data point x*=(-2, 5) comes in." }, { "code": null, "e": 7542, "s": 7290, "text": "To see which class it belongs to, let us compute p(c|x*) for all classes. From the picture, it should belong to class c3=2, but let’s see. Let us ignore the denominator p(x) for a second. Using the following loop computed the nominators for j=1, 2, 3." }, { "code": null, "e": 7720, "s": 7542, "text": "x_new = np.array([-2, 5])for j in range(3): print(f'Probability for class {j}: {(1/np.sqrt(2*np.pi*stds[j]**2)*np.exp(-0.5*((x_new-means[j])/stds[j])**2)).prod()*p[j]:.12f}')" }, { "code": null, "e": 7731, "s": 7720, "text": "We receive" }, { "code": null, "e": 7849, "s": 7731, "text": "Probability for class 0: 0.000000000263Probability for class 1: 0.000000044359Probability for class 2: 0.000325643718" }, { "code": null, "e": 8185, "s": 7849, "text": "Of course, these probabilities (we shouldn’t call them that way) don’t add up to one since we ignored the denominator. However, this is no problem since we can just take these unnormalized probabilities and divide them by their sum, then they will add up to one. So, dividing these three values by their sum of about 0.00032569, we get" }, { "code": null, "e": 8243, "s": 8185, "text": "A clear winner, as we expected. Now, let us implement it!" }, { "code": null, "e": 8572, "s": 8243, "text": "This implementation is by far not efficient, not numerically stable, it only serves an educational purpose. We have discussed most of the things, so it should be easy to follow along now. You can ignore all the check functions, or read my article Build your own custom scikit-learn if you are interested in what they exactly do." }, { "code": null, "e": 8879, "s": 8572, "text": "Just note that I implemented a predict_proba method first to compute probabilities. The method predict just calls this method and returns the index (=class) with the highest probability using an argmax function (there it is again!). The class awaits classes from 0 to k-1, where k is the number of classes." }, { "code": null, "e": 10123, "s": 8879, "text": "import numpy as npfrom sklearn.base import BaseEstimator, ClassifierMixinfrom sklearn.utils.validation import check_X_y, check_array, check_is_fittedclass GaussianNaiveBayesClassifier(BaseEstimator, ClassifierMixin): def fit(self, X, y): X, y = check_X_y(X, y) self.priors_ = np.bincount(y) / len(y) self.n_classes_ = np.max(y) + 1 self.means_ = np.array([X[np.where(y==i)].mean(axis=0) for i in range(self.n_classes_)]) self.stds_ = np.array([X[np.where(y==i)].std(axis=0) for i in range(self.n_classes_)]) return self def predict_proba(self, X): check_is_fitted(self) X = check_array(X) res = [] for i in range(len(X)): probas = [] for j in range(self.n_classes_): probas.append((1/np.sqrt(2*np.pi*self.stds_[j]**2)*np.exp(-0.5*((X[i]-self.means_[j])/self.stds_[j])**2)).prod()*self.priors_[j]) probas = np.array(probas) res.append(probas / probas.sum()) return np.array(res) def predict(self, X): check_is_fitted(self) X = check_array(X) res = self.predict_proba(X) return res.argmax(axis=1)" }, { "code": null, "e": 10306, "s": 10123, "text": "While the code is quite short it is still too long to be completely sure that we didn’t do any mistakes. So, let us check how it fares against the scikit-learn GaussianNB classifier." }, { "code": null, "e": 10417, "s": 10306, "text": "my_gauss = GaussianNaiveBayesClassifier()my_gauss.fit(X, y)my_gauss.predict_proba([[-2, 5], [0,0], [6, -0.3]])" }, { "code": null, "e": 10425, "s": 10417, "text": "outputs" }, { "code": null, "e": 10595, "s": 10425, "text": "array([[8.06313823e-07, 1.36201957e-04, 9.99862992e-01], [1.00000000e+00, 4.23258691e-14, 1.92051255e-11], [4.30879705e-01, 5.69120295e-01, 9.66618838e-27]])" }, { "code": null, "e": 10640, "s": 10595, "text": "The predictions using the predict method are" }, { "code": null, "e": 10704, "s": 10640, "text": "# my_gauss.predict([[-2, 5], [0,0], [6, -0.3]])array([2, 0, 1])" }, { "code": null, "e": 10756, "s": 10704, "text": "Now, let us use scikit-learn. Throwing in some code" }, { "code": null, "e": 10876, "s": 10756, "text": "from sklearn.naive_bayes import GaussianNBgnb = GaussianNB()gnb.fit(X, y)gnb.predict_proba([[-2, 5], [0,0], [6, -0.3]])" }, { "code": null, "e": 10883, "s": 10876, "text": "yields" }, { "code": null, "e": 11053, "s": 10883, "text": "array([[8.06314158e-07, 1.36201959e-04, 9.99862992e-01], [1.00000000e+00, 4.23259111e-14, 1.92051343e-11], [4.30879698e-01, 5.69120302e-01, 9.66619630e-27]])" }, { "code": null, "e": 11363, "s": 11053, "text": "The numbers look kind of similar to the ones of our classifier, but they are a little bit off in the last few displayed digits. Did we do anything wrong? No. The scikit-learn version just merely uses another hyperparameter var_smoothing=1e-09 . If we set this one to zero, we get exactly our numbers. Perfect!" }, { "code": null, "e": 11669, "s": 11363, "text": "Have a look at the decision regions of our classifier. I also marked the three points we used for testing. That one point close to the border has only a 56.9% chance to belong to the red class, as you can see from the predict_proba outputs. The other two points are classified with much higher confidence." }, { "code": null, "e": 12096, "s": 11669, "text": "In this article, we have learned how the Gaussian naive Bayes classifier works and gave an intuition on why it was designed that way — it is a direct approach to model the probability of interest. Compare this with Logistic regression: there, the probability is modeled using a linear function with a sigmoid function applied on top of it. It’s still an easy model, but it does not feel as natural as a naive Bayes classifier." }, { "code": null, "e": 12377, "s": 12096, "text": "We continued by calculating a few examples and collecting some useful pieces of code on the way. Finally, we have implemented a complete Gaussian naive Bayes classifier in a way that works well with scikit-learn. That means you can use it in pipelines or grid search, for example." }, { "code": null, "e": 12586, "s": 12377, "text": "In the end, we did a small sanity check by importing scikit-learns own Gaussian naive Bayes classifier and testing if both, our and scikit-learn’s classifier yield the same result. This test was successful. 😎" }, { "code": null, "e": 12676, "s": 12586, "text": "I hope that you learned something new, interesting, and useful today. Thanks for reading!" }, { "code": null, "e": 12702, "s": 12676, "text": "As the last point, if you" }, { "code": null, "e": 12805, "s": 12702, "text": "want to support me in writing more about machine learning andplan to get a Medium subscription anyway," }, { "code": null, "e": 12867, "s": 12805, "text": "want to support me in writing more about machine learning and" }, { "code": null, "e": 12909, "s": 12867, "text": "plan to get a Medium subscription anyway," }, { "code": null, "e": 12966, "s": 12909, "text": "why not do it via this link? This would help me a lot! 😊" }, { "code": null, "e": 13079, "s": 12966, "text": "To be transparent, the price for you does not change, but about half of the subscription fees go directly to me." }, { "code": null, "e": 13124, "s": 13079, "text": "Thanks a lot, if you consider supporting me!" } ]
Create Hoverable Buttons with CSS
Use the CSS :hover selector to create hoverable buttons. You can try to run the following code to create hoverable buttons: Live Demo <!DOCTYPE html> <html> <head> <style> .btn { background-color: yellow; color: black; text-align: center; font-size: 15px; padding: 20px; border-radius: 15px; border: 3px dashed blue; } .btn:hover { background-color: orange; color: black; border: 3px solid blue; } </style> </head> <body> <h2>Result</h2> <p>Click below for result:</p> <button class = "btn">Result</button> </body> </html>
[ { "code": null, "e": 1186, "s": 1062, "text": "Use the CSS :hover selector to create hoverable buttons. You can try to run the following code to create hoverable buttons:" }, { "code": null, "e": 1196, "s": 1186, "text": "Live Demo" }, { "code": null, "e": 1783, "s": 1196, "text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n .btn {\n background-color: yellow;\n color: black;\n text-align: center;\n font-size: 15px;\n padding: 20px;\n border-radius: 15px;\n border: 3px dashed blue;\n }\n .btn:hover {\n background-color: orange;\n color: black;\n border: 3px solid blue;\n }\n </style>\n </head>\n <body>\n <h2>Result</h2>\n <p>Click below for result:</p>\n <button class = \"btn\">Result</button>\n </body>\n</html>" } ]
Example of createSignalingChannel() in HTML5
Web RTC required peer-to-peer communication between browsers. This mechanism required signalling, network information, session control and media information. Web developers can choose different mechanism to communicate between the browsers such as SIP or XMPP or any two way communications. An example of createSignalingChannel(): var signalingChannel = createSignalingChannel(); var pc; var configuration = ...; // run start(true) to initiate a call function start(isCaller) { pc = new RTCPeerConnection(configuration); // send any ice candidates to the other peer pc.onicecandidate = function (evt) { signalingChannel.send(JSON.stringify({ "candidate": evt.candidate })); }; // once remote stream arrives, show it in the remote video element pc.onaddstream = function (evt) { remoteView.src = URL.createObjectURL(evt.stream); }; // get the local stream, show it in the local video element and send it navigator.getUserMedia({ "audio": true, "video": true }, function (stream) { selfView.src = URL.createObjectURL(stream); pc.addStream(stream); if (isCaller) pc.createOffer(gotDescription); else pc.createAnswer(pc.remoteDescription, gotDescription); function gotDescription(desc) { pc.setLocalDescription(desc); signalingChannel.send(JSON.stringify({ "sdp": desc })); } }); } signalingChannel.onmessage = function (evt) { if (!pc) start(false); var signal = JSON.parse(evt.data); if (signal.sdp) pc.setRemoteDescription(new RTCSessionDescription(signal.sdp)); else pc.addIceCandidate(new RTCIceCandidate(signal.candidate)); };
[ { "code": null, "e": 1393, "s": 1062, "text": "Web RTC required peer-to-peer communication between browsers. This mechanism required signalling, network information, session control and media information. Web developers can choose different mechanism to communicate between the browsers such as SIP or XMPP or any two way communications. An example of createSignalingChannel():" }, { "code": null, "e": 2747, "s": 1393, "text": "var signalingChannel = createSignalingChannel();\nvar pc;\nvar configuration = ...;\n\n// run start(true) to initiate a call\nfunction start(isCaller) {\n pc = new RTCPeerConnection(configuration);\n // send any ice candidates to the other peer\n pc.onicecandidate = function (evt) {\n signalingChannel.send(JSON.stringify({ \"candidate\": evt.candidate }));\n };\n \n // once remote stream arrives, show it in the remote video element\n pc.onaddstream = function (evt) {\n remoteView.src = URL.createObjectURL(evt.stream);\n };\n\n // get the local stream, show it in the local video element and send it\n navigator.getUserMedia({ \"audio\": true, \"video\": true }, function (stream) {\n selfView.src = URL.createObjectURL(stream);\n pc.addStream(stream);\n if (isCaller)\n pc.createOffer(gotDescription);\n else\n pc.createAnswer(pc.remoteDescription, gotDescription);\n function gotDescription(desc) {\n pc.setLocalDescription(desc);\n signalingChannel.send(JSON.stringify({ \"sdp\": desc }));\n }\n });\n}\nsignalingChannel.onmessage = function (evt) {\n if (!pc)\n start(false);\n var signal = JSON.parse(evt.data);\n if (signal.sdp)\n pc.setRemoteDescription(new RTCSessionDescription(signal.sdp));\n else\n pc.addIceCandidate(new RTCIceCandidate(signal.candidate));\n};" } ]
Construct a binary string following the given constraints - GeeksforGeeks
08 Nov, 2021 Given three integers A, B and X. The task is to construct a binary string str which has exactly A number of 0’s and B number of 1’s provided there has to be at least X indices such that str[i] != str[i+1]. Inputs are such that there’s always a valid solution.Examples: Input: A = 2, B = 2, X = 1 Output: 1100 There are two 0’s and two 1’s and one (=X) index such that s[i] != s[i+1] (i.e. i = 1)Input: A = 4, B = 3, X = 2 Output: 0111000 Approach: Divide x by 2 and store it in a variable d. Check if d is even and d / 2 != a, if the condition is true then print 0 and decrement d and a by 1. Loop from 1 to d and print 10 and in the end update a = a – d and b = b – d. Finally print the remaining 0’s and 1’s depending on the values of a and b. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include <iostream>using namespace std; // Function to print a binary string which has// 'a' number of 0's, 'b' number of 1's and there are// at least 'x' indices such that s[i] != s[i+1]int constructBinString(int a, int b, int x){ int d, i; // Divide index value by 2 and store // it into d d = x / 2; // If index value x is even and // x/2 is not equal to a if (x % 2 == 0 && x / 2 != a) { d--; cout << 0; a--; } // Loop for d for each d print 10 for (i = 0; i < d; i++) cout << "10"; // subtract d from a and b a = a - d; b = b - d; // Loop for b to print remaining 1's for (i = 0; i < b; i++) { cout << "1"; } // Loop for a to print remaining 0's for (i = 0; i < a; i++) { cout << "0"; }} // Driver codeint main(){ int a = 4, b = 3, x = 2; constructBinString(a, b, x); return 0;} // Java implementation of the approachclass GFG{// Function to print a binary string which has// 'a' number of 0's, 'b' number of 1's and there are// at least 'x' indices such that s[i] != s[i+1]static void constructBinString(int a, int b, int x){ int d, i; // Divide index value by 2 and store // it into d d = x / 2; // If index value x is even and // x/2 is not equal to a if (x % 2 == 0 && x / 2 != a) { d--; System.out.print("0"); a--; } // Loop for d for each d print 10 for (i = 0; i < d; i++) System.out.print("10"); // subtract d from a and b a = a - d; b = b - d; // Loop for b to print remaining 1's for (i = 0; i < b; i++) { System.out.print("1"); } // Loop for a to print remaining 0's for (i = 0; i < a; i++) { System.out.print("0"); }} // Driver codepublic static void main(String[] args){ int a = 4, b = 3, x = 2; constructBinString(a, b, x);}} // This code is contributed// by Mukul Singh # Python3 implementation of the above approach # Function to print a binary string which# has 'a' number of 0's, 'b' number of 1's# and there are at least 'x' indices such# that s[i] != s[i+1]def constructBinString(a, b, x): # Divide index value by 2 and # store it into d d = x // 2 # If index value x is even and # x/2 is not equal to a if x % 2 == 0 and x // 2 != a: d -= 1 print("0", end = "") a -= 1 # Loop for d for each d print 10 for i in range(d): print("10", end = "") # subtract d from a and b a = a - d b = b - d # Loop for b to print remaining 1's for i in range(b): print("1", end = "") # Loop for a to print remaining 0's for i in range(a): print("0", end = "") # Driver Codeif __name__ == "__main__": a, b, x = 4, 3, 2 constructBinString(a, b, x) # This code is contributed by Rituraj_Jain // C# implementation of the approachusing System; class GFG{// Function to print a binary string which has// 'a' number of 0's, 'b' number of 1's and there are// at least 'x' indices such that s[i] != s[i+1]static void constructBinString(int a, int b, int x){ int d, i; // Divide index value by 2 and store // it into d d = x / 2; // If index value x is even and // x/2 is not equal to a if (x % 2 == 0 && x / 2 != a) { d--; Console.Write("0"); a--; } // Loop for d for each d print 10 for (i = 0; i < d; i++) Console.Write("10"); // subtract d from a and b a = a - d; b = b - d; // Loop for b to print remaining 1's for (i = 0; i < b; i++) { Console.Write("1"); } // Loop for a to print remaining 0's for (i = 0; i < a; i++) { Console.Write("0"); }} // Driver codepublic static void Main(){ int a = 4, b = 3, x = 2; constructBinString(a, b, x);}} // This code is contributed// by Akanksha Rai <?php// PHP implementation of the// above approach // Function to print a binary string// which has 'a' number of 0's, 'b'// number of 1's and there are at least// 'x' indices such that s[i] != s[i+1]function constructBinString($a, $b, $x){ $d; $i; // Divide index value by 2 // and store it into d $d = $x / 2; // If index value x is even and // x/2 is not equal to a if ($x % 2 == 0 && $x / 2 != $a) { $d--; echo 0; $a--; } // Loop for d for each d print 10 for ($i = 0; $i < $d; $i++) echo "10"; // subtract d from a and b $a = $a - $d; $b = $b - $d; // Loop for b to print remaining 1's for ($i = 0; $i < $b; $i++) { echo "1"; } // Loop for a to print remaining 0's for ($i = 0; $i < $a; $i++) { echo "0"; }} // Driver code$a = 4;$b = 3;$x = 2;constructBinString($a, $b, $x); // This code is contributed by ajit?> <script> // Javascript implementation of the approach // Function to print a binary string which has // 'a' number of 0's, 'b' number of 1's and there are // at least 'x' indices such that s[i] != s[i+1] function constructBinString(a, b, x) { let d, i; // Divide index value by 2 and store // it into d d = parseInt(x / 2, 10); // If index value x is even and // x/2 is not equal to a if (x % 2 == 0 && parseInt(x / 2, 10) != a) { d--; document.write("0"); a--; } // Loop for d for each d print 10 for (i = 0; i < d; i++) document.write("10"); // subtract d from a and b a = a - d; b = b - d; // Loop for b to print remaining 1's for (i = 0; i < b; i++) { document.write("1"); } // Loop for a to print remaining 0's for (i = 0; i < a; i++) { document.write("0"); } } let a = 4, b = 3, x = 2; constructBinString(a, b, x); </script> 0111000 Time Complexity: O(max(a,b,x)) Auxiliary Space: O(1) jit_t Akanksha_Rai rituraj_jain Code_Mech ManasChhabra2 mukesh07 rohan07 binary-string Constructive Algorithms Algorithms Competitive Programming Strings Strings Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments DSA Sheet by Love Babbar K means Clustering - Introduction SCAN (Elevator) Disk Scheduling Algorithms Quadratic Probing in Hashing Difference between Informed and Uninformed Search in AI Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Competitive Programming - A Complete Guide Modulo 10^9+7 (1000000007) Prefix Sum Array - Implementation and Applications in Competitive Programming
[ { "code": null, "e": 24586, "s": 24558, "text": "\n08 Nov, 2021" }, { "code": null, "e": 24857, "s": 24586, "text": "Given three integers A, B and X. The task is to construct a binary string str which has exactly A number of 0’s and B number of 1’s provided there has to be at least X indices such that str[i] != str[i+1]. Inputs are such that there’s always a valid solution.Examples: " }, { "code": null, "e": 25028, "s": 24857, "text": "Input: A = 2, B = 2, X = 1 Output: 1100 There are two 0’s and two 1’s and one (=X) index such that s[i] != s[i+1] (i.e. i = 1)Input: A = 4, B = 3, X = 2 Output: 0111000 " }, { "code": null, "e": 25042, "s": 25030, "text": "Approach: " }, { "code": null, "e": 25086, "s": 25042, "text": "Divide x by 2 and store it in a variable d." }, { "code": null, "e": 25187, "s": 25086, "text": "Check if d is even and d / 2 != a, if the condition is true then print 0 and decrement d and a by 1." }, { "code": null, "e": 25264, "s": 25187, "text": "Loop from 1 to d and print 10 and in the end update a = a – d and b = b – d." }, { "code": null, "e": 25340, "s": 25264, "text": "Finally print the remaining 0’s and 1’s depending on the values of a and b." }, { "code": null, "e": 25392, "s": 25340, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25396, "s": 25392, "text": "C++" }, { "code": null, "e": 25401, "s": 25396, "text": "Java" }, { "code": null, "e": 25409, "s": 25401, "text": "Python3" }, { "code": null, "e": 25412, "s": 25409, "text": "C#" }, { "code": null, "e": 25416, "s": 25412, "text": "PHP" }, { "code": null, "e": 25427, "s": 25416, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <iostream>using namespace std; // Function to print a binary string which has// 'a' number of 0's, 'b' number of 1's and there are// at least 'x' indices such that s[i] != s[i+1]int constructBinString(int a, int b, int x){ int d, i; // Divide index value by 2 and store // it into d d = x / 2; // If index value x is even and // x/2 is not equal to a if (x % 2 == 0 && x / 2 != a) { d--; cout << 0; a--; } // Loop for d for each d print 10 for (i = 0; i < d; i++) cout << \"10\"; // subtract d from a and b a = a - d; b = b - d; // Loop for b to print remaining 1's for (i = 0; i < b; i++) { cout << \"1\"; } // Loop for a to print remaining 0's for (i = 0; i < a; i++) { cout << \"0\"; }} // Driver codeint main(){ int a = 4, b = 3, x = 2; constructBinString(a, b, x); return 0;}", "e": 26362, "s": 25427, "text": null }, { "code": "// Java implementation of the approachclass GFG{// Function to print a binary string which has// 'a' number of 0's, 'b' number of 1's and there are// at least 'x' indices such that s[i] != s[i+1]static void constructBinString(int a, int b, int x){ int d, i; // Divide index value by 2 and store // it into d d = x / 2; // If index value x is even and // x/2 is not equal to a if (x % 2 == 0 && x / 2 != a) { d--; System.out.print(\"0\"); a--; } // Loop for d for each d print 10 for (i = 0; i < d; i++) System.out.print(\"10\"); // subtract d from a and b a = a - d; b = b - d; // Loop for b to print remaining 1's for (i = 0; i < b; i++) { System.out.print(\"1\"); } // Loop for a to print remaining 0's for (i = 0; i < a; i++) { System.out.print(\"0\"); }} // Driver codepublic static void main(String[] args){ int a = 4, b = 3, x = 2; constructBinString(a, b, x);}} // This code is contributed// by Mukul Singh", "e": 27388, "s": 26362, "text": null }, { "code": "# Python3 implementation of the above approach # Function to print a binary string which# has 'a' number of 0's, 'b' number of 1's# and there are at least 'x' indices such# that s[i] != s[i+1]def constructBinString(a, b, x): # Divide index value by 2 and # store it into d d = x // 2 # If index value x is even and # x/2 is not equal to a if x % 2 == 0 and x // 2 != a: d -= 1 print(\"0\", end = \"\") a -= 1 # Loop for d for each d print 10 for i in range(d): print(\"10\", end = \"\") # subtract d from a and b a = a - d b = b - d # Loop for b to print remaining 1's for i in range(b): print(\"1\", end = \"\") # Loop for a to print remaining 0's for i in range(a): print(\"0\", end = \"\") # Driver Codeif __name__ == \"__main__\": a, b, x = 4, 3, 2 constructBinString(a, b, x) # This code is contributed by Rituraj_Jain", "e": 28298, "s": 27388, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{// Function to print a binary string which has// 'a' number of 0's, 'b' number of 1's and there are// at least 'x' indices such that s[i] != s[i+1]static void constructBinString(int a, int b, int x){ int d, i; // Divide index value by 2 and store // it into d d = x / 2; // If index value x is even and // x/2 is not equal to a if (x % 2 == 0 && x / 2 != a) { d--; Console.Write(\"0\"); a--; } // Loop for d for each d print 10 for (i = 0; i < d; i++) Console.Write(\"10\"); // subtract d from a and b a = a - d; b = b - d; // Loop for b to print remaining 1's for (i = 0; i < b; i++) { Console.Write(\"1\"); } // Loop for a to print remaining 0's for (i = 0; i < a; i++) { Console.Write(\"0\"); }} // Driver codepublic static void Main(){ int a = 4, b = 3, x = 2; constructBinString(a, b, x);}} // This code is contributed// by Akanksha Rai", "e": 29312, "s": 28298, "text": null }, { "code": "<?php// PHP implementation of the// above approach // Function to print a binary string// which has 'a' number of 0's, 'b'// number of 1's and there are at least// 'x' indices such that s[i] != s[i+1]function constructBinString($a, $b, $x){ $d; $i; // Divide index value by 2 // and store it into d $d = $x / 2; // If index value x is even and // x/2 is not equal to a if ($x % 2 == 0 && $x / 2 != $a) { $d--; echo 0; $a--; } // Loop for d for each d print 10 for ($i = 0; $i < $d; $i++) echo \"10\"; // subtract d from a and b $a = $a - $d; $b = $b - $d; // Loop for b to print remaining 1's for ($i = 0; $i < $b; $i++) { echo \"1\"; } // Loop for a to print remaining 0's for ($i = 0; $i < $a; $i++) { echo \"0\"; }} // Driver code$a = 4;$b = 3;$x = 2;constructBinString($a, $b, $x); // This code is contributed by ajit?>", "e": 30244, "s": 29312, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to print a binary string which has // 'a' number of 0's, 'b' number of 1's and there are // at least 'x' indices such that s[i] != s[i+1] function constructBinString(a, b, x) { let d, i; // Divide index value by 2 and store // it into d d = parseInt(x / 2, 10); // If index value x is even and // x/2 is not equal to a if (x % 2 == 0 && parseInt(x / 2, 10) != a) { d--; document.write(\"0\"); a--; } // Loop for d for each d print 10 for (i = 0; i < d; i++) document.write(\"10\"); // subtract d from a and b a = a - d; b = b - d; // Loop for b to print remaining 1's for (i = 0; i < b; i++) { document.write(\"1\"); } // Loop for a to print remaining 0's for (i = 0; i < a; i++) { document.write(\"0\"); } } let a = 4, b = 3, x = 2; constructBinString(a, b, x); </script>", "e": 31343, "s": 30244, "text": null }, { "code": null, "e": 31351, "s": 31343, "text": "0111000" }, { "code": null, "e": 31384, "s": 31353, "text": "Time Complexity: O(max(a,b,x))" }, { "code": null, "e": 31406, "s": 31384, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 31412, "s": 31406, "text": "jit_t" }, { "code": null, "e": 31425, "s": 31412, "text": "Akanksha_Rai" }, { "code": null, "e": 31438, "s": 31425, "text": "rituraj_jain" }, { "code": null, "e": 31448, "s": 31438, "text": "Code_Mech" }, { "code": null, "e": 31462, "s": 31448, "text": "ManasChhabra2" }, { "code": null, "e": 31471, "s": 31462, "text": "mukesh07" }, { "code": null, "e": 31479, "s": 31471, "text": "rohan07" }, { "code": null, "e": 31493, "s": 31479, "text": "binary-string" }, { "code": null, "e": 31517, "s": 31493, "text": "Constructive Algorithms" }, { "code": null, "e": 31528, "s": 31517, "text": "Algorithms" }, { "code": null, "e": 31552, "s": 31528, "text": "Competitive Programming" }, { "code": null, "e": 31560, "s": 31552, "text": "Strings" }, { "code": null, "e": 31568, "s": 31560, "text": "Strings" }, { "code": null, "e": 31579, "s": 31568, "text": "Algorithms" }, { "code": null, "e": 31677, "s": 31579, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31686, "s": 31677, "text": "Comments" }, { "code": null, "e": 31699, "s": 31686, "text": "Old Comments" }, { "code": null, "e": 31724, "s": 31699, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 31758, "s": 31724, "text": "K means Clustering - Introduction" }, { "code": null, "e": 31801, "s": 31758, "text": "SCAN (Elevator) Disk Scheduling Algorithms" }, { "code": null, "e": 31830, "s": 31801, "text": "Quadratic Probing in Hashing" }, { "code": null, "e": 31886, "s": 31830, "text": "Difference between Informed and Uninformed Search in AI" }, { "code": null, "e": 31929, "s": 31886, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 31970, "s": 31929, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 32013, "s": 31970, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 32040, "s": 32013, "text": "Modulo 10^9+7 (1000000007)" } ]
Filters in Linux - GeeksforGeeks
13 Jul, 2021 Filters are programs that take plain text(either stored in a file or produced by another program) as standard input, transforms it into a meaningful format, and then returns it as standard output. Linux has a number of filters. Some of the most commonly used filters are explained below: 1. cat : Displays the text of the file line by line. Syntax: cat [path] 2. head : Displays the first n lines of the specified text files. If the number of lines is not specified then by default prints first 10 lines. Syntax: head [-number_of_lines_to_print] [path] 3. tail : It works the same way as head, just in reverse order. The only difference in tail is, it returns the lines from bottom to up. Syntax: tail [-number_of_lines_to_print] [path] 4. sort : Sorts the lines alphabetically by default but there are many options available to modify the sorting mechanism. Be sure to check out the main page to see everything it can do. Syntax: sort [-options] [path] 5. uniq : Removes duplicate lines. uniq has a limitation that it can only remove continuous duplicate lines(although this can be fixed by the use of piping). Assuming we have the following data. Syntax: uniq [options] [path] You can see that applying uniq doesn’t remove any duplicate lines, because uniq only removes duplicate lines which are together. When applying uniq to sorted data, it removes the duplicate lines because, after sorting data, duplicate lines come together. 6. wc : wc command gives the number of lines, words and characters in the data. Syntax: wc [-options] [path] In above image the wc gives 4 outputs as: number of lines number of words number of characters path 7. grep : grep is used to search a particular information from a text file. Syntax: grep [options] pattern [path] Below are the two ways in which we can implement grep. 8. tac : tac is just the reverse of cat and it works the same way, i.e., instead of printing from lines 1 through n, it prints lines n through 1. It is just reverse of cat command. Syntax: tac [path] 9. sed : sed stands for stream editor. It allows us to apply search and replace operation on our data effectively. sed is quite an advanced filter and all its options can be seen on its man page. Syntax: sed [path] The expression we have used above is very basic and is of the form ‘s/search/replace/g’ In the above image, we can clearly see that Scooby is replaced by Scrapy. 10. nl : nl is used to number the lines of our text data. Syntax: nl [-options] [path] It can clearly be seen in the above image that the lines have been numbered princekhj555 Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments scp command in Linux with Examples nohup Command in Linux with Examples mv command in Linux with examples chown command in Linux with Examples Docker - COPY Instruction Thread functions in C/C++ nslookup command in Linux with Examples SED command in Linux | Set 2 Named Pipe or FIFO with example C program uniq Command in LINUX with examples
[ { "code": null, "e": 24041, "s": 24013, "text": "\n13 Jul, 2021" }, { "code": null, "e": 24330, "s": 24041, "text": "Filters are programs that take plain text(either stored in a file or produced by another program) as standard input, transforms it into a meaningful format, and then returns it as standard output. Linux has a number of filters. Some of the most commonly used filters are explained below: " }, { "code": null, "e": 24384, "s": 24330, "text": "1. cat : Displays the text of the file line by line. " }, { "code": null, "e": 24394, "s": 24384, "text": "Syntax: " }, { "code": null, "e": 24405, "s": 24394, "text": "cat [path]" }, { "code": null, "e": 24551, "s": 24405, "text": "2. head : Displays the first n lines of the specified text files. If the number of lines is not specified then by default prints first 10 lines. " }, { "code": null, "e": 24561, "s": 24551, "text": "Syntax: " }, { "code": null, "e": 24602, "s": 24561, "text": "head [-number_of_lines_to_print] [path] " }, { "code": null, "e": 24739, "s": 24602, "text": "3. tail : It works the same way as head, just in reverse order. The only difference in tail is, it returns the lines from bottom to up. " }, { "code": null, "e": 24749, "s": 24739, "text": "Syntax: " }, { "code": null, "e": 24789, "s": 24749, "text": "tail [-number_of_lines_to_print] [path]" }, { "code": null, "e": 24976, "s": 24789, "text": "4. sort : Sorts the lines alphabetically by default but there are many options available to modify the sorting mechanism. Be sure to check out the main page to see everything it can do. " }, { "code": null, "e": 24985, "s": 24976, "text": "Syntax: " }, { "code": null, "e": 25008, "s": 24985, "text": "sort [-options] [path]" }, { "code": null, "e": 25204, "s": 25008, "text": "5. uniq : Removes duplicate lines. uniq has a limitation that it can only remove continuous duplicate lines(although this can be fixed by the use of piping). Assuming we have the following data. " }, { "code": null, "e": 25213, "s": 25204, "text": "Syntax: " }, { "code": null, "e": 25235, "s": 25213, "text": "uniq [options] [path]" }, { "code": null, "e": 25366, "s": 25235, "text": "You can see that applying uniq doesn’t remove any duplicate lines, because uniq only removes duplicate lines which are together. " }, { "code": null, "e": 25493, "s": 25366, "text": "When applying uniq to sorted data, it removes the duplicate lines because, after sorting data, duplicate lines come together. " }, { "code": null, "e": 25574, "s": 25493, "text": "6. wc : wc command gives the number of lines, words and characters in the data. " }, { "code": null, "e": 25583, "s": 25574, "text": "Syntax: " }, { "code": null, "e": 25604, "s": 25583, "text": "wc [-options] [path]" }, { "code": null, "e": 25648, "s": 25604, "text": "In above image the wc gives 4 outputs as: " }, { "code": null, "e": 25664, "s": 25648, "text": "number of lines" }, { "code": null, "e": 25680, "s": 25664, "text": "number of words" }, { "code": null, "e": 25701, "s": 25680, "text": "number of characters" }, { "code": null, "e": 25706, "s": 25701, "text": "path" }, { "code": null, "e": 25783, "s": 25706, "text": "7. grep : grep is used to search a particular information from a text file. " }, { "code": null, "e": 25792, "s": 25783, "text": "Syntax: " }, { "code": null, "e": 25822, "s": 25792, "text": "grep [options] pattern [path]" }, { "code": null, "e": 25879, "s": 25822, "text": "Below are the two ways in which we can implement grep. " }, { "code": null, "e": 26061, "s": 25879, "text": "8. tac : tac is just the reverse of cat and it works the same way, i.e., instead of printing from lines 1 through n, it prints lines n through 1. It is just reverse of cat command. " }, { "code": null, "e": 26071, "s": 26061, "text": "Syntax: " }, { "code": null, "e": 26083, "s": 26071, "text": "tac [path] " }, { "code": null, "e": 26280, "s": 26083, "text": "9. sed : sed stands for stream editor. It allows us to apply search and replace operation on our data effectively. sed is quite an advanced filter and all its options can be seen on its man page. " }, { "code": null, "e": 26289, "s": 26280, "text": "Syntax: " }, { "code": null, "e": 26301, "s": 26289, "text": "sed [path]" }, { "code": null, "e": 26391, "s": 26301, "text": "The expression we have used above is very basic and is of the form ‘s/search/replace/g’ " }, { "code": null, "e": 26466, "s": 26391, "text": "In the above image, we can clearly see that Scooby is replaced by Scrapy. " }, { "code": null, "e": 26525, "s": 26466, "text": "10. nl : nl is used to number the lines of our text data. " }, { "code": null, "e": 26534, "s": 26525, "text": "Syntax: " }, { "code": null, "e": 26555, "s": 26534, "text": "nl [-options] [path]" }, { "code": null, "e": 26632, "s": 26555, "text": "It can clearly be seen in the above image that the lines have been numbered " }, { "code": null, "e": 26645, "s": 26632, "text": "princekhj555" }, { "code": null, "e": 26656, "s": 26645, "text": "Linux-Unix" }, { "code": null, "e": 26754, "s": 26656, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26763, "s": 26754, "text": "Comments" }, { "code": null, "e": 26776, "s": 26763, "text": "Old Comments" }, { "code": null, "e": 26811, "s": 26776, "text": "scp command in Linux with Examples" }, { "code": null, "e": 26848, "s": 26811, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 26882, "s": 26848, "text": "mv command in Linux with examples" }, { "code": null, "e": 26919, "s": 26882, "text": "chown command in Linux with Examples" }, { "code": null, "e": 26945, "s": 26919, "text": "Docker - COPY Instruction" }, { "code": null, "e": 26971, "s": 26945, "text": "Thread functions in C/C++" }, { "code": null, "e": 27011, "s": 26971, "text": "nslookup command in Linux with Examples" }, { "code": null, "e": 27040, "s": 27011, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 27082, "s": 27040, "text": "Named Pipe or FIFO with example C program" } ]
std::string::compare() in C++ - GeeksforGeeks
18 Jan, 2022 compare() is a public member function of string class. It compares the value of the string object (or a substring) to the sequence of characters specified by its arguments. The compare() can process more than one argument for each string so that one can specify a substring by its index and by its length.Return type : compare() returns an integer value rather than a Boolean value.Different Syntaxes for string::compare() : Syntax 1: Compares the string *this with the string str. int string::compare (const string& str) const Returns: 0 : if both strings are equal. A value < 0 : if *this is shorter than str or, first character that doesn't match is smaller than str. A value > 0 : if *this is longer than str or, first character that doesn't match is greater CPP // CPP code for demonstrating// string::compare (const string& str) const #include<iostream>using namespace std; void compareOperation(string s1, string s2){ // returns a value < 0 (s1 is smaller then s2) if((s1.compare(s2)) < 0) cout << s1 << " is smaller than " << s2 << endl; // returns 0(s1, is being compared to itself) if((s1.compare(s1)) == 0) cout << s1 << " is equal to " << s1 << endl; else cout << "Strings didn't match "; } // Driver Codeint main(){ string s1("Geeks"); string s2("forGeeks"); compareOperation(s1, s2); return 0;} Output: Geeks is smaller than forGeeks Geeks is equal to Geeks Syntax 2: Compares at most, len characters of string *this, starting with index idx with the string str. int string::compare (size_type idx, size_type len, const string& str) const Throws out_of_range if index > size(). CPP // CPP code to demonstrate// int string::compare (size_type idx, size_type len,// const string&amp; str) const #include<iostream>using namespace std; void compareOperation(string s1, string s2){ // Compares 5 characters from index number 3 of s2 with s1 if((s2.compare(3, 5, s1)) == 0) cout << "Here, "<< s1 << " are " << s2; else cout << "Strings didn't match ";}// Driver Codeint main(){ string s1("Geeks"); string s2("forGeeks"); compareOperation(s1, s2); return 0;} Output: Here, Geeks are forGeeks Syntax 3: Compares at most, len characters of string *this starting with index idx with at most, str_len characters of string str starting with index str_idx. int string::compare (size_type idx, size_type len, const string& str, size_type str_idx, size_type str_len) const Throws out_of_range if idx > size(). Throws out_of_range if str_idx > str.size(). CPP // CPP code to demonstrate// int string::compare (size_type idx, size_type len, const string&amp;// str, size_type str_idx, size_type str_len) const #include<iostream>using namespace std; void compareOperation(string s1, string s2){ // Compares 5 characters from index number 0 of s1 with // 5 characters from index 3 of s2 if((s1.compare(0, 5, s2, 3, 5)) == 0) cout << "Welcome to " << s1 << s2 << " World"; else cout << "Strings didn't match ";}// Driver Codeint main(){ string s1("Geeks"); string s2("forGeeks"); compareOperation(s1, s2); return 0;} Output: Welcome, to GeeksforGeeks World Syntax 4: Compares the characters of string *this with the characters of the C-string cstr. int string::compare (const char* cstr) const CPP // CPP code to demonstrate// int string::compare (const char* cstr) const #include<iostream>using namespace std; void compareOperation(string s1, string s2){ // returns < 0 (s1 < "GeeksforGeeks") if((s1.compare("GeeksforGeeks")) < 0) cout << s1 << " is smaller than string " << "GeeksforGeeks"; //returns 0 (s2 is "forgeeks") if((s2.compare("forGeeks")) == 0) cout << endl << s2 << " is equal to string " << s2; else cout << "Strings didn't match "; }// Driver Codeint main(){ string s1("Geeks"); string s2("forGeeks"); compareOperation(s1, s2); return 0;} Output: Geeks is smaller than string GeeksforGeeks forGeeks is equal to string forGeeks Syntax 5: Compares at most, len characters of string *this, starting with index idx with all characters of the C-string cstr. int string::compare (size_type idx, size_type len, const char* cstr) const Note that cstr may not be a null pointer (NULL). CPP // CPP code to demonstrate// int string::compare (size_type idx, size_type len,// const char* cstr) const#include<iostream>using namespace std; void compareOperation(string s1){ // Compares 5 characters from 0 index of s1 with "Geeks" if((s1.compare(0, 5, "Geeks")) == 0) cout << s1 << " are " << "awesome people"; else cout << "Strings didn't match "; } // Driver Codeint main(){ string s1("Geeks"); compareOperation(s1); return 0;} Output: Geeks are awesome people Syntax 6: Compares, at most, len characters of string *this, starting with index idx with chars_len characters of the character array chars. int string::compare (size_type idx, size_type len, const char* chars, size_type chars_len)const Note that chars must have at least chars_len characters. The characters may have arbitrary values. Thus, ‘\0’ has no special meaning. CPP // CPP code to demonstrate// int string::compare (size_type idx, size_type len,// const char* chars, size_type chars_len)const #include<iostream>using namespace std; void compareOperation(string s1, string s2){ // Compares 5 characters from 0 index of s1 with // 5 characters of string "Geeks" if((s1.compare(0, 5, "Geeks", 5)) == 0) cout << "This is " << s1 << s2 ; else cout << "Strings didn't match ";} // Driver Codeint main(){ string s1("Geeks"); string s2("forGeeks"); compareOperation(s1, s2); return 0;} Output: This is GeeksforGeeks This article is contributed by Sakshi Tiwari. If you like GeeksforGeeks (We know you do!) and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. germanshephered48 cpp-string cpp-strings-library STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Inheritance in C++ Map in C++ Standard Template Library (STL) Constructors in C++ C++ Classes and Objects Socket Programming in C/C++ Bitwise Operators in C/C++ Operator Overloading in C++ Copy Constructor in C++ Virtual Function in C++ Templates in C++ with Examples
[ { "code": null, "e": 24051, "s": 24023, "text": "\n18 Jan, 2022" }, { "code": null, "e": 24477, "s": 24051, "text": "compare() is a public member function of string class. It compares the value of the string object (or a substring) to the sequence of characters specified by its arguments. The compare() can process more than one argument for each string so that one can specify a substring by its index and by its length.Return type : compare() returns an integer value rather than a Boolean value.Different Syntaxes for string::compare() : " }, { "code": null, "e": 24534, "s": 24477, "text": "Syntax 1: Compares the string *this with the string str." }, { "code": null, "e": 24815, "s": 24534, "text": "int string::compare (const string& str) const\nReturns:\n0 : if both strings are equal.\nA value < 0 : if *this is shorter than str or,\nfirst character that doesn't match is smaller than str.\nA value > 0 : if *this is longer than str or,\nfirst character that doesn't match is greater" }, { "code": null, "e": 24819, "s": 24815, "text": "CPP" }, { "code": "// CPP code for demonstrating// string::compare (const string& str) const #include<iostream>using namespace std; void compareOperation(string s1, string s2){ // returns a value < 0 (s1 is smaller then s2) if((s1.compare(s2)) < 0) cout << s1 << \" is smaller than \" << s2 << endl; // returns 0(s1, is being compared to itself) if((s1.compare(s1)) == 0) cout << s1 << \" is equal to \" << s1 << endl; else cout << \"Strings didn't match \"; } // Driver Codeint main(){ string s1(\"Geeks\"); string s2(\"forGeeks\"); compareOperation(s1, s2); return 0;}", "e": 25419, "s": 24819, "text": null }, { "code": null, "e": 25428, "s": 25419, "text": "Output: " }, { "code": null, "e": 25483, "s": 25428, "text": "Geeks is smaller than forGeeks\nGeeks is equal to Geeks" }, { "code": null, "e": 25588, "s": 25483, "text": "Syntax 2: Compares at most, len characters of string *this, starting with index idx with the string str." }, { "code": null, "e": 25703, "s": 25588, "text": "int string::compare (size_type idx, size_type len, const string& str) const\nThrows out_of_range if index > size()." }, { "code": null, "e": 25707, "s": 25703, "text": "CPP" }, { "code": "// CPP code to demonstrate// int string::compare (size_type idx, size_type len,// const string&amp; str) const #include<iostream>using namespace std; void compareOperation(string s1, string s2){ // Compares 5 characters from index number 3 of s2 with s1 if((s2.compare(3, 5, s1)) == 0) cout << \"Here, \"<< s1 << \" are \" << s2; else cout << \"Strings didn't match \";}// Driver Codeint main(){ string s1(\"Geeks\"); string s2(\"forGeeks\"); compareOperation(s1, s2); return 0;}", "e": 26217, "s": 25707, "text": null }, { "code": null, "e": 26226, "s": 26217, "text": "Output: " }, { "code": null, "e": 26251, "s": 26226, "text": "Here, Geeks are forGeeks" }, { "code": null, "e": 26410, "s": 26251, "text": "Syntax 3: Compares at most, len characters of string *this starting with index idx with at most, str_len characters of string str starting with index str_idx." }, { "code": null, "e": 26607, "s": 26410, "text": "int string::compare (size_type idx, size_type len, const string& \nstr, size_type str_idx, size_type str_len) const\nThrows out_of_range if idx > size().\nThrows out_of_range if str_idx > str.size()." }, { "code": null, "e": 26611, "s": 26607, "text": "CPP" }, { "code": "// CPP code to demonstrate// int string::compare (size_type idx, size_type len, const string&amp;// str, size_type str_idx, size_type str_len) const #include<iostream>using namespace std; void compareOperation(string s1, string s2){ // Compares 5 characters from index number 0 of s1 with // 5 characters from index 3 of s2 if((s1.compare(0, 5, s2, 3, 5)) == 0) cout << \"Welcome to \" << s1 << s2 << \" World\"; else cout << \"Strings didn't match \";}// Driver Codeint main(){ string s1(\"Geeks\"); string s2(\"forGeeks\"); compareOperation(s1, s2); return 0;}", "e": 27207, "s": 26611, "text": null }, { "code": null, "e": 27216, "s": 27207, "text": "Output: " }, { "code": null, "e": 27248, "s": 27216, "text": "Welcome, to GeeksforGeeks World" }, { "code": null, "e": 27341, "s": 27248, "text": "Syntax 4: Compares the characters of string *this with the characters of the C-string cstr. " }, { "code": null, "e": 27386, "s": 27341, "text": "int string::compare (const char* cstr) const" }, { "code": null, "e": 27390, "s": 27386, "text": "CPP" }, { "code": "// CPP code to demonstrate// int string::compare (const char* cstr) const #include<iostream>using namespace std; void compareOperation(string s1, string s2){ // returns < 0 (s1 < \"GeeksforGeeks\") if((s1.compare(\"GeeksforGeeks\")) < 0) cout << s1 << \" is smaller than string \" << \"GeeksforGeeks\"; //returns 0 (s2 is \"forgeeks\") if((s2.compare(\"forGeeks\")) == 0) cout << endl << s2 << \" is equal to string \" << s2; else cout << \"Strings didn't match \"; }// Driver Codeint main(){ string s1(\"Geeks\"); string s2(\"forGeeks\"); compareOperation(s1, s2); return 0;}", "e": 28005, "s": 27390, "text": null }, { "code": null, "e": 28014, "s": 28005, "text": "Output: " }, { "code": null, "e": 28094, "s": 28014, "text": "Geeks is smaller than string GeeksforGeeks\nforGeeks is equal to string forGeeks" }, { "code": null, "e": 28220, "s": 28094, "text": "Syntax 5: Compares at most, len characters of string *this, starting with index idx with all characters of the C-string cstr." }, { "code": null, "e": 28295, "s": 28220, "text": "int string::compare (size_type idx, size_type len, const char* cstr) const" }, { "code": null, "e": 28344, "s": 28295, "text": "Note that cstr may not be a null pointer (NULL)." }, { "code": null, "e": 28348, "s": 28344, "text": "CPP" }, { "code": "// CPP code to demonstrate// int string::compare (size_type idx, size_type len,// const char* cstr) const#include<iostream>using namespace std; void compareOperation(string s1){ // Compares 5 characters from 0 index of s1 with \"Geeks\" if((s1.compare(0, 5, \"Geeks\")) == 0) cout << s1 << \" are \" << \"awesome people\"; else cout << \"Strings didn't match \"; } // Driver Codeint main(){ string s1(\"Geeks\"); compareOperation(s1); return 0;}", "e": 28824, "s": 28348, "text": null }, { "code": null, "e": 28833, "s": 28824, "text": "Output: " }, { "code": null, "e": 28858, "s": 28833, "text": "Geeks are awesome people" }, { "code": null, "e": 29000, "s": 28858, "text": "Syntax 6: Compares, at most, len characters of string *this, starting with index idx with chars_len characters of the character array chars. " }, { "code": null, "e": 29097, "s": 29000, "text": "int string::compare (size_type idx, size_type len, const char* chars, \nsize_type chars_len)const" }, { "code": null, "e": 29231, "s": 29097, "text": "Note that chars must have at least chars_len characters. The characters may have arbitrary values. Thus, ‘\\0’ has no special meaning." }, { "code": null, "e": 29235, "s": 29231, "text": "CPP" }, { "code": "// CPP code to demonstrate// int string::compare (size_type idx, size_type len,// const char* chars, size_type chars_len)const #include<iostream>using namespace std; void compareOperation(string s1, string s2){ // Compares 5 characters from 0 index of s1 with // 5 characters of string \"Geeks\" if((s1.compare(0, 5, \"Geeks\", 5)) == 0) cout << \"This is \" << s1 << s2 ; else cout << \"Strings didn't match \";} // Driver Codeint main(){ string s1(\"Geeks\"); string s2(\"forGeeks\"); compareOperation(s1, s2); return 0;}", "e": 29792, "s": 29235, "text": null }, { "code": null, "e": 29801, "s": 29792, "text": "Output: " }, { "code": null, "e": 29823, "s": 29801, "text": "This is GeeksforGeeks" }, { "code": null, "e": 30262, "s": 29823, "text": "This article is contributed by Sakshi Tiwari. If you like GeeksforGeeks (We know you do!) and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 30280, "s": 30262, "text": "germanshephered48" }, { "code": null, "e": 30291, "s": 30280, "text": "cpp-string" }, { "code": null, "e": 30311, "s": 30291, "text": "cpp-strings-library" }, { "code": null, "e": 30315, "s": 30311, "text": "STL" }, { "code": null, "e": 30319, "s": 30315, "text": "C++" }, { "code": null, "e": 30323, "s": 30319, "text": "STL" }, { "code": null, "e": 30327, "s": 30323, "text": "CPP" }, { "code": null, "e": 30425, "s": 30327, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30434, "s": 30425, "text": "Comments" }, { "code": null, "e": 30447, "s": 30434, "text": "Old Comments" }, { "code": null, "e": 30466, "s": 30447, "text": "Inheritance in C++" }, { "code": null, "e": 30509, "s": 30466, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 30529, "s": 30509, "text": "Constructors in C++" }, { "code": null, "e": 30553, "s": 30529, "text": "C++ Classes and Objects" }, { "code": null, "e": 30581, "s": 30553, "text": "Socket Programming in C/C++" }, { "code": null, "e": 30608, "s": 30581, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 30636, "s": 30608, "text": "Operator Overloading in C++" }, { "code": null, "e": 30660, "s": 30636, "text": "Copy Constructor in C++" }, { "code": null, "e": 30684, "s": 30660, "text": "Virtual Function in C++" } ]
Named Entity Recognition (NER) with keras and tensorflow | by Nasir Safdari | Towards Data Science
Few years ago when I was working as a software engineering intern at a startup, I saw a new feature in a job posting web-app. The app was able to recognize and parse important information form the resumes like, email address, phone number, degree titles and etc. I started discussing possible approaches with our team and we decided to build a rule based parser in python to just parse different sections of a resume. After spending some time developing the parser, we realized that the answer may not be a rule-based tool. We started googling how it’s done and we came across the term Natural Language Processing (NLP) and more specific, Named Entity Recognition (NER) associated with Machine Learning. NER is an information extraction technique to identify and classify named entities in text. These entities can be pre-defined and generic like location names, organizations, time and etc, or they can be very specific like the example with the resume. NER has a wide variety of use cases in the business. I think gmail is applying NER when you are writing an email and you mention a time in your email or attaching a file, gmail offers to set a calendar notification or remind you to attach the file in case you are sending the email without an attachment. Other applications of NER include: extracting important named entities from legal, financial, and medical documents, classifying content for news providers, improving the search algorithms, and etc. For the rest of this article, we are going to have a short intro to different approaches to tackle NER problem and then we will jump into coding the state-of-the-art method. Here is a more detailed intro to NER by Suvro. Classical Approaches: mostly rule-based. here is the link to a short amazing video by Sentdex that uses NLTK package in python for NER. Machine Learning Approaches: there are two main methods in this category: A- treat the problem as a multi-class classification where named entities are our labels so we can apply different classification algorithms. The problem here is that identifying and labeling named entities require thorough understanding of the context of a sentence and sequence of the word labels in it, which this method ignores that. B- Another method in this category is Conditional Random Field (CRF) model. It is a probabilistic graphical model that can be used to model sequential data such as labels of words in a sentence. for more details and complete implementation of CRF in python, please see Tobias’s article. the CRF model is able to capture the features of the current and previous labels in a sequence but it cannot understand the context of the forward labels; this shortcoming plus the extra feature engineering involved with training a CRF model, makes it less appealing to be adapted by the industry. Deep Learning Approaches: Before discussing details about Deep Learning approaches (state-of-the-art) to NER, we need to analyze proper and clear metrics to evaluate the performance of our models. It is common to use accuracy while training a neural network in different iterations (epochs) as an evaluation metric. However, in case of NER, we might be dealing with important financial, medical, or legal documents and precise identification of named entities in those documents determines the success of the model. In other words, false positives and false negatives have a business cost in a NER task. Therefore, our main metric to evaluate our models will be F1 score because we need a balance between precision and recall. Another important strategy in building a high-performing deep learning method is understanding which type of neural network works best to tackle NER problem considering that the text is a sequential data format. yeah, you guessed it right... Long short Term Memory (LSTM). more details about LSTMs in this link. But not any type of LSTM, we need to use bi-directional LSTMs because using a standard LSTM to make predictions will only take the “past” information in a sequence of the text into account. for NER, since the context covers past and future labels in a sequence, we need to take both the past and the future information into account. A bidirectional LSTM is a combination of two LSTMs — one runs forward from “right to left” and one runs backward from “left to right”. we are going to have a quick look at the architecture of four different state-of-the-art approaches by referring to the actual research paper and then we will move on to implement the one with the highest accuracy. Bidirectional LSTM-CRF: Bidirectional LSTM-CRF: More details and implementation in keras. 2. Bidirectional LSTM-CNNs: More details and implementation in keras. 3. Bidirectional LSTM-CNNS-CRF: 4. ELMo (Embedding from Language Models ): one of the very recent papers (Deep contextualized word representations) introduces a new type of deep contextualized word representation that models both complex characteristics of word use (e.g., syntax and semantics), and how these uses vary across linguistic contexts (i.e., to model polysemy). the new approach (ELMo) has three important representations: 1. Contextual: The representation for each word depends on the entire context in which it is used. 2. Deep: The word representations combine all layers of a deep pre-trained neural network. 3. Character based: ELMo representations are purely character based, allowing the network to use morphological clues to form robust representations for out-of-vocabulary tokens unseen in training. ELMo has a great understanding of the language because it’s trained on a massive dataset, ELMo embeddings are trained on the 1 Billion Word Benchmark. the training is called bidirectional language model (biLM) that can learn from the past and predict the next word in a sequence of words like a sentence. Let’s see how we can implement this approach. we are going to use a dataset from kaggle. import pandas as pdimport numpy as npimport matplotlib.pyplot as pltplt.style.use("ggplot")data = pd.read_csv("ner_dataset.csv", encoding="latin1")data = data.drop(['POS'], axis =1)data = data.fillna(method="ffill")data.tail(12)words = set(list(data['Word'].values))words.add('PADword')n_words = len(words)n_words35179tags = list(set(data["Tag"].values))n_tags = len(tags)n_tags17 we have 47958 sentences in our dataset, 35179 different words and 17 different named entities (Tags). Let’s have a look at the distribution of the sentence lengths in the dataset: class SentenceGetter(object): def __init__(self, data): self.n_sent = 1 self.data = data self.empty = False agg_func = lambda s: [(w, t) for w, t in zip(s["Word"].values.tolist(),s["Tag"].values.tolist())] self.grouped = self.data.groupby("Sentence #").apply(agg_func) self.sentences = [s for s in self.grouped] def get_next(self): try: s = self.grouped["Sentence: {}".format(self.n_sent)] self.n_sent += 1 return s except: return None this Class is in charge of converting every sentence with its named entities (tags) into a list of tuples [(word, named entity), ...] getter = SentenceGetter(data)sent = getter.get_next()print(sent)[('Thousands', 'O'), ('of', 'O'), ('demonstrators', 'O'), ('have', 'O'), ('marched', 'O'), ('through', 'O'), ('London', 'B-geo'), ('to', 'O'), ('protest', 'O'), ('the', 'O'), ('war', 'O'), ('in', 'O'), ('Iraq', 'B-geo'), ('and', 'O'), ('demand', 'O'), ('the', 'O'), ('withdrawal', 'O'), ('of', 'O'), ('British', 'B-gpe'), ('troops', 'O'), ('from', 'O'), ('that', 'O'), ('country', 'O'), ('.', 'O')]sentences = getter.sentencesprint(len(sentences))47959largest_sen = max(len(sen) for sen in sentences)print('biggest sentence has {} words'.format(largest_sen))biggest sentence has 104 words so the longest sentence has 140 words in it and we can see that almost all of the sentences have less than 60 words in them. One of the biggest benefits of this approach is that we dont need any feature engineering; all we need is the sentences and its labeled words, the rest of the work is carried on by ELMo embeddings. In order to feed our sentences into a LSTM network, they all need to be the same size. looking at the distribution graph, we can set the length of all sentences to 50 and add a generic word for the empty spaces; this process is called padding.(another reason that 50 is a good number is that my laptop cannot handle longer sentences). max_len = 50X = [[w[0]for w in s] for s in sentences]new_X = []for seq in X: new_seq = [] for i in range(max_len): try: new_seq.append(seq[i]) except: new_seq.append("PADword") new_X.append(new_seq)new_X[15]['Israeli','officials','say','Prime','Minister','Ariel', 'Sharon', 'will','undergo','a', 'medical','procedure','Thursday', 'to','close','a','tiny','hole','in','his','heart','discovered', 'during','treatment', 'for','a', 'minor', 'stroke', 'suffered', 'last', 'month', '.', 'PADword', 'PADword', 'PADword', 'PADword', 'PADword', 'PADword', 'PADword', 'PADword', 'PADword', 'PADword', 'PADword', 'PADword', 'PADword', 'PADword', 'PADword', 'PADword', 'PADword', 'PADword'] and the same applies for the named entities but we need to map our labels to numbers this time: from keras.preprocessing.sequence import pad_sequencestags2index = {t:i for i,t in enumerate(tags)}y = [[tags2index[w[1]] for w in s] for s in sentences]y = pad_sequences(maxlen=max_len, sequences=y, padding="post", value=tags2index["O"])y[15]array([4, 7, 7, 0, 1, 1, 1, 7, 7, 7, 7, 7, 9, 7, 7, 7, 7, 7, 7, 7, 7, 7,7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,7, 7, 7, 7, 7, 7]) next we split our data into training and testing set and then we import tensorflow Hub ( a library for the publication, discovery, and consumption of reusable parts of machine learning models) to load the ELMo embedding feature and keras to start building our network. from sklearn.model_selection import train_test_splitimport tensorflow as tfimport tensorflow_hub as hubfrom keras import backend as KX_tr, X_te, y_tr, y_te = train_test_split(new_X, y, test_size=0.1, random_state=2018)sess = tf.Session()K.set_session(sess)elmo_model = hub.Module("https://tfhub.dev/google/elmo/2", trainable=True)sess.run(tf.global_variables_initializer())sess.run(tf.tables_initializer()) Running above block of code for the first time will take some time because ELMo is almost 400 MB. next we use a function to convert our sentences to ELMo embeddings: batch_size = 32def ElmoEmbedding(x): return elmo_model(inputs={"tokens": tf.squeeze(tf.cast(x, tf.string)),"sequence_len": tf.constant(batch_size*[max_len]) }, signature="tokens", as_dict=True)["elmo"] now let’s build our neural network: from keras.models import Model, Inputfrom keras.layers.merge import addfrom keras.layers import LSTM, Embedding, Dense, TimeDistributed, Dropout, Bidirectional, Lambdainput_text = Input(shape=(max_len,), dtype=tf.string)embedding = Lambda(ElmoEmbedding, output_shape=(max_len, 1024))(input_text)x = Bidirectional(LSTM(units=512, return_sequences=True, recurrent_dropout=0.2, dropout=0.2))(embedding)x_rnn = Bidirectional(LSTM(units=512, return_sequences=True, recurrent_dropout=0.2, dropout=0.2))(x)x = add([x, x_rnn]) # residual connection to the first biLSTMout = TimeDistributed(Dense(n_tags, activation="softmax"))(x)model = Model(input_text, out)model.compile(optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"]) since we have 32 as the batch size, feeding the network must be in chunks that are all multiples of 32: X_tr, X_val = X_tr[:1213*batch_size], X_tr[-135*batch_size:]y_tr, y_val = y_tr[:1213*batch_size], y_tr[-135*batch_size:]y_tr = y_tr.reshape(y_tr.shape[0], y_tr.shape[1], 1)y_val = y_val.reshape(y_val.shape[0], y_val.shape[1], 1)history = model.fit(np.array(X_tr), y_tr, validation_data=(np.array(X_val), y_val),batch_size=batch_size, epochs=3, verbose=1)Train on 38816 samples, validate on 4320 samplesEpoch 1/338816/38816 [==============================] - 834s 21ms/step - loss: 0.0625 - acc: 0.9818 - val_loss: 0.0449 - val_acc: 0.9861Epoch 2/338816/38816 [==============================] - 833s 21ms/step - loss: 0.0405 - acc: 0.9869 - val_loss: 0.0417 - val_acc: 0.9868Epoch 3/338816/38816 [==============================] - 831s 21ms/step - loss: 0.0336 - acc: 0.9886 - val_loss: 0.0406 - val_acc: 0.9873 The initial goal was to play around with parameter tuning to achieve higher accuracy but my laptop was not able to handle more than 3 epochs and batch sizes bigger than 32 or increasing the test size. I am running keras on a Geforce GTX 1060 and it took almost 45 minutes to train those 3 epochs, if you have a better GPU, give it shot by changing some of those parameters. 0.9873 validation accuracy is a great score, however we are not interested to evaluate our model with Accuracy metric. Let’s see how we can get Precision, Recall, and F1 scores: from seqeval.metrics import precision_score, recall_score, f1_score, classification_reportX_te = X_te[:149*batch_size]test_pred = model.predict(np.array(X_te), verbose=1)4768/4768 [==============================] - 64s 13ms/stepidx2tag = {i: w for w, i in tags2index.items()}def pred2label(pred): out = [] for pred_i in pred: out_i = [] for p in pred_i: p_i = np.argmax(p) out_i.append(idx2tag[p_i].replace("PADword", "O")) out.append(out_i) return outdef test2label(pred): out = [] for pred_i in pred: out_i = [] for p in pred_i: out_i.append(idx2tag[p].replace("PADword", "O")) out.append(out_i) return out pred_labels = pred2label(test_pred)test_labels = test2label(y_te[:149*32])print(classification_report(test_labels, pred_labels)) precision recall f1-score support org 0.69 0.66 0.68 2061 tim 0.88 0.84 0.86 2148 gpe 0.95 0.93 0.94 1591 per 0.75 0.80 0.77 1677 geo 0.85 0.89 0.87 3720 art 0.23 0.14 0.18 49 eve 0.33 0.33 0.33 33 nat 0.47 0.36 0.41 22avg / total 0.82 0.82 0.82 11301 0.82 F1 score is an outstanding achievement. it beats all the other three deep learning methods mentioned at the beginning of this section and it can be easily adapted by the industry. finally, let’s see how our predictions look like: i = 390p = model.predict(np.array(X_te[i:i+batch_size]))[0]p = np.argmax(p, axis=-1)print("{:15} {:5}: ({})".format("Word", "Pred", "True"))print("="*30)for w, true, pred in zip(X_te[i], y_te[i], p): if w != "__PAD__": print("{:15}:{:5} ({})".format(w, tags[pred], tags[true]))Word Pred : (True)==============================Citing :O (O)a :O (O)draft :O (O)report :O (O)from :O (O)the :O (O)U.S. :B-org (B-org)Government :I-org (I-org)Accountability :I-org (O)office :O (O), :O (O)The :B-org (B-org)New :I-org (I-org)York :I-org (I-org)Times :I-org (I-org)said :O (O)Saturday :B-tim (B-tim)the :O (O)losses :O (O)amount :O (O)to :O (O)between :O (O)1,00,000 :O (O)and :O (O)3,00,000 :O (O)barrels :O (O)a :O (O)day :O (O)of :O (O)Iraq :B-geo (B-geo)'s :O (O)declared :O (O)oil :O (O)production :O (O)over :O (O)the :O (O)past :B-tim (B-tim)four :I-tim (I-tim)years :O (O). :O (O)PADword :O (O)PADword :O (O)PADword :O (O)PADword :O (O)PADword :O (O)PADword :O (O)PADword :O (O)PADword :O (O)PADword :O (O)PADword :O (O) like always, the code and jupyter notebook is available on my Github. Questions and Comments are highly appreciated.
[ { "code": null, "e": 876, "s": 172, "text": "Few years ago when I was working as a software engineering intern at a startup, I saw a new feature in a job posting web-app. The app was able to recognize and parse important information form the resumes like, email address, phone number, degree titles and etc. I started discussing possible approaches with our team and we decided to build a rule based parser in python to just parse different sections of a resume. After spending some time developing the parser, we realized that the answer may not be a rule-based tool. We started googling how it’s done and we came across the term Natural Language Processing (NLP) and more specific, Named Entity Recognition (NER) associated with Machine Learning." }, { "code": null, "e": 1852, "s": 876, "text": "NER is an information extraction technique to identify and classify named entities in text. These entities can be pre-defined and generic like location names, organizations, time and etc, or they can be very specific like the example with the resume. NER has a wide variety of use cases in the business. I think gmail is applying NER when you are writing an email and you mention a time in your email or attaching a file, gmail offers to set a calendar notification or remind you to attach the file in case you are sending the email without an attachment. Other applications of NER include: extracting important named entities from legal, financial, and medical documents, classifying content for news providers, improving the search algorithms, and etc. For the rest of this article, we are going to have a short intro to different approaches to tackle NER problem and then we will jump into coding the state-of-the-art method. Here is a more detailed intro to NER by Suvro." }, { "code": null, "e": 1988, "s": 1852, "text": "Classical Approaches: mostly rule-based. here is the link to a short amazing video by Sentdex that uses NLTK package in python for NER." }, { "code": null, "e": 2985, "s": 1988, "text": "Machine Learning Approaches: there are two main methods in this category: A- treat the problem as a multi-class classification where named entities are our labels so we can apply different classification algorithms. The problem here is that identifying and labeling named entities require thorough understanding of the context of a sentence and sequence of the word labels in it, which this method ignores that. B- Another method in this category is Conditional Random Field (CRF) model. It is a probabilistic graphical model that can be used to model sequential data such as labels of words in a sentence. for more details and complete implementation of CRF in python, please see Tobias’s article. the CRF model is able to capture the features of the current and previous labels in a sequence but it cannot understand the context of the forward labels; this shortcoming plus the extra feature engineering involved with training a CRF model, makes it less appealing to be adapted by the industry." }, { "code": null, "e": 3011, "s": 2985, "text": "Deep Learning Approaches:" }, { "code": null, "e": 3712, "s": 3011, "text": "Before discussing details about Deep Learning approaches (state-of-the-art) to NER, we need to analyze proper and clear metrics to evaluate the performance of our models. It is common to use accuracy while training a neural network in different iterations (epochs) as an evaluation metric. However, in case of NER, we might be dealing with important financial, medical, or legal documents and precise identification of named entities in those documents determines the success of the model. In other words, false positives and false negatives have a business cost in a NER task. Therefore, our main metric to evaluate our models will be F1 score because we need a balance between precision and recall." }, { "code": null, "e": 4492, "s": 3712, "text": "Another important strategy in building a high-performing deep learning method is understanding which type of neural network works best to tackle NER problem considering that the text is a sequential data format. yeah, you guessed it right... Long short Term Memory (LSTM). more details about LSTMs in this link. But not any type of LSTM, we need to use bi-directional LSTMs because using a standard LSTM to make predictions will only take the “past” information in a sequence of the text into account. for NER, since the context covers past and future labels in a sequence, we need to take both the past and the future information into account. A bidirectional LSTM is a combination of two LSTMs — one runs forward from “right to left” and one runs backward from “left to right”." }, { "code": null, "e": 4707, "s": 4492, "text": "we are going to have a quick look at the architecture of four different state-of-the-art approaches by referring to the actual research paper and then we will move on to implement the one with the highest accuracy." }, { "code": null, "e": 4731, "s": 4707, "text": "Bidirectional LSTM-CRF:" }, { "code": null, "e": 4755, "s": 4731, "text": "Bidirectional LSTM-CRF:" }, { "code": null, "e": 4797, "s": 4755, "text": "More details and implementation in keras." }, { "code": null, "e": 4825, "s": 4797, "text": "2. Bidirectional LSTM-CNNs:" }, { "code": null, "e": 4867, "s": 4825, "text": "More details and implementation in keras." }, { "code": null, "e": 4899, "s": 4867, "text": "3. Bidirectional LSTM-CNNS-CRF:" }, { "code": null, "e": 4942, "s": 4899, "text": "4. ELMo (Embedding from Language Models ):" }, { "code": null, "e": 5302, "s": 4942, "text": "one of the very recent papers (Deep contextualized word representations) introduces a new type of deep contextualized word representation that models both complex characteristics of word use (e.g., syntax and semantics), and how these uses vary across linguistic contexts (i.e., to model polysemy). the new approach (ELMo) has three important representations:" }, { "code": null, "e": 5401, "s": 5302, "text": "1. Contextual: The representation for each word depends on the entire context in which it is used." }, { "code": null, "e": 5492, "s": 5401, "text": "2. Deep: The word representations combine all layers of a deep pre-trained neural network." }, { "code": null, "e": 5689, "s": 5492, "text": "3. Character based: ELMo representations are purely character based, allowing the network to use morphological clues to form robust representations for out-of-vocabulary tokens unseen in training." }, { "code": null, "e": 6083, "s": 5689, "text": "ELMo has a great understanding of the language because it’s trained on a massive dataset, ELMo embeddings are trained on the 1 Billion Word Benchmark. the training is called bidirectional language model (biLM) that can learn from the past and predict the next word in a sequence of words like a sentence. Let’s see how we can implement this approach. we are going to use a dataset from kaggle." }, { "code": null, "e": 6464, "s": 6083, "text": "import pandas as pdimport numpy as npimport matplotlib.pyplot as pltplt.style.use(\"ggplot\")data = pd.read_csv(\"ner_dataset.csv\", encoding=\"latin1\")data = data.drop(['POS'], axis =1)data = data.fillna(method=\"ffill\")data.tail(12)words = set(list(data['Word'].values))words.add('PADword')n_words = len(words)n_words35179tags = list(set(data[\"Tag\"].values))n_tags = len(tags)n_tags17" }, { "code": null, "e": 6566, "s": 6464, "text": "we have 47958 sentences in our dataset, 35179 different words and 17 different named entities (Tags)." }, { "code": null, "e": 6644, "s": 6566, "text": "Let’s have a look at the distribution of the sentence lengths in the dataset:" }, { "code": null, "e": 7194, "s": 6644, "text": "class SentenceGetter(object): def __init__(self, data): self.n_sent = 1 self.data = data self.empty = False agg_func = lambda s: [(w, t) for w, t in zip(s[\"Word\"].values.tolist(),s[\"Tag\"].values.tolist())] self.grouped = self.data.groupby(\"Sentence #\").apply(agg_func) self.sentences = [s for s in self.grouped] def get_next(self): try: s = self.grouped[\"Sentence: {}\".format(self.n_sent)] self.n_sent += 1 return s except: return None" }, { "code": null, "e": 7328, "s": 7194, "text": "this Class is in charge of converting every sentence with its named entities (tags) into a list of tuples [(word, named entity), ...]" }, { "code": null, "e": 7981, "s": 7328, "text": "getter = SentenceGetter(data)sent = getter.get_next()print(sent)[('Thousands', 'O'), ('of', 'O'), ('demonstrators', 'O'), ('have', 'O'), ('marched', 'O'), ('through', 'O'), ('London', 'B-geo'), ('to', 'O'), ('protest', 'O'), ('the', 'O'), ('war', 'O'), ('in', 'O'), ('Iraq', 'B-geo'), ('and', 'O'), ('demand', 'O'), ('the', 'O'), ('withdrawal', 'O'), ('of', 'O'), ('British', 'B-gpe'), ('troops', 'O'), ('from', 'O'), ('that', 'O'), ('country', 'O'), ('.', 'O')]sentences = getter.sentencesprint(len(sentences))47959largest_sen = max(len(sen) for sen in sentences)print('biggest sentence has {} words'.format(largest_sen))biggest sentence has 104 words" }, { "code": null, "e": 8106, "s": 7981, "text": "so the longest sentence has 140 words in it and we can see that almost all of the sentences have less than 60 words in them." }, { "code": null, "e": 8639, "s": 8106, "text": "One of the biggest benefits of this approach is that we dont need any feature engineering; all we need is the sentences and its labeled words, the rest of the work is carried on by ELMo embeddings. In order to feed our sentences into a LSTM network, they all need to be the same size. looking at the distribution graph, we can set the length of all sentences to 50 and add a generic word for the empty spaces; this process is called padding.(another reason that 50 is a good number is that my laptop cannot handle longer sentences)." }, { "code": null, "e": 9362, "s": 8639, "text": "max_len = 50X = [[w[0]for w in s] for s in sentences]new_X = []for seq in X: new_seq = [] for i in range(max_len): try: new_seq.append(seq[i]) except: new_seq.append(\"PADword\") new_X.append(new_seq)new_X[15]['Israeli','officials','say','Prime','Minister','Ariel', 'Sharon', 'will','undergo','a', 'medical','procedure','Thursday', 'to','close','a','tiny','hole','in','his','heart','discovered', 'during','treatment', 'for','a', 'minor', 'stroke', 'suffered', 'last', 'month', '.', 'PADword', 'PADword', 'PADword', 'PADword', 'PADword', 'PADword', 'PADword', 'PADword', 'PADword', 'PADword', 'PADword', 'PADword', 'PADword', 'PADword', 'PADword', 'PADword', 'PADword', 'PADword']" }, { "code": null, "e": 9458, "s": 9362, "text": "and the same applies for the named entities but we need to map our labels to numbers this time:" }, { "code": null, "e": 9857, "s": 9458, "text": "from keras.preprocessing.sequence import pad_sequencestags2index = {t:i for i,t in enumerate(tags)}y = [[tags2index[w[1]] for w in s] for s in sentences]y = pad_sequences(maxlen=max_len, sequences=y, padding=\"post\", value=tags2index[\"O\"])y[15]array([4, 7, 7, 0, 1, 1, 1, 7, 7, 7, 7, 7, 9, 7, 7, 7, 7, 7, 7, 7, 7, 7,7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,7, 7, 7, 7, 7, 7])" }, { "code": null, "e": 10126, "s": 9857, "text": "next we split our data into training and testing set and then we import tensorflow Hub ( a library for the publication, discovery, and consumption of reusable parts of machine learning models) to load the ELMo embedding feature and keras to start building our network." }, { "code": null, "e": 10533, "s": 10126, "text": "from sklearn.model_selection import train_test_splitimport tensorflow as tfimport tensorflow_hub as hubfrom keras import backend as KX_tr, X_te, y_tr, y_te = train_test_split(new_X, y, test_size=0.1, random_state=2018)sess = tf.Session()K.set_session(sess)elmo_model = hub.Module(\"https://tfhub.dev/google/elmo/2\", trainable=True)sess.run(tf.global_variables_initializer())sess.run(tf.tables_initializer())" }, { "code": null, "e": 10699, "s": 10533, "text": "Running above block of code for the first time will take some time because ELMo is almost 400 MB. next we use a function to convert our sentences to ELMo embeddings:" }, { "code": null, "e": 10969, "s": 10699, "text": "batch_size = 32def ElmoEmbedding(x): return elmo_model(inputs={\"tokens\": tf.squeeze(tf.cast(x, tf.string)),\"sequence_len\": tf.constant(batch_size*[max_len]) }, signature=\"tokens\", as_dict=True)[\"elmo\"]" }, { "code": null, "e": 11005, "s": 10969, "text": "now let’s build our neural network:" }, { "code": null, "e": 11799, "s": 11005, "text": "from keras.models import Model, Inputfrom keras.layers.merge import addfrom keras.layers import LSTM, Embedding, Dense, TimeDistributed, Dropout, Bidirectional, Lambdainput_text = Input(shape=(max_len,), dtype=tf.string)embedding = Lambda(ElmoEmbedding, output_shape=(max_len, 1024))(input_text)x = Bidirectional(LSTM(units=512, return_sequences=True, recurrent_dropout=0.2, dropout=0.2))(embedding)x_rnn = Bidirectional(LSTM(units=512, return_sequences=True, recurrent_dropout=0.2, dropout=0.2))(x)x = add([x, x_rnn]) # residual connection to the first biLSTMout = TimeDistributed(Dense(n_tags, activation=\"softmax\"))(x)model = Model(input_text, out)model.compile(optimizer=\"adam\", loss=\"sparse_categorical_crossentropy\", metrics=[\"accuracy\"])" }, { "code": null, "e": 11903, "s": 11799, "text": "since we have 32 as the batch size, feeding the network must be in chunks that are all multiples of 32:" }, { "code": null, "e": 12714, "s": 11903, "text": "X_tr, X_val = X_tr[:1213*batch_size], X_tr[-135*batch_size:]y_tr, y_val = y_tr[:1213*batch_size], y_tr[-135*batch_size:]y_tr = y_tr.reshape(y_tr.shape[0], y_tr.shape[1], 1)y_val = y_val.reshape(y_val.shape[0], y_val.shape[1], 1)history = model.fit(np.array(X_tr), y_tr, validation_data=(np.array(X_val), y_val),batch_size=batch_size, epochs=3, verbose=1)Train on 38816 samples, validate on 4320 samplesEpoch 1/338816/38816 [==============================] - 834s 21ms/step - loss: 0.0625 - acc: 0.9818 - val_loss: 0.0449 - val_acc: 0.9861Epoch 2/338816/38816 [==============================] - 833s 21ms/step - loss: 0.0405 - acc: 0.9869 - val_loss: 0.0417 - val_acc: 0.9868Epoch 3/338816/38816 [==============================] - 831s 21ms/step - loss: 0.0336 - acc: 0.9886 - val_loss: 0.0406 - val_acc: 0.9873" }, { "code": null, "e": 13088, "s": 12714, "text": "The initial goal was to play around with parameter tuning to achieve higher accuracy but my laptop was not able to handle more than 3 epochs and batch sizes bigger than 32 or increasing the test size. I am running keras on a Geforce GTX 1060 and it took almost 45 minutes to train those 3 epochs, if you have a better GPU, give it shot by changing some of those parameters." }, { "code": null, "e": 13266, "s": 13088, "text": "0.9873 validation accuracy is a great score, however we are not interested to evaluate our model with Accuracy metric. Let’s see how we can get Precision, Recall, and F1 scores:" }, { "code": null, "e": 14621, "s": 13266, "text": "from seqeval.metrics import precision_score, recall_score, f1_score, classification_reportX_te = X_te[:149*batch_size]test_pred = model.predict(np.array(X_te), verbose=1)4768/4768 [==============================] - 64s 13ms/stepidx2tag = {i: w for w, i in tags2index.items()}def pred2label(pred): out = [] for pred_i in pred: out_i = [] for p in pred_i: p_i = np.argmax(p) out_i.append(idx2tag[p_i].replace(\"PADword\", \"O\")) out.append(out_i) return outdef test2label(pred): out = [] for pred_i in pred: out_i = [] for p in pred_i: out_i.append(idx2tag[p].replace(\"PADword\", \"O\")) out.append(out_i) return out pred_labels = pred2label(test_pred)test_labels = test2label(y_te[:149*32])print(classification_report(test_labels, pred_labels)) precision recall f1-score support org 0.69 0.66 0.68 2061 tim 0.88 0.84 0.86 2148 gpe 0.95 0.93 0.94 1591 per 0.75 0.80 0.77 1677 geo 0.85 0.89 0.87 3720 art 0.23 0.14 0.18 49 eve 0.33 0.33 0.33 33 nat 0.47 0.36 0.41 22avg / total 0.82 0.82 0.82 11301" }, { "code": null, "e": 14806, "s": 14621, "text": "0.82 F1 score is an outstanding achievement. it beats all the other three deep learning methods mentioned at the beginning of this section and it can be easily adapted by the industry." }, { "code": null, "e": 14856, "s": 14806, "text": "finally, let’s see how our predictions look like:" }, { "code": null, "e": 16493, "s": 14856, "text": "i = 390p = model.predict(np.array(X_te[i:i+batch_size]))[0]p = np.argmax(p, axis=-1)print(\"{:15} {:5}: ({})\".format(\"Word\", \"Pred\", \"True\"))print(\"=\"*30)for w, true, pred in zip(X_te[i], y_te[i], p): if w != \"__PAD__\": print(\"{:15}:{:5} ({})\".format(w, tags[pred], tags[true]))Word Pred : (True)==============================Citing :O (O)a :O (O)draft :O (O)report :O (O)from :O (O)the :O (O)U.S. :B-org (B-org)Government :I-org (I-org)Accountability :I-org (O)office :O (O), :O (O)The :B-org (B-org)New :I-org (I-org)York :I-org (I-org)Times :I-org (I-org)said :O (O)Saturday :B-tim (B-tim)the :O (O)losses :O (O)amount :O (O)to :O (O)between :O (O)1,00,000 :O (O)and :O (O)3,00,000 :O (O)barrels :O (O)a :O (O)day :O (O)of :O (O)Iraq :B-geo (B-geo)'s :O (O)declared :O (O)oil :O (O)production :O (O)over :O (O)the :O (O)past :B-tim (B-tim)four :I-tim (I-tim)years :O (O). :O (O)PADword :O (O)PADword :O (O)PADword :O (O)PADword :O (O)PADword :O (O)PADword :O (O)PADword :O (O)PADword :O (O)PADword :O (O)PADword :O (O)" }, { "code": null, "e": 16563, "s": 16493, "text": "like always, the code and jupyter notebook is available on my Github." } ]
Inspect live objects in Python
Functions in this module provide usefule information about live objects such as modules, classes, methods, functions, code objects etc. These functions perform type checking, retrieve source code, inspect classes and functions, and examine the interpreter stack. getmembers()− This function returns all the members of an object in a list of name, value pairs sorted by name. If the optional predicate is supplied, only members for which the predicate returns a true value are included. getmodulename() −This function returns the name of the module named by the file path, without including the names of enclosing packages We shall be using following script for understanding the behaviour of inspect module. #inspect-example.py '''This is module docstring''' def hello(): '''hello docstring''' print ('Hello world') return #class definitions class parent: '''parent docstring''' def __init__(self): self.var='hello' def hello(self): print (self.var) class child(parent): def hello(self): '''hello function overridden''' super().hello() print ("How are you?") starts with '__' >>> import inspect, inspect_example >>> for k,v in inspect.getmembers(inspect_example): if k.startswith('__')==False:print (k,v) child hello parent >>> Predicate is a logical condition applied to functions in inspect module. For example getmembers() function returns list of module's members for which given predicate condition is true. Following predicates are defined in inspect module Here only class members in the module will be returned. >>> for k,v in inspect.getmembers(inspect_example, inspect.isclass): print (k,v) child <class 'inspect_example.child'> parent <class 'inspect_example.parent'> >>> To retrieve members of a specified class 'child' − >>> inspect.getmembers(inspect_example.child) >>> x=inspect_example.child() >>> inspect.getmembers(x) The getdoc() function retrieves docstring of a module, class or function. >>> inspect.getdoc(inspect_example) 'This is module docstring' >>> inspect.getdoc(inspect_example.parent) 'parent docstring' >>> inspect.getdoc(inspect_example.hello) 'hello docstring' The getsource() function fetches the definition code of a function − >>> print (inspect.getsource(inspect_example.hello)) def hello(): '''hello docstring''' print ('Hello world') return >>> sign=inspect.signature(inspect_example.parent.hello) >>> print (sign) The inspect module also has a command line interface. C:\Users\acer>python -m inspect -d inspect_example Target: inspect_example Origin: C:\python36\inspect_example.py Cached: C:\python36\__pycache__\inspect_example.cpython-36.pyc Loader: <_frozen_importlib_external.SourceFileLoader object at 0x0000029827BD0D30> Following command returns source code of 'Hello()' function in the module. C:\Users\acer>python -m inspect inspect_example:hello def hello(): '''hello docstring''' print ('Hello world') return
[ { "code": null, "e": 1325, "s": 1062, "text": "Functions in this module provide usefule information about live objects such as modules, classes, methods, functions, code objects etc. These functions perform type checking, retrieve source code, inspect classes and functions, and examine the interpreter stack." }, { "code": null, "e": 1684, "s": 1325, "text": "getmembers()− This function returns all the members of an object in a list of name, value pairs sorted by name. If the optional predicate is supplied, only members for which the predicate returns a true value are included. getmodulename() −This function returns the name of the module named by the file path, without including the names of enclosing packages" }, { "code": null, "e": 1770, "s": 1684, "text": "We shall be using following script for understanding the behaviour of inspect module." }, { "code": null, "e": 2172, "s": 1770, "text": "#inspect-example.py\n'''This is module docstring'''\ndef hello():\n '''hello docstring'''\n print ('Hello world')\n return\n#class definitions\nclass parent:\n '''parent docstring'''\n def __init__(self):\n self.var='hello'\n def hello(self):\n print (self.var)\nclass child(parent):\n def hello(self):\n '''hello function overridden'''\n super().hello()\n print (\"How are you?\")" }, { "code": null, "e": 2189, "s": 2172, "text": "starts with '__'" }, { "code": null, "e": 2347, "s": 2189, "text": ">>> import inspect, inspect_example\n>>> for k,v in inspect.getmembers(inspect_example):\n if k.startswith('__')==False:print (k,v)\nchild\nhello\nparent\n>>>" }, { "code": null, "e": 2583, "s": 2347, "text": "Predicate is a logical condition applied to functions in inspect module. For example getmembers() function returns list of module's members for which given predicate condition is true. Following predicates are defined in inspect module" }, { "code": null, "e": 2639, "s": 2583, "text": "Here only class members in the module will be returned." }, { "code": null, "e": 2808, "s": 2639, "text": ">>> for k,v in inspect.getmembers(inspect_example, inspect.isclass):\n print (k,v)\nchild <class 'inspect_example.child'>\nparent <class 'inspect_example.parent'>\n>>>" }, { "code": null, "e": 2859, "s": 2808, "text": "To retrieve members of a specified class 'child' −" }, { "code": null, "e": 2961, "s": 2859, "text": ">>> inspect.getmembers(inspect_example.child)\n>>> x=inspect_example.child()\n>>> inspect.getmembers(x)" }, { "code": null, "e": 3035, "s": 2961, "text": "The getdoc() function retrieves docstring of a module, class or function." }, { "code": null, "e": 3220, "s": 3035, "text": ">>> inspect.getdoc(inspect_example)\n'This is module docstring'\n>>> inspect.getdoc(inspect_example.parent)\n'parent docstring'\n>>> inspect.getdoc(inspect_example.hello)\n'hello docstring'" }, { "code": null, "e": 3289, "s": 3220, "text": "The getsource() function fetches the definition code of a function −" }, { "code": null, "e": 3489, "s": 3289, "text": ">>> print (inspect.getsource(inspect_example.hello))\ndef hello():\n '''hello docstring'''\n print ('Hello world')\n return\n>>> sign=inspect.signature(inspect_example.parent.hello)\n>>> print (sign)" }, { "code": null, "e": 3543, "s": 3489, "text": "The inspect module also has a command line interface." }, { "code": null, "e": 3803, "s": 3543, "text": "C:\\Users\\acer>python -m inspect -d inspect_example\nTarget: inspect_example\nOrigin: C:\\python36\\inspect_example.py\nCached: C:\\python36\\__pycache__\\inspect_example.cpython-36.pyc\nLoader: <_frozen_importlib_external.SourceFileLoader object at\n0x0000029827BD0D30>" }, { "code": null, "e": 3878, "s": 3803, "text": "Following command returns source code of 'Hello()' function in the module." }, { "code": null, "e": 4005, "s": 3878, "text": "C:\\Users\\acer>python -m inspect inspect_example:hello\ndef hello():\n '''hello docstring'''\n print ('Hello world')\n return" } ]