title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How to Install Selenium WebDriver on MacOS?
21 Sep, 2021 In this article, we will learn how to install Selenium WebDriver in Python on macOS. Selenium WebDriver is a web framework that permits you to execute cross-browser tests. This tool is used for automating web-based application testing to verify that it performs expectedly. Follow the below steps to install Selenium WebDriver on macOS: Step 1: Install the latest Python3 in MacOS Step 2: Download and install the latest Chrome and check your Chrome version from “chrome://settings/help“ Step 3: Download the Chrome WebDriver Zip File matching with your Chrome version and Apple Chip from here and extract the chromedriver. Step 4: Copy the chromedriver and paste it to “/usr/local/bin” (If this folder doesn’t exist then create one) Step 5: Open a terminal inside the bin folder and run the following command so that MacOS can verify the app. xattr -d com.apple.quarantine chromedriver Step 6: Upgrade your pip to avoid errors during installation. pip3 install --upgrade pip Step 7: Install selenium library via pip. pip3 install selenium Run the python code below in your system and it should open up “https://geeksforgeeks.org” in your chrome browser automatically. Python3 from selenium import webdriverimport time # Main Functionif __name__ == '__main__': options = webdriver.ChromeOptions() options.add_argument("--start-maximized") options.add_argument('--log-level=3') # Provide the path of chromedriver present on your system. driver = webdriver.Chrome(executable_path="chromedriver", chrome_options=options) driver.set_window_size(1920,1080) # Send a get request to the url driver.get('https://www.geeksforgeeks.org/') time.sleep(60) driver.quit() print("Done") Browser Output: Chrome Browser Terminal Output: Terminal Blogathon-2021 how-to-install Picked Python-selenium Blogathon How To Installation Guide TechTips Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Sep, 2021" }, { "code": null, "e": 326, "s": 52, "text": "In this article, we will learn how to install Selenium WebDriver in Python on macOS. Selenium WebDriver is a web framework that permits you to execute cross-browser tests. This tool is used for automating web-based application testing to verify that it performs expectedly." }, { "code": null, "e": 389, "s": 326, "text": "Follow the below steps to install Selenium WebDriver on macOS:" }, { "code": null, "e": 433, "s": 389, "text": "Step 1: Install the latest Python3 in MacOS" }, { "code": null, "e": 540, "s": 433, "text": "Step 2: Download and install the latest Chrome and check your Chrome version from “chrome://settings/help“" }, { "code": null, "e": 676, "s": 540, "text": "Step 3: Download the Chrome WebDriver Zip File matching with your Chrome version and Apple Chip from here and extract the chromedriver." }, { "code": null, "e": 786, "s": 676, "text": "Step 4: Copy the chromedriver and paste it to “/usr/local/bin” (If this folder doesn’t exist then create one)" }, { "code": null, "e": 896, "s": 786, "text": "Step 5: Open a terminal inside the bin folder and run the following command so that MacOS can verify the app." }, { "code": null, "e": 939, "s": 896, "text": "xattr -d com.apple.quarantine chromedriver" }, { "code": null, "e": 1001, "s": 939, "text": "Step 6: Upgrade your pip to avoid errors during installation." }, { "code": null, "e": 1028, "s": 1001, "text": "pip3 install --upgrade pip" }, { "code": null, "e": 1070, "s": 1028, "text": "Step 7: Install selenium library via pip." }, { "code": null, "e": 1092, "s": 1070, "text": "pip3 install selenium" }, { "code": null, "e": 1221, "s": 1092, "text": "Run the python code below in your system and it should open up “https://geeksforgeeks.org” in your chrome browser automatically." }, { "code": null, "e": 1229, "s": 1221, "text": "Python3" }, { "code": "from selenium import webdriverimport time # Main Functionif __name__ == '__main__': options = webdriver.ChromeOptions() options.add_argument(\"--start-maximized\") options.add_argument('--log-level=3') # Provide the path of chromedriver present on your system. driver = webdriver.Chrome(executable_path=\"chromedriver\", chrome_options=options) driver.set_window_size(1920,1080) # Send a get request to the url driver.get('https://www.geeksforgeeks.org/') time.sleep(60) driver.quit() print(\"Done\")", "e": 1793, "s": 1229, "text": null }, { "code": null, "e": 1809, "s": 1793, "text": "Browser Output:" }, { "code": null, "e": 1824, "s": 1809, "text": "Chrome Browser" }, { "code": null, "e": 1841, "s": 1824, "text": "Terminal Output:" }, { "code": null, "e": 1850, "s": 1841, "text": "Terminal" }, { "code": null, "e": 1865, "s": 1850, "text": "Blogathon-2021" }, { "code": null, "e": 1880, "s": 1865, "text": "how-to-install" }, { "code": null, "e": 1887, "s": 1880, "text": "Picked" }, { "code": null, "e": 1903, "s": 1887, "text": "Python-selenium" }, { "code": null, "e": 1913, "s": 1903, "text": "Blogathon" }, { "code": null, "e": 1920, "s": 1913, "text": "How To" }, { "code": null, "e": 1939, "s": 1920, "text": "Installation Guide" }, { "code": null, "e": 1948, "s": 1939, "text": "TechTips" } ]
PHP | gmdate() Function
05 Jul, 2018 The gmdate() is an inbuilt function in PHP which is used to format a GMT/UTC date and time and return the formatted date strings. It is similar to the date() function but it returns the time in Greenwich Mean Time (GMT). Syntax: string gmdate ( $format, $timestamp ) Parameters: The gmdate() function accepts two parameters as mentioned above and described below: $format: It is a mandatory parameter which specifies the format of returned date and time. $timestamp: Timestamp is an optional parameter, if it is not included then current date and time will be used. Return Value: This function Returns a formatted date string on success and FALSE on failure and an E_WARNING. Below programs illustrate the gmdate() function. Program 1: <?php// PHP program to illustrate gmdate function // display date Jun 25 2018 23:21:50echo gmdate("M d Y H:i:s", mktime(23, 21, 50, 6, 25, 2018)) ."\n"; // display date World Wide Web Consortium// 2018-06-25T23:21:50+00:00echo gmdate(DATE_W3C, mktime(23, 21, 50, 6, 25, 2018)). "\n"; // display date as ISO-8601 formatecho gmdate(DATE_ISO8601, mktime(23, 21, 50, 6, 25, 2018)). "\n"; ?> Jun 25 2018 23:21:50 2018-06-25T23:21:50+00:00 2018-06-25T23:21:50+0000 Program 2: Passing one parameter, then it will return the current local time (time()). <?php// PHP program to illustrate gmdate function // display current date and time // Jun 28 2018 14:52:50echo gmdate("M d Y H:i:s") ."\n"; // display date World Wide Web Consortiumecho gmdate(DATE_W3C). "\n"; // display date as ISO-8601 formatecho gmdate(DATE_ISO8601). "\n"; ?> Jun 29 2018 06:32:34 2018-06-29T06:32:34+00:00 2018-06-29T06:32:34+0000 Similar Article: PHP | Date and Time PHP | time() Function Reference: http://php.net/manual/en/function.gmdate.php PHP-date-time PHP-function 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": "\n05 Jul, 2018" }, { "code": null, "e": 249, "s": 28, "text": "The gmdate() is an inbuilt function in PHP which is used to format a GMT/UTC date and time and return the formatted date strings. It is similar to the date() function but it returns the time in Greenwich Mean Time (GMT)." }, { "code": null, "e": 257, "s": 249, "text": "Syntax:" }, { "code": null, "e": 295, "s": 257, "text": "string gmdate ( $format, $timestamp )" }, { "code": null, "e": 392, "s": 295, "text": "Parameters: The gmdate() function accepts two parameters as mentioned above and described below:" }, { "code": null, "e": 483, "s": 392, "text": "$format: It is a mandatory parameter which specifies the format of returned date and time." }, { "code": null, "e": 594, "s": 483, "text": "$timestamp: Timestamp is an optional parameter, if it is not included then current date and time will be used." }, { "code": null, "e": 704, "s": 594, "text": "Return Value: This function Returns a formatted date string on success and FALSE on failure and an E_WARNING." }, { "code": null, "e": 753, "s": 704, "text": "Below programs illustrate the gmdate() function." }, { "code": null, "e": 764, "s": 753, "text": "Program 1:" }, { "code": "<?php// PHP program to illustrate gmdate function // display date Jun 25 2018 23:21:50echo gmdate(\"M d Y H:i:s\", mktime(23, 21, 50, 6, 25, 2018)) .\"\\n\"; // display date World Wide Web Consortium// 2018-06-25T23:21:50+00:00echo gmdate(DATE_W3C, mktime(23, 21, 50, 6, 25, 2018)). \"\\n\"; // display date as ISO-8601 formatecho gmdate(DATE_ISO8601, mktime(23, 21, 50, 6, 25, 2018)). \"\\n\"; ?>", "e": 1187, "s": 764, "text": null }, { "code": null, "e": 1260, "s": 1187, "text": "Jun 25 2018 23:21:50\n2018-06-25T23:21:50+00:00\n2018-06-25T23:21:50+0000\n" }, { "code": null, "e": 1347, "s": 1260, "text": "Program 2: Passing one parameter, then it will return the current local time (time())." }, { "code": "<?php// PHP program to illustrate gmdate function // display current date and time // Jun 28 2018 14:52:50echo gmdate(\"M d Y H:i:s\") .\"\\n\"; // display date World Wide Web Consortiumecho gmdate(DATE_W3C). \"\\n\"; // display date as ISO-8601 formatecho gmdate(DATE_ISO8601). \"\\n\"; ?>", "e": 1642, "s": 1347, "text": null }, { "code": null, "e": 1715, "s": 1642, "text": "Jun 29 2018 06:32:34\n2018-06-29T06:32:34+00:00\n2018-06-29T06:32:34+0000\n" }, { "code": null, "e": 1732, "s": 1715, "text": "Similar Article:" }, { "code": null, "e": 1752, "s": 1732, "text": "PHP | Date and Time" }, { "code": null, "e": 1774, "s": 1752, "text": "PHP | time() Function" }, { "code": null, "e": 1830, "s": 1774, "text": "Reference: http://php.net/manual/en/function.gmdate.php" }, { "code": null, "e": 1844, "s": 1830, "text": "PHP-date-time" }, { "code": null, "e": 1857, "s": 1844, "text": "PHP-function" }, { "code": null, "e": 1861, "s": 1857, "text": "PHP" }, { "code": null, "e": 1878, "s": 1861, "text": "Web Technologies" }, { "code": null, "e": 1882, "s": 1878, "text": "PHP" } ]
Reverse substrings between each pair of parenthesis
10 Mar, 2022 Given a string str that consists of lower case English letters and brackets. The task is to reverse the substrings in each pair of matching parentheses, starting from the innermost one. The result should not contain any brackets. Examples: Input: str = “(skeeg(for)skeeg)” Output: geeksforgeeks Input: str = “((ng)ipm(ca))” Output: camping Approach: This problem can be solved using a stack. First, whenever a ‘(‘ is encountered then push the index of the element into the stack, and whenever a ‘)’ is encountered then get the top element of the stack as the latest index and reverse the string between the current index and index from the top of the stack. Follow this for the rest of the string and finally print the updated string. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the modified stringstring reverseParentheses(string str, int len){ stack<int> st; for (int i = 0; i < len; i++) { // Push the index of the current // opening bracket if (str[i] == '(') { st.push(i); } // Reverse the substring starting // after the last encountered opening // bracket till the current character else if (str[i] == ')') { reverse(str.begin() + st.top() + 1, str.begin() + i); st.pop(); } } // To store the modified string string res = ""; for (int i = 0; i < len; i++) { if (str[i] != ')' && str[i] != '(') res += (str[i]); } return res;} // Driver codeint main(){ string str = "(skeeg(for)skeeg)"; int len = str.length(); cout << reverseParentheses(str, len); return 0;} // Java implementation of the approachimport java.io.*;import java.util.*;class GFG { static void reverse(char A[], int l, int h) { if (l < h) { char ch = A[l]; A[l] = A[h]; A[h] = ch; reverse(A, l + 1, h - 1); } } // Function to return the modified string static String reverseParentheses(String str, int len) { Stack<Integer> st = new Stack<Integer>(); for (int i = 0; i < len; i++) { // Push the index of the current // opening bracket if (str.charAt(i) == '(') { st.push(i); } // Reverse the substring starting // after the last encountered opening // bracket till the current character else if (str.charAt(i) == ')') { char[] A = str.toCharArray(); reverse(A, st.peek() + 1, i); str = String.copyValueOf(A); st.pop(); } } // To store the modified string String res = ""; for (int i = 0; i < len; i++) { if (str.charAt(i) != ')' && str.charAt(i) != '(') { res += (str.charAt(i)); } } return res; } // Driver code public static void main (String[] args) { String str = "(skeeg(for)skeeg)"; int len = str.length(); System.out.println(reverseParentheses(str, len)); }} // This code is contributed by avanitrachhadiya2155 # Python3 implementation of the approach # Function to return the modified stringdef reverseParentheses(strr, lenn): st = [] for i in range(lenn): # Push the index of the current # opening bracket if (strr[i] == '('): st.append(i) # Reverse the substring starting # after the last encountered opening # bracket till the current character else if (strr[i] == ')'): temp = strr[st[-1]:i + 1] strr = strr[:st[-1]] + temp[::-1] + \ strr[i + 1:] del st[-1] # To store the modified string res = "" for i in range(lenn): if (strr[i] != ')' and strr[i] != '('): res += (strr[i]) return res # Driver codeif __name__ == '__main__': strr = "(skeeg(for)skeeg)" lenn = len(strr) st = [i for i in strr] print(reverseParentheses(strr, lenn)) # This code is contributed by Mohit Kumar // C# implementation of the approachusing System;using System.Collections.Generic;using System.Text; class GFG{ static void reverse(char[] A, int l, int h){ if (l < h) { char ch = A[l]; A[l] = A[h]; A[h] = ch; reverse(A, l + 1, h - 1); }} // Function to return the modified stringstatic string reverseParentheses(string str, int len){ Stack<int> st = new Stack<int>(); for(int i = 0; i < len; i++) { // Push the index of the current // opening bracket if (str[i] == '(') { st.Push(i); } // Reverse the substring starting // after the last encountered opening // bracket till the current character else if (str[i] == ')') { char[] A = str.ToCharArray(); reverse(A, st.Peek() + 1, i); str = new string(A); st.Pop(); } } // To store the modified string string res = ""; for(int i = 0; i < len; i++) { if (str[i] != ')' && str[i] != '(') { res += str[i]; } } return res;} // Driver codestatic public void Main(){ string str = "(skeeg(for)skeeg)"; int len = str.Length; Console.WriteLine(reverseParentheses(str, len));}} // This code is contributed by rag2127 <script>// Javascript implementation of the approachfunction reverse(A,l,h){ if (l < h) { let ch = A[l]; A[l] = A[h]; A[h] = ch; reverse(A, l + 1, h - 1); }} // Function to return the modified stringfunction reverseParentheses(str,len){ let st = []; for (let i = 0; i < len; i++) { // Push the index of the current // opening bracket if (str[i] == '(') { st.push(i); } // Reverse the substring starting // after the last encountered opening // bracket till the current character else if (str[i] == ')') { let A = [...str] reverse(A, st[st.length-1] + 1, i); str = [...A]; st.pop(); } } // To store the modified string let res = ""; for (let i = 0; i < len; i++) { if (str[i] != ')' && str[i] != '(') { res += (str[i]); } } return res;} // Driver codelet str = "(skeeg(for)skeeg)";let len = str.length;document.write(reverseParentheses(str, len)); // This code is contributed by patel2127</script> geeksforgeeks mohit kumar 29 avanitrachhadiya2155 rag2127 patel2127 shashikantsolanki042 ruhelaa48 surinderdawra388 simmytarika5 substring Competitive Programming Stack Strings Strings Stack Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n10 Mar, 2022" }, { "code": null, "e": 284, "s": 54, "text": "Given a string str that consists of lower case English letters and brackets. The task is to reverse the substrings in each pair of matching parentheses, starting from the innermost one. The result should not contain any brackets." }, { "code": null, "e": 296, "s": 284, "text": "Examples: " }, { "code": null, "e": 351, "s": 296, "text": "Input: str = “(skeeg(for)skeeg)” Output: geeksforgeeks" }, { "code": null, "e": 397, "s": 351, "text": "Input: str = “((ng)ipm(ca))” Output: camping " }, { "code": null, "e": 792, "s": 397, "text": "Approach: This problem can be solved using a stack. First, whenever a ‘(‘ is encountered then push the index of the element into the stack, and whenever a ‘)’ is encountered then get the top element of the stack as the latest index and reverse the string between the current index and index from the top of the stack. Follow this for the rest of the string and finally print the updated string." }, { "code": null, "e": 845, "s": 792, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 849, "s": 845, "text": "C++" }, { "code": null, "e": 854, "s": 849, "text": "Java" }, { "code": null, "e": 862, "s": 854, "text": "Python3" }, { "code": null, "e": 865, "s": 862, "text": "C#" }, { "code": null, "e": 876, "s": 865, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the modified stringstring reverseParentheses(string str, int len){ stack<int> st; for (int i = 0; i < len; i++) { // Push the index of the current // opening bracket if (str[i] == '(') { st.push(i); } // Reverse the substring starting // after the last encountered opening // bracket till the current character else if (str[i] == ')') { reverse(str.begin() + st.top() + 1, str.begin() + i); st.pop(); } } // To store the modified string string res = \"\"; for (int i = 0; i < len; i++) { if (str[i] != ')' && str[i] != '(') res += (str[i]); } return res;} // Driver codeint main(){ string str = \"(skeeg(for)skeeg)\"; int len = str.length(); cout << reverseParentheses(str, len); return 0;}", "e": 1842, "s": 876, "text": null }, { "code": "// Java implementation of the approachimport java.io.*;import java.util.*;class GFG { static void reverse(char A[], int l, int h) { if (l < h) { char ch = A[l]; A[l] = A[h]; A[h] = ch; reverse(A, l + 1, h - 1); } } // Function to return the modified string static String reverseParentheses(String str, int len) { Stack<Integer> st = new Stack<Integer>(); for (int i = 0; i < len; i++) { // Push the index of the current // opening bracket if (str.charAt(i) == '(') { st.push(i); } // Reverse the substring starting // after the last encountered opening // bracket till the current character else if (str.charAt(i) == ')') { char[] A = str.toCharArray(); reverse(A, st.peek() + 1, i); str = String.copyValueOf(A); st.pop(); } } // To store the modified string String res = \"\"; for (int i = 0; i < len; i++) { if (str.charAt(i) != ')' && str.charAt(i) != '(') { res += (str.charAt(i)); } } return res; } // Driver code public static void main (String[] args) { String str = \"(skeeg(for)skeeg)\"; int len = str.length(); System.out.println(reverseParentheses(str, len)); }} // This code is contributed by avanitrachhadiya2155", "e": 3178, "s": 1842, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the modified stringdef reverseParentheses(strr, lenn): st = [] for i in range(lenn): # Push the index of the current # opening bracket if (strr[i] == '('): st.append(i) # Reverse the substring starting # after the last encountered opening # bracket till the current character else if (strr[i] == ')'): temp = strr[st[-1]:i + 1] strr = strr[:st[-1]] + temp[::-1] + \\ strr[i + 1:] del st[-1] # To store the modified string res = \"\" for i in range(lenn): if (strr[i] != ')' and strr[i] != '('): res += (strr[i]) return res # Driver codeif __name__ == '__main__': strr = \"(skeeg(for)skeeg)\" lenn = len(strr) st = [i for i in strr] print(reverseParentheses(strr, lenn)) # This code is contributed by Mohit Kumar", "e": 4111, "s": 3178, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections.Generic;using System.Text; class GFG{ static void reverse(char[] A, int l, int h){ if (l < h) { char ch = A[l]; A[l] = A[h]; A[h] = ch; reverse(A, l + 1, h - 1); }} // Function to return the modified stringstatic string reverseParentheses(string str, int len){ Stack<int> st = new Stack<int>(); for(int i = 0; i < len; i++) { // Push the index of the current // opening bracket if (str[i] == '(') { st.Push(i); } // Reverse the substring starting // after the last encountered opening // bracket till the current character else if (str[i] == ')') { char[] A = str.ToCharArray(); reverse(A, st.Peek() + 1, i); str = new string(A); st.Pop(); } } // To store the modified string string res = \"\"; for(int i = 0; i < len; i++) { if (str[i] != ')' && str[i] != '(') { res += str[i]; } } return res;} // Driver codestatic public void Main(){ string str = \"(skeeg(for)skeeg)\"; int len = str.Length; Console.WriteLine(reverseParentheses(str, len));}} // This code is contributed by rag2127", "e": 5443, "s": 4111, "text": null }, { "code": "<script>// Javascript implementation of the approachfunction reverse(A,l,h){ if (l < h) { let ch = A[l]; A[l] = A[h]; A[h] = ch; reverse(A, l + 1, h - 1); }} // Function to return the modified stringfunction reverseParentheses(str,len){ let st = []; for (let i = 0; i < len; i++) { // Push the index of the current // opening bracket if (str[i] == '(') { st.push(i); } // Reverse the substring starting // after the last encountered opening // bracket till the current character else if (str[i] == ')') { let A = [...str] reverse(A, st[st.length-1] + 1, i); str = [...A]; st.pop(); } } // To store the modified string let res = \"\"; for (let i = 0; i < len; i++) { if (str[i] != ')' && str[i] != '(') { res += (str[i]); } } return res;} // Driver codelet str = \"(skeeg(for)skeeg)\";let len = str.length;document.write(reverseParentheses(str, len)); // This code is contributed by patel2127</script>", "e": 6546, "s": 5443, "text": null }, { "code": null, "e": 6560, "s": 6546, "text": "geeksforgeeks" }, { "code": null, "e": 6577, "s": 6562, "text": "mohit kumar 29" }, { "code": null, "e": 6598, "s": 6577, "text": "avanitrachhadiya2155" }, { "code": null, "e": 6606, "s": 6598, "text": "rag2127" }, { "code": null, "e": 6616, "s": 6606, "text": "patel2127" }, { "code": null, "e": 6637, "s": 6616, "text": "shashikantsolanki042" }, { "code": null, "e": 6647, "s": 6637, "text": "ruhelaa48" }, { "code": null, "e": 6664, "s": 6647, "text": "surinderdawra388" }, { "code": null, "e": 6677, "s": 6664, "text": "simmytarika5" }, { "code": null, "e": 6687, "s": 6677, "text": "substring" }, { "code": null, "e": 6711, "s": 6687, "text": "Competitive Programming" }, { "code": null, "e": 6717, "s": 6711, "text": "Stack" }, { "code": null, "e": 6725, "s": 6717, "text": "Strings" }, { "code": null, "e": 6733, "s": 6725, "text": "Strings" }, { "code": null, "e": 6739, "s": 6733, "text": "Stack" } ]
Python | Pandas Series.str.encode()
27 Mar, 2019 Series.str can be used to access the values of the series as strings and apply several methods to it. Pandas Series.str.encode() function is used to encode character string in the Series/Index using indicated encoding. Equivalent to str.encode(). Syntax: Series.str.encode(encoding, errors=’strict’) Parameter :encoding : strerrors : str, optional Returns : encoded : Series/Index of objects Example #1: Use Series.str.encode() function to encode the character strings present in the underlying data of the given series object. Use ‘raw_unicode_escape’ for encoding. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New_York', 'Lisbon', 'Tokyo', 'Paris', 'Munich']) # Creating the indexidx = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] # set the indexsr.index = idx # Print the seriesprint(sr) Output : Now we will use Series.str.encode() function to encode the character strings present in the underlying data of the given series object. # use 'raw_unicode_escape' encodingresult = sr.str.encode(encoding = 'raw_unicode_escape') # print the resultprint(result) Output : As we can see in the output, the Series.str.encode() function has successfully encoded the strings in the given series object. Example #2 : Use Series.str.encode() function to encode the character strings present in the underlying data of the given series object. Use ‘punycode’ for encoding. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['Mike', 'Alessa', 'Nick', 'Kim', 'Britney']) # Creating the indexidx = ['Name 1', 'Name 2', 'Name 3', 'Name 4', 'Name 5'] # set the indexsr.index = idx # Print the seriesprint(sr) Output : Now we will use Series.str.encode() function to encode the character strings present in the underlying data of the given series object. # use 'punycode' encodingresult = sr.str.encode(encoding = 'punycode') # print the resultprint(result) Output : As we can see in the output, the Series.str.encode() function has successfully encoded the strings in the given series object. Python-pandas Python-pandas-series-str Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n27 Mar, 2019" }, { "code": null, "e": 299, "s": 52, "text": "Series.str can be used to access the values of the series as strings and apply several methods to it. Pandas Series.str.encode() function is used to encode character string in the Series/Index using indicated encoding. Equivalent to str.encode()." }, { "code": null, "e": 352, "s": 299, "text": "Syntax: Series.str.encode(encoding, errors=’strict’)" }, { "code": null, "e": 400, "s": 352, "text": "Parameter :encoding : strerrors : str, optional" }, { "code": null, "e": 444, "s": 400, "text": "Returns : encoded : Series/Index of objects" }, { "code": null, "e": 619, "s": 444, "text": "Example #1: Use Series.str.encode() function to encode the character strings present in the underlying data of the given series object. Use ‘raw_unicode_escape’ for encoding." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New_York', 'Lisbon', 'Tokyo', 'Paris', 'Munich']) # Creating the indexidx = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] # set the indexsr.index = idx # Print the seriesprint(sr)", "e": 890, "s": 619, "text": null }, { "code": null, "e": 899, "s": 890, "text": "Output :" }, { "code": null, "e": 1035, "s": 899, "text": "Now we will use Series.str.encode() function to encode the character strings present in the underlying data of the given series object." }, { "code": "# use 'raw_unicode_escape' encodingresult = sr.str.encode(encoding = 'raw_unicode_escape') # print the resultprint(result)", "e": 1159, "s": 1035, "text": null }, { "code": null, "e": 1168, "s": 1159, "text": "Output :" }, { "code": null, "e": 1295, "s": 1168, "text": "As we can see in the output, the Series.str.encode() function has successfully encoded the strings in the given series object." }, { "code": null, "e": 1461, "s": 1295, "text": "Example #2 : Use Series.str.encode() function to encode the character strings present in the underlying data of the given series object. Use ‘punycode’ for encoding." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['Mike', 'Alessa', 'Nick', 'Kim', 'Britney']) # Creating the indexidx = ['Name 1', 'Name 2', 'Name 3', 'Name 4', 'Name 5'] # set the indexsr.index = idx # Print the seriesprint(sr)", "e": 1726, "s": 1461, "text": null }, { "code": null, "e": 1735, "s": 1726, "text": "Output :" }, { "code": null, "e": 1871, "s": 1735, "text": "Now we will use Series.str.encode() function to encode the character strings present in the underlying data of the given series object." }, { "code": "# use 'punycode' encodingresult = sr.str.encode(encoding = 'punycode') # print the resultprint(result)", "e": 1975, "s": 1871, "text": null }, { "code": null, "e": 1984, "s": 1975, "text": "Output :" }, { "code": null, "e": 2111, "s": 1984, "text": "As we can see in the output, the Series.str.encode() function has successfully encoded the strings in the given series object." }, { "code": null, "e": 2125, "s": 2111, "text": "Python-pandas" }, { "code": null, "e": 2150, "s": 2125, "text": "Python-pandas-series-str" }, { "code": null, "e": 2157, "s": 2150, "text": "Python" } ]
What are reserved keywords in C#?
Keywords are reserved words predefined to the C# compiler. These keywords cannot be used as identifiers. If you want to use these keywords as identifiers, you may prefix the keyword with the @ character. In C#, some identifiers have special meaning in the context of code, such as get and set are called contextual keywords. The following table lists the reserved keywords − Let us see an example of using bool reserved keyword in C# − Live Demo using System; using System.Collections; class Demo { static void Main() { bool[] arr = new bool[5]; arr[0] = true; arr[1] = true; arr[2] = false; arr[3] = false; BitArray bArr = new BitArray(arr); foreach (bool b in bArr) { Console.WriteLine(b); } bool str = arr[1]; Console.WriteLine("Value of 2nd element:"+str); } } True True False False False Value of 2nd element:True
[ { "code": null, "e": 1391, "s": 1187, "text": "Keywords are reserved words predefined to the C# compiler. These keywords cannot be used as identifiers. If you want to use these keywords as identifiers, you may prefix the keyword with the @ character." }, { "code": null, "e": 1512, "s": 1391, "text": "In C#, some identifiers have special meaning in the context of code, such as get and set are called contextual keywords." }, { "code": null, "e": 1562, "s": 1512, "text": "The following table lists the reserved keywords −" }, { "code": null, "e": 1623, "s": 1562, "text": "Let us see an example of using bool reserved keyword in C# −" }, { "code": null, "e": 1634, "s": 1623, "text": " Live Demo" }, { "code": null, "e": 2032, "s": 1634, "text": "using System;\nusing System.Collections;\n\nclass Demo {\n static void Main() {\n bool[] arr = new bool[5];\n arr[0] = true;\n arr[1] = true;\n arr[2] = false;\n arr[3] = false;\n\n BitArray bArr = new BitArray(arr);\n\n foreach (bool b in bArr) {\n Console.WriteLine(b);\n }\n\n bool str = arr[1];\n Console.WriteLine(\"Value of 2nd element:\"+str);\n }\n}" }, { "code": null, "e": 2086, "s": 2032, "text": "True\nTrue\nFalse\nFalse\nFalse\nValue of 2nd element:True" } ]
Python | Check if any element occurs n times in given list
08 Sep, 2020 Given a list, the task is to find whether any element occurs ‘n’ times in given list of integers. It will basically check for the first element that occurs n number of times. Examples: Input: l = [1, 2, 3, 4, 0, 4, 3, 2, 1, 2], n = 3 Output : 2 Input: l = [1, 2, 3, 4, 0, 4, 3, 2, 1, 2, 1, 1], n = 4 Output : 1 Below are some methods to do the task in Python – Method 1: Using Simple Iteration and Sort Python3 # Python code to find occurrence of any element# appearing 'n' times # Input Initialisationinput = [1, 2, 3, 0, 4, 3, 4, 0, 0] # Sort Inputinput.sort() # Constants Declarationn = 3prev = -1count = 0flag = 0 # Iteratingfor item in input: if item == prev: count = count + 1 else: count = 1 prev = item if count == n: flag = 1 print("There are {} occurrences of {} in {}".format(n, item, input)) break # If no element is not found.if flag == 0: print("No occurrences found") Output : There are 3 occurrences of 0 in [0, 0, 0, 1, 2, 3, 3, 4, 4] Method 2: Using Count Python3 # Python code to find occurrence of any element# appearing 'n' times # Input list initialisationinput = [1, 2, 3, 4, 0, 4, 3, 4] # Constant declarationn = 3 # printprint("There are {} occurrences of {} in {}".format(input.count(n), n, input)) Output : There are 2 occurrences of 3 in [1, 2, 3, 4, 0, 4, 3, 4] Method 3: Using defaultdictWe first populate item of list in a dictionary and then we find whether count of any element is equal to n. Python3 # Python code to find occurrence of any element# appearing 'n' times # importingfrom collections import defaultdict # Dictionary declarationdic = defaultdict(int) # Input list initialisationInput = [9, 8, 7, 6, 5, 9, 2] # Dictionary populatefor i in Input: dic[i]+= 1 # constant declarationn = 2flag = 0 # Finding from dictionaryfor element in Input: if element in dic.keys() and dic[element] == n: print("Yes, {} has {} occurrence in {}.".format(element, n, Input)) flag = 1 break # if element not found.if flag == 0: print("No occurrences found") Output : Yes, 9 has 2 occurrence in [9, 8, 7, 6, 5, 9, 2] alukas07 askudlarek 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": "\n08 Sep, 2020" }, { "code": null, "e": 215, "s": 28, "text": "Given a list, the task is to find whether any element occurs ‘n’ times in given list of integers. It will basically check for the first element that occurs n number of times. Examples: " }, { "code": null, "e": 349, "s": 215, "text": "Input: l = [1, 2, 3, 4, 0, 4, 3, 2, 1, 2], n = 3\nOutput : 2\n\nInput: l = [1, 2, 3, 4, 0, 4, 3, 2, 1, 2, 1, 1], n = 4\nOutput : 1\n\n\n" }, { "code": null, "e": 443, "s": 349, "text": "Below are some methods to do the task in Python – Method 1: Using Simple Iteration and Sort " }, { "code": null, "e": 451, "s": 443, "text": "Python3" }, { "code": "# Python code to find occurrence of any element# appearing 'n' times # Input Initialisationinput = [1, 2, 3, 0, 4, 3, 4, 0, 0] # Sort Inputinput.sort() # Constants Declarationn = 3prev = -1count = 0flag = 0 # Iteratingfor item in input: if item == prev: count = count + 1 else: count = 1 prev = item if count == n: flag = 1 print(\"There are {} occurrences of {} in {}\".format(n, item, input)) break # If no element is not found.if flag == 0: print(\"No occurrences found\")", "e": 978, "s": 451, "text": null }, { "code": null, "e": 989, "s": 978, "text": "Output : " }, { "code": null, "e": 1051, "s": 989, "text": "There are 3 occurrences of 0 in [0, 0, 0, 1, 2, 3, 3, 4, 4]\n\n" }, { "code": null, "e": 1076, "s": 1051, "text": " Method 2: Using Count " }, { "code": null, "e": 1084, "s": 1076, "text": "Python3" }, { "code": "# Python code to find occurrence of any element# appearing 'n' times # Input list initialisationinput = [1, 2, 3, 4, 0, 4, 3, 4] # Constant declarationn = 3 # printprint(\"There are {} occurrences of {} in {}\".format(input.count(n), n, input))", "e": 1327, "s": 1084, "text": null }, { "code": null, "e": 1338, "s": 1327, "text": "Output : " }, { "code": null, "e": 1397, "s": 1338, "text": "There are 2 occurrences of 3 in [1, 2, 3, 4, 0, 4, 3, 4]\n\n" }, { "code": null, "e": 1535, "s": 1397, "text": " Method 3: Using defaultdictWe first populate item of list in a dictionary and then we find whether count of any element is equal to n. " }, { "code": null, "e": 1543, "s": 1535, "text": "Python3" }, { "code": "# Python code to find occurrence of any element# appearing 'n' times # importingfrom collections import defaultdict # Dictionary declarationdic = defaultdict(int) # Input list initialisationInput = [9, 8, 7, 6, 5, 9, 2] # Dictionary populatefor i in Input: dic[i]+= 1 # constant declarationn = 2flag = 0 # Finding from dictionaryfor element in Input: if element in dic.keys() and dic[element] == n: print(\"Yes, {} has {} occurrence in {}.\".format(element, n, Input)) flag = 1 break # if element not found.if flag == 0: print(\"No occurrences found\")", "e": 2122, "s": 1543, "text": null }, { "code": null, "e": 2133, "s": 2122, "text": "Output : " }, { "code": null, "e": 2184, "s": 2133, "text": "Yes, 9 has 2 occurrence in [9, 8, 7, 6, 5, 9, 2]\n\n" }, { "code": null, "e": 2195, "s": 2186, "text": "alukas07" }, { "code": null, "e": 2206, "s": 2195, "text": "askudlarek" }, { "code": null, "e": 2227, "s": 2206, "text": "Python list-programs" }, { "code": null, "e": 2234, "s": 2227, "text": "Python" }, { "code": null, "e": 2250, "s": 2234, "text": "Python Programs" }, { "code": null, "e": 2348, "s": 2250, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2366, "s": 2348, "text": "Python Dictionary" }, { "code": null, "e": 2408, "s": 2366, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2430, "s": 2408, "text": "Enumerate() in Python" }, { "code": null, "e": 2465, "s": 2430, "text": "Read a file line by line in Python" }, { "code": null, "e": 2491, "s": 2465, "text": "Python String | replace()" }, { "code": null, "e": 2534, "s": 2491, "text": "Python program to convert a list to string" }, { "code": null, "e": 2556, "s": 2534, "text": "Defaultdict in Python" }, { "code": null, "e": 2595, "s": 2556, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2633, "s": 2595, "text": "Python | Convert a list to dictionary" } ]
How to scrape multiple pages using Selenium in Python?
03 Mar, 2021 As we know, selenium is a web-based automation tool that helps us to automate browsers. Selenium is an Open-Source testing tool which means we can easily download it from the internet and use it. With the help of Selenium, we can also scrap the data from the webpages. Here, In this article, we are going to discuss how to scrap multiple pages using selenium. There can be many ways for scraping the data from webpages, we will discuss one of them. Looping over the page number is the most simple way for scraping the data. We can use an incrementing counter for changing one page to another page. As many times, our loop will run, the program will scrap the data from webpages. First Page URL: https://webscraper.io/test-sites/e-commerce/static/computers/laptops?page=1 At last, the Only page numbers will increment like page=1, page=2... Now, Let see for second page URL. Second Page URL: https://webscraper.io/test-sites/e-commerce/static/computers/laptops?page=2 Now, Let discuss the approach Installation: Our first step, before writing a single line of code. We have to install the selenium for using webdriver class. Through which we can instantiate the browsers and get the webpage from the targeted URL. pip install selenium Once selenium installed successfully. Now, we can go to the next step for installing our next package. The next package is webdriver_manager, Let install it first, pip install webdriver_manager Yeah! We are done with the Installation of Important or necessary packages Now, Let see the implementation below: Here in this program, with the help of for loop, We will scrap two webpages because we are running for loop two times only. If we want to scrap more pages, so, we can increase the loop count. Store the page URL in a string variable page_url, and increment its page number count using the for loop counter. Now, Instantiate the Chrome web browser Open the page URL in Chrome browser using driver object Now, Scraping data from the webpage using element locators like find_elements_by_class_name method. This method will return a list of types of elements. We will store all necessary data inside the list variable such as title, price, description, and rating. Store all the data as list of list of a single product. In element_list, we will store this resultant list. Finally, Print element_list. Then close the driver object. Python3 # importing necessary packagesfrom selenium import webdriverfrom webdriver_manager.chrome import ChromeDriverManager # for holding the resultant listelement_list = [] for page in range(1, 3, 1): page_url = "https://webscraper.io/test-sites/e-commerce/static/computers/laptops?page=" + str(page) driver = webdriver.Chrome(ChromeDriverManager().install()) driver.get(page_url) title = driver.find_elements_by_class_name("title") price = driver.find_elements_by_class_name("price") description = driver.find_elements_by_class_name("description") rating = driver.find_elements_by_class_name("ratings") for i in range(len(title)): element_list.append([title[i].text, price[i].text, description[i].text, rating[i].text]) print(element_list) #closing the driverdriver.close() Output: Storing data in Excel File: Now, We will store the data from element_list to Excel file using xlsxwriter package. So, First, we have to install this xlsxwriter package. pip install xlsxwriter Once’s installation get done. Let’s see the simple code through which we can convert the list of elements into an Excel file. Python3 with xlsxwriter.Workbook('result.xlsx') as workbook: worksheet = workbook.add_worksheet() for row_num, data in enumerate(element_list): worksheet.write_row(row_num, 0, data) First, we are creating a workbook named result.xlsx. After that, We will consider the list of a single product as a single row. Enumerate the list as a row and its data as columns inside the Excel file which is starting as a row number 0 and column number 0. Now, Let’s see its implementation: Python3 import xlsxwriterfrom selenium import webdriverfrom webdriver_manager.chrome import ChromeDriverManager element_list = [] for page in range(1, 3, 1): page_url = "https://webscraper.io/test-sites/e-commerce/static/computers/laptops?page=" + str(page) driver = webdriver.Chrome(ChromeDriverManager().install()) driver.get(page_url) title = driver.find_elements_by_class_name("title") price = driver.find_elements_by_class_name("price") description = driver.find_elements_by_class_name("description") rating = driver.find_elements_by_class_name("ratings") for i in range(len(title)): element_list.append([title[i].text, price[i].text, description[i].text, rating[i].text]) with xlsxwriter.Workbook('result.xlsx') as workbook: worksheet = workbook.add_worksheet() for row_num, data in enumerate(element_list): worksheet.write_row(row_num, 0, data) driver.close() Output: Output file. Click here for downloading the output file. Picked Python Selenium-Exercises Python-selenium Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n03 Mar, 2021" }, { "code": null, "e": 413, "s": 52, "text": "As we know, selenium is a web-based automation tool that helps us to automate browsers. Selenium is an Open-Source testing tool which means we can easily download it from the internet and use it. With the help of Selenium, we can also scrap the data from the webpages. Here, In this article, we are going to discuss how to scrap multiple pages using selenium. " }, { "code": null, "e": 732, "s": 413, "text": "There can be many ways for scraping the data from webpages, we will discuss one of them. Looping over the page number is the most simple way for scraping the data. We can use an incrementing counter for changing one page to another page. As many times, our loop will run, the program will scrap the data from webpages." }, { "code": null, "e": 748, "s": 732, "text": "First Page URL:" }, { "code": null, "e": 824, "s": 748, "text": "https://webscraper.io/test-sites/e-commerce/static/computers/laptops?page=1" }, { "code": null, "e": 927, "s": 824, "text": "At last, the Only page numbers will increment like page=1, page=2... Now, Let see for second page URL." }, { "code": null, "e": 944, "s": 927, "text": "Second Page URL:" }, { "code": null, "e": 1020, "s": 944, "text": "https://webscraper.io/test-sites/e-commerce/static/computers/laptops?page=2" }, { "code": null, "e": 1050, "s": 1020, "text": "Now, Let discuss the approach" }, { "code": null, "e": 1064, "s": 1050, "text": "Installation:" }, { "code": null, "e": 1266, "s": 1064, "text": "Our first step, before writing a single line of code. We have to install the selenium for using webdriver class. Through which we can instantiate the browsers and get the webpage from the targeted URL." }, { "code": null, "e": 1287, "s": 1266, "text": "pip install selenium" }, { "code": null, "e": 1391, "s": 1287, "text": "Once selenium installed successfully. Now, we can go to the next step for installing our next package. " }, { "code": null, "e": 1452, "s": 1391, "text": "The next package is webdriver_manager, Let install it first," }, { "code": null, "e": 1482, "s": 1452, "text": "pip install webdriver_manager" }, { "code": null, "e": 1557, "s": 1482, "text": "Yeah! We are done with the Installation of Important or necessary packages" }, { "code": null, "e": 1596, "s": 1557, "text": "Now, Let see the implementation below:" }, { "code": null, "e": 1788, "s": 1596, "text": "Here in this program, with the help of for loop, We will scrap two webpages because we are running for loop two times only. If we want to scrap more pages, so, we can increase the loop count." }, { "code": null, "e": 1902, "s": 1788, "text": "Store the page URL in a string variable page_url, and increment its page number count using the for loop counter." }, { "code": null, "e": 1942, "s": 1902, "text": "Now, Instantiate the Chrome web browser" }, { "code": null, "e": 1998, "s": 1942, "text": "Open the page URL in Chrome browser using driver object" }, { "code": null, "e": 2257, "s": 1998, "text": "Now, Scraping data from the webpage using element locators like find_elements_by_class_name method. This method will return a list of types of elements. We will store all necessary data inside the list variable such as title, price, description, and rating." }, { "code": null, "e": 2365, "s": 2257, "text": "Store all the data as list of list of a single product. In element_list, we will store this resultant list." }, { "code": null, "e": 2424, "s": 2365, "text": "Finally, Print element_list. Then close the driver object." }, { "code": null, "e": 2432, "s": 2424, "text": "Python3" }, { "code": "# importing necessary packagesfrom selenium import webdriverfrom webdriver_manager.chrome import ChromeDriverManager # for holding the resultant listelement_list = [] for page in range(1, 3, 1): page_url = \"https://webscraper.io/test-sites/e-commerce/static/computers/laptops?page=\" + str(page) driver = webdriver.Chrome(ChromeDriverManager().install()) driver.get(page_url) title = driver.find_elements_by_class_name(\"title\") price = driver.find_elements_by_class_name(\"price\") description = driver.find_elements_by_class_name(\"description\") rating = driver.find_elements_by_class_name(\"ratings\") for i in range(len(title)): element_list.append([title[i].text, price[i].text, description[i].text, rating[i].text]) print(element_list) #closing the driverdriver.close()", "e": 3242, "s": 2432, "text": null }, { "code": null, "e": 3250, "s": 3242, "text": "Output:" }, { "code": null, "e": 3278, "s": 3250, "text": "Storing data in Excel File:" }, { "code": null, "e": 3419, "s": 3278, "text": "Now, We will store the data from element_list to Excel file using xlsxwriter package. So, First, we have to install this xlsxwriter package." }, { "code": null, "e": 3442, "s": 3419, "text": "pip install xlsxwriter" }, { "code": null, "e": 3568, "s": 3442, "text": "Once’s installation get done. Let’s see the simple code through which we can convert the list of elements into an Excel file." }, { "code": null, "e": 3576, "s": 3568, "text": "Python3" }, { "code": "with xlsxwriter.Workbook('result.xlsx') as workbook: worksheet = workbook.add_worksheet() for row_num, data in enumerate(element_list): worksheet.write_row(row_num, 0, data)", "e": 3765, "s": 3576, "text": null }, { "code": null, "e": 4025, "s": 3765, "text": "First, we are creating a workbook named result.xlsx. After that, We will consider the list of a single product as a single row. Enumerate the list as a row and its data as columns inside the Excel file which is starting as a row number 0 and column number 0. " }, { "code": null, "e": 4060, "s": 4025, "text": "Now, Let’s see its implementation:" }, { "code": null, "e": 4068, "s": 4060, "text": "Python3" }, { "code": "import xlsxwriterfrom selenium import webdriverfrom webdriver_manager.chrome import ChromeDriverManager element_list = [] for page in range(1, 3, 1): page_url = \"https://webscraper.io/test-sites/e-commerce/static/computers/laptops?page=\" + str(page) driver = webdriver.Chrome(ChromeDriverManager().install()) driver.get(page_url) title = driver.find_elements_by_class_name(\"title\") price = driver.find_elements_by_class_name(\"price\") description = driver.find_elements_by_class_name(\"description\") rating = driver.find_elements_by_class_name(\"ratings\") for i in range(len(title)): element_list.append([title[i].text, price[i].text, description[i].text, rating[i].text]) with xlsxwriter.Workbook('result.xlsx') as workbook: worksheet = workbook.add_worksheet() for row_num, data in enumerate(element_list): worksheet.write_row(row_num, 0, data) driver.close()", "e": 4983, "s": 4068, "text": null }, { "code": null, "e": 4991, "s": 4983, "text": "Output:" }, { "code": null, "e": 5004, "s": 4991, "text": "Output file." }, { "code": null, "e": 5048, "s": 5004, "text": "Click here for downloading the output file." }, { "code": null, "e": 5055, "s": 5048, "text": "Picked" }, { "code": null, "e": 5081, "s": 5055, "text": "Python Selenium-Exercises" }, { "code": null, "e": 5097, "s": 5081, "text": "Python-selenium" }, { "code": null, "e": 5121, "s": 5097, "text": "Technical Scripter 2020" }, { "code": null, "e": 5128, "s": 5121, "text": "Python" }, { "code": null, "e": 5147, "s": 5128, "text": "Technical Scripter" } ]
How to submit a form on Enter button using jQuery ?
18 Aug, 2020 Given an HTML form and the task is to submit the form after clicking the ‘Enter’ button using jQuery. To submit the form using ‘Enter’ button, we will use jQuery keypress() method and to check the ‘Enter’ button is pressed or not, we will use ‘Enter’ button key code value. <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <script src="https://code.jquery.com/jquery-3.5.1.min.js"integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"> </script> <meta name="viewport" content= "width=device-width, initial-scale=1.0"></head> <body> <h3 style="color: green;font-size: 28px;"> GeeksforGeeks </h3> <form class="info"> <input name="fname" /><br> <input name="lname" /><br> <button type="submit">Submit</button> </form></body> </html> JavaScript Code: <script> // Wait for document to load $(document).ready(() => { $('.info').on('submit', () => { // prevents default behaviour // Prevents event propagation return false; }); }); $('.info').keypress((e) => { // Enter key corresponds to number 13 if (e.which === 13) { $('.info').submit(); console.log('form submitted'); } })</script> Explanation:We use the jQuery event.which to check the keycode on the keypress. The keycode for the enter key is 13, so if the keycode matches to thirteen then we use the .submit() method on the form element to submit the form. Complete Code: <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity= "sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"> </script> <meta name="viewport" content= "width=device-width, initial-scale=1.0"></head> <body> <h3 style="color: green;font-size: 28px;"> GeeksforGeeks </h3> <form class="info"> <input name="fname" /><br><br> <input name="lname" /><br><br> <button type="submit">Submit</button> </form> <script> $(document).ready(() => { $('.info').on('submit', () => { return false; }); }); $('.info').keypress((e) => { if (e.which === 13) { $('.info').submit(); alert('Form submitted successfully.') } }) </script></body> </html> Output: CSS-Misc HTML-Misc jQuery-Misc Picked CSS HTML JQuery Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Aug, 2020" }, { "code": null, "e": 302, "s": 28, "text": "Given an HTML form and the task is to submit the form after clicking the ‘Enter’ button using jQuery. To submit the form using ‘Enter’ button, we will use jQuery keypress() method and to check the ‘Enter’ button is pressed or not, we will use ‘Enter’ button key code value." }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <script src=\"https://code.jquery.com/jquery-3.5.1.min.js\"integrity=\"sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=\" crossorigin=\"anonymous\"> </script> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"></head> <body> <h3 style=\"color: green;font-size: 28px;\"> GeeksforGeeks </h3> <form class=\"info\"> <input name=\"fname\" /><br> <input name=\"lname\" /><br> <button type=\"submit\">Submit</button> </form></body> </html>", "e": 876, "s": 302, "text": null }, { "code": null, "e": 893, "s": 876, "text": "JavaScript Code:" }, { "code": "<script> // Wait for document to load $(document).ready(() => { $('.info').on('submit', () => { // prevents default behaviour // Prevents event propagation return false; }); }); $('.info').keypress((e) => { // Enter key corresponds to number 13 if (e.which === 13) { $('.info').submit(); console.log('form submitted'); } })</script>", "e": 1337, "s": 893, "text": null }, { "code": null, "e": 1565, "s": 1337, "text": "Explanation:We use the jQuery event.which to check the keycode on the keypress. The keycode for the enter key is 13, so if the keycode matches to thirteen then we use the .submit() method on the form element to submit the form." }, { "code": null, "e": 1580, "s": 1565, "text": "Complete Code:" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <script src=\"https://code.jquery.com/jquery-3.5.1.min.js\" integrity= \"sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=\" crossorigin=\"anonymous\"> </script> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"></head> <body> <h3 style=\"color: green;font-size: 28px;\"> GeeksforGeeks </h3> <form class=\"info\"> <input name=\"fname\" /><br><br> <input name=\"lname\" /><br><br> <button type=\"submit\">Submit</button> </form> <script> $(document).ready(() => { $('.info').on('submit', () => { return false; }); }); $('.info').keypress((e) => { if (e.which === 13) { $('.info').submit(); alert('Form submitted successfully.') } }) </script></body> </html>", "e": 2515, "s": 1580, "text": null }, { "code": null, "e": 2523, "s": 2515, "text": "Output:" }, { "code": null, "e": 2532, "s": 2523, "text": "CSS-Misc" }, { "code": null, "e": 2542, "s": 2532, "text": "HTML-Misc" }, { "code": null, "e": 2554, "s": 2542, "text": "jQuery-Misc" }, { "code": null, "e": 2561, "s": 2554, "text": "Picked" }, { "code": null, "e": 2565, "s": 2561, "text": "CSS" }, { "code": null, "e": 2570, "s": 2565, "text": "HTML" }, { "code": null, "e": 2577, "s": 2570, "text": "JQuery" }, { "code": null, "e": 2594, "s": 2577, "text": "Web Technologies" }, { "code": null, "e": 2599, "s": 2594, "text": "HTML" } ]
Plot Multiple Columns of Pandas Dataframe on Bar Chart with Matplotlib
24 Jan, 2021 Prerequisites: Pandas Matplotlib In this article, we will learn how to plot multiple columns on bar chart using Matplotlib. Bar Plot is used to represent categories of data using rectangular bars. We can plot these bars with overlapping edges or on same axes. Different ways of plotting bar graph in the same chart are using matplotlib and pandas are discussed below. The trick here is to pass all the data that has to be plotted together as a value to ‘y’ parameter of plot function. Syntax: matplotlib.pyplot.plot(\*args, scalex=True, scaley=True, data=None, \*\*kwargs) Approach: Import module Create or load data Pass data to plot() Plot graph Example: Python3 # importing pandas libraryimport pandas as pd# import matplotlib libraryimport matplotlib.pyplot as plt # creating dataframedf = pd.DataFrame({ 'Name': ['John', 'Sammy', 'Joe'], 'Age': [45, 38, 90], 'Height(in cm)': [150, 180, 160]}) # plotting graphdf.plot(x="Name", y=["Age", "Height(in cm)"], kind="bar") Output: Plotting all separate graph on the same axes, differentiated by color can be one alternative. Here again plot() function is employed. Approach: Import module Create or load data Plot first graph Plot all other graphs on the same axes Example: Python3 # importing pandas libraryimport pandas as pd# import matplotlib libraryimport matplotlib.pyplot as plt # creating dataframedf = pd.DataFrame({ 'Name': ['John', 'Sammy', 'Joe'], 'Age': [45, 38, 90], 'Height(in cm)': [150, 180, 160]}) # plotting Heightax = df.plot(x="Name", y="Height(in cm)", kind="bar")# plotting age on the same axisdf.plot(x="Name", y="Age", kind="bar", ax=ax, color="maroon") Output: Another way of creating such a functionality can be plotting multiple subplots and displaying them as one. This can be done using subplot() function. Syntax: subplot(nrows, ncols, index, **kwargs) Approach: Import module Create or load data Create multiple subplots Plot on single axes Example: Python3 # importing pandas libraryimport pandas as pd# import matplotlib libraryimport matplotlib.pyplot as plt # creating dataframedf = pd.DataFrame({ 'Name': ['John', 'Sammy', 'Joe'], 'Age': [45, 38, 90], 'Height(in cm)': [150, 180, 160]}) # creating subplots and plotting them togetherax = plt.subplot()ax.bar(df["Name"], df["Height(in cm)"])ax.bar(df["Name"], df["Age"], color="maroon") Output: Picked Python-matplotlib Python-pandas Technical Scripter 2020 Python Technical Scripter 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": "\n24 Jan, 2021" }, { "code": null, "e": 70, "s": 54, "text": "Prerequisites: " }, { "code": null, "e": 77, "s": 70, "text": "Pandas" }, { "code": null, "e": 88, "s": 77, "text": "Matplotlib" }, { "code": null, "e": 423, "s": 88, "text": "In this article, we will learn how to plot multiple columns on bar chart using Matplotlib. Bar Plot is used to represent categories of data using rectangular bars. We can plot these bars with overlapping edges or on same axes. Different ways of plotting bar graph in the same chart are using matplotlib and pandas are discussed below." }, { "code": null, "e": 540, "s": 423, "text": "The trick here is to pass all the data that has to be plotted together as a value to ‘y’ parameter of plot function." }, { "code": null, "e": 549, "s": 540, "text": "Syntax: " }, { "code": null, "e": 630, "s": 549, "text": "matplotlib.pyplot.plot(\\*args, scalex=True, scaley=True, data=None, \\*\\*kwargs) " }, { "code": null, "e": 640, "s": 630, "text": "Approach:" }, { "code": null, "e": 655, "s": 640, "text": "Import module " }, { "code": null, "e": 675, "s": 655, "text": "Create or load data" }, { "code": null, "e": 695, "s": 675, "text": "Pass data to plot()" }, { "code": null, "e": 706, "s": 695, "text": "Plot graph" }, { "code": null, "e": 715, "s": 706, "text": "Example:" }, { "code": null, "e": 723, "s": 715, "text": "Python3" }, { "code": "# importing pandas libraryimport pandas as pd# import matplotlib libraryimport matplotlib.pyplot as plt # creating dataframedf = pd.DataFrame({ 'Name': ['John', 'Sammy', 'Joe'], 'Age': [45, 38, 90], 'Height(in cm)': [150, 180, 160]}) # plotting graphdf.plot(x=\"Name\", y=[\"Age\", \"Height(in cm)\"], kind=\"bar\")", "e": 1042, "s": 723, "text": null }, { "code": null, "e": 1050, "s": 1042, "text": "Output:" }, { "code": null, "e": 1184, "s": 1050, "text": "Plotting all separate graph on the same axes, differentiated by color can be one alternative. Here again plot() function is employed." }, { "code": null, "e": 1194, "s": 1184, "text": "Approach:" }, { "code": null, "e": 1208, "s": 1194, "text": "Import module" }, { "code": null, "e": 1228, "s": 1208, "text": "Create or load data" }, { "code": null, "e": 1245, "s": 1228, "text": "Plot first graph" }, { "code": null, "e": 1285, "s": 1245, "text": "Plot all other graphs on the same axes " }, { "code": null, "e": 1294, "s": 1285, "text": "Example:" }, { "code": null, "e": 1302, "s": 1294, "text": "Python3" }, { "code": "# importing pandas libraryimport pandas as pd# import matplotlib libraryimport matplotlib.pyplot as plt # creating dataframedf = pd.DataFrame({ 'Name': ['John', 'Sammy', 'Joe'], 'Age': [45, 38, 90], 'Height(in cm)': [150, 180, 160]}) # plotting Heightax = df.plot(x=\"Name\", y=\"Height(in cm)\", kind=\"bar\")# plotting age on the same axisdf.plot(x=\"Name\", y=\"Age\", kind=\"bar\", ax=ax, color=\"maroon\")", "e": 1710, "s": 1302, "text": null }, { "code": null, "e": 1718, "s": 1710, "text": "Output:" }, { "code": null, "e": 1868, "s": 1718, "text": "Another way of creating such a functionality can be plotting multiple subplots and displaying them as one. This can be done using subplot() function." }, { "code": null, "e": 1876, "s": 1868, "text": "Syntax:" }, { "code": null, "e": 1915, "s": 1876, "text": "subplot(nrows, ncols, index, **kwargs)" }, { "code": null, "e": 1925, "s": 1915, "text": "Approach:" }, { "code": null, "e": 1939, "s": 1925, "text": "Import module" }, { "code": null, "e": 1959, "s": 1939, "text": "Create or load data" }, { "code": null, "e": 1985, "s": 1959, "text": "Create multiple subplots " }, { "code": null, "e": 2005, "s": 1985, "text": "Plot on single axes" }, { "code": null, "e": 2014, "s": 2005, "text": "Example:" }, { "code": null, "e": 2022, "s": 2014, "text": "Python3" }, { "code": "# importing pandas libraryimport pandas as pd# import matplotlib libraryimport matplotlib.pyplot as plt # creating dataframedf = pd.DataFrame({ 'Name': ['John', 'Sammy', 'Joe'], 'Age': [45, 38, 90], 'Height(in cm)': [150, 180, 160]}) # creating subplots and plotting them togetherax = plt.subplot()ax.bar(df[\"Name\"], df[\"Height(in cm)\"])ax.bar(df[\"Name\"], df[\"Age\"], color=\"maroon\")", "e": 2416, "s": 2022, "text": null }, { "code": null, "e": 2424, "s": 2416, "text": "Output:" }, { "code": null, "e": 2431, "s": 2424, "text": "Picked" }, { "code": null, "e": 2449, "s": 2431, "text": "Python-matplotlib" }, { "code": null, "e": 2463, "s": 2449, "text": "Python-pandas" }, { "code": null, "e": 2487, "s": 2463, "text": "Technical Scripter 2020" }, { "code": null, "e": 2494, "s": 2487, "text": "Python" }, { "code": null, "e": 2513, "s": 2494, "text": "Technical Scripter" }, { "code": null, "e": 2611, "s": 2513, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2629, "s": 2611, "text": "Python Dictionary" }, { "code": null, "e": 2671, "s": 2629, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2693, "s": 2671, "text": "Enumerate() in Python" }, { "code": null, "e": 2728, "s": 2693, "text": "Read a file line by line in Python" }, { "code": null, "e": 2754, "s": 2728, "text": "Python String | replace()" }, { "code": null, "e": 2786, "s": 2754, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2815, "s": 2786, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2842, "s": 2815, "text": "Python Classes and Objects" }, { "code": null, "e": 2872, "s": 2842, "text": "Iterate over a list in Python" } ]
Python – Itertools.chain()
25 Aug, 2021 The itertools is a module in Python having a collection of functions that are used for handling iterators. They make iterating through the iterables like lists and strings very easily. One such itertools function is chain().Note: For more information, refer to Python Itertools It is a function that takes a series of iterables and returns one iterable. It groups all the iterables together and produces a single iterable as output. Its output cannot be used directly and thus explicitly converted into iterables. This function come under the category iterators terminating iterators.Syntax : chain (*iterables) The internal working of chain can be implemented as given below : def chain(*iterables): for it in iterables: for each in it: yield each Example 1: The odd numbers and even numbers are in separate lists. Combine them to form a new single list. Python3 from itertools import chain # a list of odd numbersodd = [1, 3, 5, 7, 9] # a list of even numberseven = [2, 4, 6, 8, 10] # chaining odd and even numbersnumbers = list(chain(odd, even)) print(numbers) [1, 3, 5, 7, 9, 2, 4, 6, 8, 10] Example 2: Some of the consonants are in a list. The vowels are given in a list. Combine them and also sort them. Python3 from itertools import chain # some consonantsconsonants = ['d', 'f', 'k', 'l', 'n', 'p'] # some vowelsvowels = ['a', 'e', 'i', 'o', 'u'] # resultatnt listres = list(chain(consonants, vowels)) # sorting the listres.sort() print(res) ['a', 'd', 'e', 'f', 'i', 'k', 'l', 'n', 'o', 'p', 'u'] Example 3: In the example below, Each String is considered to be an iterable and each character in it is considered to be an element in the iterator. Thus every character is yielded Python3 from itertools import chain res = list(chain('ABC', 'DEF', 'GHI', 'JKL')) print(res) ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L'] Example 4: Python3 from itertools import chain st1 = "Geeks"st2 = "for"st3 = "Geeks" res = list(chain(st1, st2, st3))print("before joining :", res) ans = ''.join(res)print("After joining :", ans) chain.from_iterable() functionIt is similar to chain, but it can be used to chain items from a single iterable. The difference is demonstrated in the example given below:Example 5: Python3 from itertools import chain li = ['ABC', 'DEF', 'GHI', 'JKL'] # using chain-single iterable.res1 = list(chain(li)) res2 = list(chain.from_iterable(li)) print("using chain :", res1, end ="\n\n") print("using chain.from_iterable :", res2) Example 6: Now consider a list like the one given below : li=['123', '456', '789'] You are supposed to calculate the sum of the list taking every single digit into account. So the answer should be : 1+2+3+5+6+7+8+9 = 45 This can be achieved easily using the code below : Python3 from itertools import chain li = ['123', '456', '789'] res = list(chain.from_iterable(li)) print("res =", res, end ="\n\n") new_res = list(map(int, res)) print("new_res =", new_res) sum_of_li = sum(new_res) print("\nsum =", sum_of_li) res = ['1', '2', '3', '4', '5', '6', '7', '8', '9'] new_res = [1, 2, 3, 4, 5, 6, 7, 8, 9] sum = 45 To simplify it, we combine the steps. An optimized approach is given below: Python3 from itertools import chain li = ['123', '456', '789'] res = list(map(int, list(chain.from_iterable(li)))) sum_of_li = sum(res) print("res =", res, end ="\n\n")print("sum =", sum_of_li) res = [1, 2, 3, 4, 5, 6, 7, 8, 9] sum = 45 diggy kalrap615 Python-itertools 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": 53, "s": 25, "text": "\n25 Aug, 2021" }, { "code": null, "e": 332, "s": 53, "text": "The itertools is a module in Python having a collection of functions that are used for handling iterators. They make iterating through the iterables like lists and strings very easily. One such itertools function is chain().Note: For more information, refer to Python Itertools " }, { "code": null, "e": 649, "s": 332, "text": "It is a function that takes a series of iterables and returns one iterable. It groups all the iterables together and produces a single iterable as output. Its output cannot be used directly and thus explicitly converted into iterables. This function come under the category iterators terminating iterators.Syntax : " }, { "code": null, "e": 668, "s": 649, "text": "chain (*iterables)" }, { "code": null, "e": 736, "s": 668, "text": "The internal working of chain can be implemented as given below : " }, { "code": null, "e": 830, "s": 736, "text": "def chain(*iterables):\n for it in iterables:\n for each in it:\n yield each" }, { "code": null, "e": 937, "s": 830, "text": "Example 1: The odd numbers and even numbers are in separate lists. Combine them to form a new single list." }, { "code": null, "e": 945, "s": 937, "text": "Python3" }, { "code": "from itertools import chain # a list of odd numbersodd = [1, 3, 5, 7, 9] # a list of even numberseven = [2, 4, 6, 8, 10] # chaining odd and even numbersnumbers = list(chain(odd, even)) print(numbers)", "e": 1145, "s": 945, "text": null }, { "code": null, "e": 1177, "s": 1145, "text": "[1, 3, 5, 7, 9, 2, 4, 6, 8, 10]" }, { "code": null, "e": 1293, "s": 1179, "text": "Example 2: Some of the consonants are in a list. The vowels are given in a list. Combine them and also sort them." }, { "code": null, "e": 1301, "s": 1293, "text": "Python3" }, { "code": "from itertools import chain # some consonantsconsonants = ['d', 'f', 'k', 'l', 'n', 'p'] # some vowelsvowels = ['a', 'e', 'i', 'o', 'u'] # resultatnt listres = list(chain(consonants, vowels)) # sorting the listres.sort() print(res)", "e": 1533, "s": 1301, "text": null }, { "code": null, "e": 1589, "s": 1533, "text": "['a', 'd', 'e', 'f', 'i', 'k', 'l', 'n', 'o', 'p', 'u']" }, { "code": null, "e": 1773, "s": 1591, "text": "Example 3: In the example below, Each String is considered to be an iterable and each character in it is considered to be an element in the iterator. Thus every character is yielded" }, { "code": null, "e": 1781, "s": 1773, "text": "Python3" }, { "code": "from itertools import chain res = list(chain('ABC', 'DEF', 'GHI', 'JKL')) print(res)", "e": 1866, "s": 1781, "text": null }, { "code": null, "e": 1927, "s": 1866, "text": "['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L']" }, { "code": null, "e": 1941, "s": 1929, "text": "Example 4: " }, { "code": null, "e": 1949, "s": 1941, "text": "Python3" }, { "code": "from itertools import chain st1 = \"Geeks\"st2 = \"for\"st3 = \"Geeks\" res = list(chain(st1, st2, st3))print(\"before joining :\", res) ans = ''.join(res)print(\"After joining :\", ans)", "e": 2126, "s": 1949, "text": null }, { "code": null, "e": 2307, "s": 2126, "text": "chain.from_iterable() functionIt is similar to chain, but it can be used to chain items from a single iterable. The difference is demonstrated in the example given below:Example 5:" }, { "code": null, "e": 2315, "s": 2307, "text": "Python3" }, { "code": "from itertools import chain li = ['ABC', 'DEF', 'GHI', 'JKL'] # using chain-single iterable.res1 = list(chain(li)) res2 = list(chain.from_iterable(li)) print(\"using chain :\", res1, end =\"\\n\\n\") print(\"using chain.from_iterable :\", res2)", "e": 2553, "s": 2315, "text": null }, { "code": null, "e": 2612, "s": 2553, "text": "Example 6: Now consider a list like the one given below : " }, { "code": null, "e": 2637, "s": 2612, "text": "li=['123', '456', '789']" }, { "code": null, "e": 2754, "s": 2637, "text": "You are supposed to calculate the sum of the list taking every single digit into account. So the answer should be : " }, { "code": null, "e": 2775, "s": 2754, "text": "1+2+3+5+6+7+8+9 = 45" }, { "code": null, "e": 2826, "s": 2775, "text": "This can be achieved easily using the code below :" }, { "code": null, "e": 2834, "s": 2826, "text": "Python3" }, { "code": "from itertools import chain li = ['123', '456', '789'] res = list(chain.from_iterable(li)) print(\"res =\", res, end =\"\\n\\n\") new_res = list(map(int, res)) print(\"new_res =\", new_res) sum_of_li = sum(new_res) print(\"\\nsum =\", sum_of_li)", "e": 3069, "s": 2834, "text": null }, { "code": null, "e": 3170, "s": 3069, "text": "res = ['1', '2', '3', '4', '5', '6', '7', '8', '9']\n\nnew_res = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n\nsum = 45" }, { "code": null, "e": 3248, "s": 3172, "text": "To simplify it, we combine the steps. An optimized approach is given below:" }, { "code": null, "e": 3256, "s": 3248, "text": "Python3" }, { "code": "from itertools import chain li = ['123', '456', '789'] res = list(map(int, list(chain.from_iterable(li)))) sum_of_li = sum(res) print(\"res =\", res, end =\"\\n\\n\")print(\"sum =\", sum_of_li)", "e": 3442, "s": 3256, "text": null }, { "code": null, "e": 3486, "s": 3442, "text": "res = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n\nsum = 45" }, { "code": null, "e": 3494, "s": 3488, "text": "diggy" }, { "code": null, "e": 3504, "s": 3494, "text": "kalrap615" }, { "code": null, "e": 3521, "s": 3504, "text": "Python-itertools" }, { "code": null, "e": 3528, "s": 3521, "text": "Python" }, { "code": null, "e": 3626, "s": 3528, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3644, "s": 3626, "text": "Python Dictionary" }, { "code": null, "e": 3686, "s": 3644, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3708, "s": 3686, "text": "Enumerate() in Python" }, { "code": null, "e": 3743, "s": 3708, "text": "Read a file line by line in Python" }, { "code": null, "e": 3769, "s": 3743, "text": "Python String | replace()" }, { "code": null, "e": 3801, "s": 3769, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3830, "s": 3801, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3857, "s": 3830, "text": "Python Classes and Objects" }, { "code": null, "e": 3887, "s": 3857, "text": "Iterate over a list in Python" } ]
Python – datetime.tzinfo()
27 Feb, 2020 The DateTime class provides various functions to manipulate the date and time intervals. The DateTime object which you use in datetime.now() is actually the object of the DateTime class. These objects help us use the functions on dates and times. Note: For more information, refer to Python datetime module with examples The datetime.now() does not have any information about the time zones. It just uses the current system time. In some situations, the time zone details may be needed. In such cases the tzinfo abstract class is used. tzinfo is an abstract base class. It cannot be instantiated directly. A concrete subclass has to derive it and implement the methods provided by this abstract class. The instance of the tzinfo class can be passed to the constructors of the datetime and time objects. It finds its applications in situations such as the conversion of local time to UTC or to account for daylight saving time. A datetime object which does not contain any information on time zone is said to be a naive datetime object. For a naive datetime object, datetime_object.tzinfo will be None. An Aware datetime object contains the time zone information embedded in it. The methods available for implementation in tzinfo base class are : utcoffset(self, dt) dst(self, dt) tzname(self, dt) fromutc(self, dt) It returns the offset of the datetime instance passed as argument. What does this offset refer to ? It refers to the time zone offset which denotes how many hours the time zone is ahead from the Coordinated Universal Time or Universal Time Coordinate (UTC). The offset is written as +00:00. For example: for Asia/Taipei, it is written as UTC +08:00. It takes up the time of a datetime object and returns the difference between time in datetime object and the time of same point in UTC. It returns the offset in minutes east of UTC. If the local time is west of UTC, it would be negative. The general implementation form is given below: For fixed offset : def utcoff(self, dt): return constant For time aware objects : def utcoffset(self, dt): return self.stdoffset + self.dst(dt) It is abbreviated as Day-light Saving Time. It denotes advancing the clock 1 hour in summer time, so that darkness falls later according to the clock. It is set to on or off. It is checked based on a tuple containing 9 elements as follows : (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.weekday(), 0, 0) A private function is written in order to return either 0, 1 or -1 depending on these 9 elements. Based on that the value of dst(self, dt) is decided. The function is written in the class where dst() is defined. It is written as: def _isdst(self, dt): tt = (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.weekday(), 0, 0) stamp = _time.mktime(tt) tt = _time.localtime(stamp) return tt.tm_isdst > 0 Here mktime() takes this tuple and converts it to time in seconds passed since epoch in local time. Then, tm_isdst() is used along with mktime. It returns the values as follows : ‘1’ – Daylight Saving ON‘0’ – Daylight Saving OFF‘-1’ – Daylight Saving information unknown After adding this code to the class, the dst() can be defined as given below based on the conditions. For fixed offset class : def dst(self, dt): return ZERO For time aware objects : def utcoffset(self, dt): if self._isdst(dt): return DSTOFFSET else: return STDOFFSET This is used to find the time zone name of the datetime object passed. It returns a Python String object. Example: import datetime as dtfrom dateutil import tz tz_string = dt.datetime.now(dt.timezone.utc).astimezone().tzname() print("datetime.now() :", tz_string) NYC = tz.gettz('Europe / Berlin') dt1 = dt.datetime(2015, 5, 21, 12, 0) dt2 = dt.datetime(2015, 12, 21, 12, 0, tzinfo = NYC) print("Naive Object :", dt1.tzname())print("Aware Object :", dt2.tzname()) datetime.now() : UTC Naive Object : None Aware Object : CET This function takes up the date and time of the object in UTC and returns the equivalent local time. It is used mostly for adjusting the date and time. It is called from default datetime.astimezone() implementation. The dt.tzinfo will be passed as self, dt’s date and time data will be returned as an equivalent local time. Note: It will raise ValueError if dt.tzinfo is not self or/and dst() is None. The general implementation is given below: def fromutc(self, dt): dt_offset = dt.utcoffset() dt_dst = dt.dst() delta = dt_offset - dt_dst if delta: dt += delta dtdst = dt.dst() if dtdst: return dt + dtdst else: return dt Python-datetime Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts Convert integer to string in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n27 Feb, 2020" }, { "code": null, "e": 299, "s": 52, "text": "The DateTime class provides various functions to manipulate the date and time intervals. The DateTime object which you use in datetime.now() is actually the object of the DateTime class. These objects help us use the functions on dates and times." }, { "code": null, "e": 373, "s": 299, "text": "Note: For more information, refer to Python datetime module with examples" }, { "code": null, "e": 754, "s": 373, "text": "The datetime.now() does not have any information about the time zones. It just uses the current system time. In some situations, the time zone details may be needed. In such cases the tzinfo abstract class is used. tzinfo is an abstract base class. It cannot be instantiated directly. A concrete subclass has to derive it and implement the methods provided by this abstract class." }, { "code": null, "e": 979, "s": 754, "text": "The instance of the tzinfo class can be passed to the constructors of the datetime and time objects. It finds its applications in situations such as the conversion of local time to UTC or to account for daylight saving time." }, { "code": null, "e": 1230, "s": 979, "text": "A datetime object which does not contain any information on time zone is said to be a naive datetime object. For a naive datetime object, datetime_object.tzinfo will be None. An Aware datetime object contains the time zone information embedded in it." }, { "code": null, "e": 1298, "s": 1230, "text": "The methods available for implementation in tzinfo base class are :" }, { "code": null, "e": 1318, "s": 1298, "text": "utcoffset(self, dt)" }, { "code": null, "e": 1332, "s": 1318, "text": "dst(self, dt)" }, { "code": null, "e": 1349, "s": 1332, "text": "tzname(self, dt)" }, { "code": null, "e": 1367, "s": 1349, "text": "fromutc(self, dt)" }, { "code": null, "e": 1434, "s": 1367, "text": "It returns the offset of the datetime instance passed as argument." }, { "code": null, "e": 1467, "s": 1434, "text": "What does this offset refer to ?" }, { "code": null, "e": 1717, "s": 1467, "text": "It refers to the time zone offset which denotes how many hours the time zone is ahead from the Coordinated Universal Time or Universal Time Coordinate (UTC). The offset is written as +00:00. For example: for Asia/Taipei, it is written as UTC +08:00." }, { "code": null, "e": 2003, "s": 1717, "text": "It takes up the time of a datetime object and returns the difference between time in datetime object and the time of same point in UTC. It returns the offset in minutes east of UTC. If the local time is west of UTC, it would be negative. The general implementation form is given below:" }, { "code": null, "e": 2165, "s": 2003, "text": "For fixed offset :\n\n def utcoff(self, dt):\n return constant\n\nFor time aware objects :\n\ndef utcoffset(self, dt):\n return self.stdoffset + self.dst(dt)" }, { "code": null, "e": 2406, "s": 2165, "text": "It is abbreviated as Day-light Saving Time. It denotes advancing the clock 1 hour in summer time, so that darkness falls later according to the clock. It is set to on or off. It is checked based on a tuple containing 9 elements as follows :" }, { "code": null, "e": 2485, "s": 2406, "text": "(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.weekday(), 0, 0)" }, { "code": null, "e": 2715, "s": 2485, "text": "A private function is written in order to return either 0, 1 or -1 depending on these 9 elements. Based on that the value of dst(self, dt) is decided. The function is written in the class where dst() is defined. It is written as:" }, { "code": "def _isdst(self, dt): tt = (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.weekday(), 0, 0) stamp = _time.mktime(tt) tt = _time.localtime(stamp) return tt.tm_isdst > 0", "e": 2957, "s": 2715, "text": null }, { "code": null, "e": 3136, "s": 2957, "text": "Here mktime() takes this tuple and converts it to time in seconds passed since epoch in local time. Then, tm_isdst() is used along with mktime. It returns the values as follows :" }, { "code": null, "e": 3228, "s": 3136, "text": "‘1’ – Daylight Saving ON‘0’ – Daylight Saving OFF‘-1’ – Daylight Saving information unknown" }, { "code": null, "e": 3330, "s": 3228, "text": "After adding this code to the class, the dst() can be defined as given below based on the conditions." }, { "code": null, "e": 3551, "s": 3330, "text": "For fixed offset class :\n\n def dst(self, dt):\n return ZERO\n\nFor time aware objects :\n\n def utcoffset(self, dt):\n if self._isdst(dt):\n return DSTOFFSET\n else:\n return STDOFFSET\n\n" }, { "code": null, "e": 3657, "s": 3551, "text": "This is used to find the time zone name of the datetime object passed. It returns a Python String object." }, { "code": null, "e": 3666, "s": 3657, "text": "Example:" }, { "code": "import datetime as dtfrom dateutil import tz tz_string = dt.datetime.now(dt.timezone.utc).astimezone().tzname() print(\"datetime.now() :\", tz_string) NYC = tz.gettz('Europe / Berlin') dt1 = dt.datetime(2015, 5, 21, 12, 0) dt2 = dt.datetime(2015, 12, 21, 12, 0, tzinfo = NYC) print(\"Naive Object :\", dt1.tzname())print(\"Aware Object :\", dt2.tzname())", "e": 4023, "s": 3666, "text": null }, { "code": null, "e": 4084, "s": 4023, "text": "datetime.now() : UTC\nNaive Object : None\nAware Object : CET\n" }, { "code": null, "e": 4408, "s": 4084, "text": "This function takes up the date and time of the object in UTC and returns the equivalent local time. It is used mostly for adjusting the date and time. It is called from default datetime.astimezone() implementation. The dt.tzinfo will be passed as self, dt’s date and time data will be returned as an equivalent local time." }, { "code": null, "e": 4486, "s": 4408, "text": "Note: It will raise ValueError if dt.tzinfo is not self or/and dst() is None." }, { "code": null, "e": 4529, "s": 4486, "text": "The general implementation is given below:" }, { "code": null, "e": 4803, "s": 4529, "text": "def fromutc(self, dt):\n dt_offset = dt.utcoffset()\n dt_dst = dt.dst()\n delta = dt_offset - dt_dst \n \n if delta:\n dt += delta \n dtdst = dt.dst()\n \n if dtdst:\n return dt + dtdst\n else:\n return dt" }, { "code": null, "e": 4819, "s": 4803, "text": "Python-datetime" }, { "code": null, "e": 4826, "s": 4819, "text": "Python" }, { "code": null, "e": 4924, "s": 4826, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4942, "s": 4924, "text": "Python Dictionary" }, { "code": null, "e": 4984, "s": 4942, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 5006, "s": 4984, "text": "Enumerate() in Python" }, { "code": null, "e": 5041, "s": 5006, "text": "Read a file line by line in Python" }, { "code": null, "e": 5073, "s": 5041, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 5102, "s": 5073, "text": "*args and **kwargs in Python" }, { "code": null, "e": 5129, "s": 5102, "text": "Python Classes and Objects" }, { "code": null, "e": 5159, "s": 5129, "text": "Iterate over a list in Python" }, { "code": null, "e": 5180, "s": 5159, "text": "Python OOPs Concepts" } ]
Select Only Numeric Columns from DataFrame in R
23 Sep, 2021 In this article, we will discuss how to select only numeric columns from dataframe in R Programming Language. We can use select_if() function to get numeric columns by calling the function with the dataframe name and isnumeric() function that will check for numeric columns. Syntax: select_if(dataframe, is.numeric) where, dataframe is the input dataframe is.numeric is sued to get the numeric columns Example: R program to get numeric columns from dataframe using dplyr R # load the package dplyrlibrary("dplyr") # create a dataframe with 4 columns and 3 rowsdata=data.frame("webtechnologies"=c("php","html","js"), marks=c(98,89,90), age=c(12,23,21), name=c("bobby","ojaswi","ramya")) # get numeric columns using dplyr() function print(select_if(data, is.numeric)) Output: Example: R program to get numeric columns from dataframe using dplyr R # load the package dplyrlibrary("dplyr") # create a dataframe with 4 columns and 3 rowsdata=data.frame(id=c(1,2,3), marks=c(98,89,90), age=c(12,23,21), name=c("bobby","ojaswi","ramya")) # get numeric columns using dplyr() function print(select_if(data, is.numeric)) Output: we will use lapply() function to get the numeric columns. Here, lapply() function is called with unlist() and the dataframe name and isnumeric() function are passed to it as parameters. Syntax: unlist(lapply(dataframe, is.numeric)) where, dataframe is the input dataframe is.numeric is used to check each dataframe column is numeric or not unlist function is used to unlist the dataframe Finally, pass this lapply() to the dataframe index Syntax: dataframe[,unlist(lapply(data, is.numeric))] Where, dataframe is the input dataframe Example: R program to get numeric columns from dataframe using base R R # create a dataframe with 4 columns and 3 rowsdata=data.frame(id=c(1,2,3), marks=c(98,89,90), age=c(12,23,21), name=c("bobby","ojaswi","ramya")) # get numeric columns using dplyr() function print(data[,unlist(lapply(data, is.numeric))]) Output: Picked R DataFrame-Programs R-DataFrame R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Sep, 2021" }, { "code": null, "e": 138, "s": 28, "text": "In this article, we will discuss how to select only numeric columns from dataframe in R Programming Language." }, { "code": null, "e": 303, "s": 138, "text": "We can use select_if() function to get numeric columns by calling the function with the dataframe name and isnumeric() function that will check for numeric columns." }, { "code": null, "e": 311, "s": 303, "text": "Syntax:" }, { "code": null, "e": 344, "s": 311, "text": "select_if(dataframe, is.numeric)" }, { "code": null, "e": 351, "s": 344, "text": "where," }, { "code": null, "e": 384, "s": 351, "text": "dataframe is the input dataframe" }, { "code": null, "e": 430, "s": 384, "text": "is.numeric is sued to get the numeric columns" }, { "code": null, "e": 499, "s": 430, "text": "Example: R program to get numeric columns from dataframe using dplyr" }, { "code": null, "e": 501, "s": 499, "text": "R" }, { "code": "# load the package dplyrlibrary(\"dplyr\") # create a dataframe with 4 columns and 3 rowsdata=data.frame(\"webtechnologies\"=c(\"php\",\"html\",\"js\"), marks=c(98,89,90), age=c(12,23,21), name=c(\"bobby\",\"ojaswi\",\"ramya\")) # get numeric columns using dplyr() function print(select_if(data, is.numeric))", "e": 861, "s": 501, "text": null }, { "code": null, "e": 869, "s": 861, "text": "Output:" }, { "code": null, "e": 938, "s": 869, "text": "Example: R program to get numeric columns from dataframe using dplyr" }, { "code": null, "e": 940, "s": 938, "text": "R" }, { "code": "# load the package dplyrlibrary(\"dplyr\") # create a dataframe with 4 columns and 3 rowsdata=data.frame(id=c(1,2,3), marks=c(98,89,90), age=c(12,23,21), name=c(\"bobby\",\"ojaswi\",\"ramya\")) # get numeric columns using dplyr() function print(select_if(data, is.numeric))", "e": 1273, "s": 940, "text": null }, { "code": null, "e": 1281, "s": 1273, "text": "Output:" }, { "code": null, "e": 1467, "s": 1281, "text": "we will use lapply() function to get the numeric columns. Here, lapply() function is called with unlist() and the dataframe name and isnumeric() function are passed to it as parameters." }, { "code": null, "e": 1475, "s": 1467, "text": "Syntax:" }, { "code": null, "e": 1513, "s": 1475, "text": "unlist(lapply(dataframe, is.numeric))" }, { "code": null, "e": 1520, "s": 1513, "text": "where," }, { "code": null, "e": 1553, "s": 1520, "text": "dataframe is the input dataframe" }, { "code": null, "e": 1621, "s": 1553, "text": "is.numeric is used to check each dataframe column is numeric or not" }, { "code": null, "e": 1669, "s": 1621, "text": "unlist function is used to unlist the dataframe" }, { "code": null, "e": 1720, "s": 1669, "text": "Finally, pass this lapply() to the dataframe index" }, { "code": null, "e": 1728, "s": 1720, "text": "Syntax:" }, { "code": null, "e": 1773, "s": 1728, "text": "dataframe[,unlist(lapply(data, is.numeric))]" }, { "code": null, "e": 1813, "s": 1773, "text": "Where, dataframe is the input dataframe" }, { "code": null, "e": 1883, "s": 1813, "text": "Example: R program to get numeric columns from dataframe using base R" }, { "code": null, "e": 1885, "s": 1883, "text": "R" }, { "code": "# create a dataframe with 4 columns and 3 rowsdata=data.frame(id=c(1,2,3), marks=c(98,89,90), age=c(12,23,21), name=c(\"bobby\",\"ojaswi\",\"ramya\")) # get numeric columns using dplyr() function print(data[,unlist(lapply(data, is.numeric))])", "e": 2188, "s": 1885, "text": null }, { "code": null, "e": 2196, "s": 2188, "text": "Output:" }, { "code": null, "e": 2203, "s": 2196, "text": "Picked" }, { "code": null, "e": 2224, "s": 2203, "text": "R DataFrame-Programs" }, { "code": null, "e": 2236, "s": 2224, "text": "R-DataFrame" }, { "code": null, "e": 2247, "s": 2236, "text": "R Language" }, { "code": null, "e": 2258, "s": 2247, "text": "R Programs" } ]
Python | Pandas dataframe.mask()
19 Nov, 2018 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.mask() function return an object of same shape as self and whose corresponding entries are from self where cond is False and otherwise are from other object. The other object could be a scalar, series, dataframe or could be a callable. The mask method is an application of the if-then idiom. For each element in the calling DataFrame, if cond is False the element is used; otherwise the corresponding element from the DataFrame other is used. Syntax: DataFrame.mask(cond, other=nan, inplace=False, axis=None, level=None, errors=’raise’, try_cast=False, raise_on_error=None) Parameters :cond : Where cond is False, keep the original value. Where True, replace with corresponding value from other. If cond is callable, it is computed on the NDFrame and should return boolean NDFrame or array. The callable must not change input NDFrame (though pandas doesn’t check it). other : Entries where cond is True are replaced with corresponding value from other. If other is callable, it is computed on the NDFrame and should return scalar or NDFrame. The callable must not change input NDFrame (though pandas doesn’t check it).inplace : Whether to perform the operation in place on the dataaxis : alignment axis if needed, default Nonelevel : alignment level if needed, default Noneerrors : str, {‘raise’, ‘ignore’}, default ‘raise’raise allow exceptions to be raised and ignore suppress exceptions. On error return original object. Note that currently this parameter won’t affect the results and will always coerce to a suitable dtype. try_cast : try to cast the result back to the input type (if possible), Returns : wh : same type as caller Example #1: Use mask() function to replace all the values in the dataframe which are greater than 10 with -25 # importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({"A":[12, 4, 5, 44, 1], "B":[5, 2, 54, 3, 2], "C":[20, 16, 7, 3, 8], "D":[14, 3, 17, 2, 6]}) # Print the dataframedf Let’s use the dataframe.mask() function to replace all the values greater than 10 with -25 # replace values greater than 10 with -25df.mask(df > 10, -25) Output : Example #2: Use mask() function with a callable. Replace all the Na value with 1000. # importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({"A":[12, 4, 5, None, 1], "B":[7, 2, 54, 3, None], "C":[20, 16, 11, 3, 8], "D":[14, 3, None, 2, 6]}) # replace the Na values with 1000df.mask(df.isna(), 1000)) Output : Python pandas-dataFrame Python pandas-dataFrame-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Nov, 2018" }, { "code": null, "e": 242, "s": 28, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 702, "s": 242, "text": "Pandas dataframe.mask() function return an object of same shape as self and whose corresponding entries are from self where cond is False and otherwise are from other object. The other object could be a scalar, series, dataframe or could be a callable. The mask method is an application of the if-then idiom. For each element in the calling DataFrame, if cond is False the element is used; otherwise the corresponding element from the DataFrame other is used." }, { "code": null, "e": 833, "s": 702, "text": "Syntax: DataFrame.mask(cond, other=nan, inplace=False, axis=None, level=None, errors=’raise’, try_cast=False, raise_on_error=None)" }, { "code": null, "e": 1127, "s": 833, "text": "Parameters :cond : Where cond is False, keep the original value. Where True, replace with corresponding value from other. If cond is callable, it is computed on the NDFrame and should return boolean NDFrame or array. The callable must not change input NDFrame (though pandas doesn’t check it)." }, { "code": null, "e": 1787, "s": 1127, "text": "other : Entries where cond is True are replaced with corresponding value from other. If other is callable, it is computed on the NDFrame and should return scalar or NDFrame. The callable must not change input NDFrame (though pandas doesn’t check it).inplace : Whether to perform the operation in place on the dataaxis : alignment axis if needed, default Nonelevel : alignment level if needed, default Noneerrors : str, {‘raise’, ‘ignore’}, default ‘raise’raise allow exceptions to be raised and ignore suppress exceptions. On error return original object. Note that currently this parameter won’t affect the results and will always coerce to a suitable dtype." }, { "code": null, "e": 1859, "s": 1787, "text": "try_cast : try to cast the result back to the input type (if possible)," }, { "code": null, "e": 1894, "s": 1859, "text": "Returns : wh : same type as caller" }, { "code": null, "e": 2004, "s": 1894, "text": "Example #1: Use mask() function to replace all the values in the dataframe which are greater than 10 with -25" }, { "code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({\"A\":[12, 4, 5, 44, 1], \"B\":[5, 2, 54, 3, 2], \"C\":[20, 16, 7, 3, 8], \"D\":[14, 3, 17, 2, 6]}) # Print the dataframedf", "e": 2264, "s": 2004, "text": null }, { "code": null, "e": 2355, "s": 2264, "text": "Let’s use the dataframe.mask() function to replace all the values greater than 10 with -25" }, { "code": "# replace values greater than 10 with -25df.mask(df > 10, -25)", "e": 2418, "s": 2355, "text": null }, { "code": null, "e": 2428, "s": 2418, "text": "Output : " }, { "code": null, "e": 2513, "s": 2428, "text": "Example #2: Use mask() function with a callable. Replace all the Na value with 1000." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({\"A\":[12, 4, 5, None, 1], \"B\":[7, 2, 54, 3, None], \"C\":[20, 16, 11, 3, 8], \"D\":[14, 3, None, 2, 6]}) # replace the Na values with 1000df.mask(df.isna(), 1000))", "e": 2816, "s": 2513, "text": null }, { "code": null, "e": 2825, "s": 2816, "text": "Output :" }, { "code": null, "e": 2849, "s": 2825, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2881, "s": 2849, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 2895, "s": 2881, "text": "Python-pandas" }, { "code": null, "e": 2902, "s": 2895, "text": "Python" }, { "code": null, "e": 3000, "s": 2902, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3018, "s": 3000, "text": "Python Dictionary" }, { "code": null, "e": 3060, "s": 3018, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3082, "s": 3060, "text": "Enumerate() in Python" }, { "code": null, "e": 3117, "s": 3082, "text": "Read a file line by line in Python" }, { "code": null, "e": 3149, "s": 3117, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3178, "s": 3149, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3205, "s": 3178, "text": "Python Classes and Objects" }, { "code": null, "e": 3235, "s": 3205, "text": "Iterate over a list in Python" }, { "code": null, "e": 3256, "s": 3235, "text": "Python OOPs Concepts" } ]
Hadoop – File Permission and ACL(Access Control List)
10 Jul, 2020 In general, a Hadoop cluster performs security on many layers. The level of protection depends upon the organization’s requirements. In this article, we are going to Learn about Hadoop’s first level of security. It contains mainly two components. Both of these features are part of the default installation. 1. File Permission2. ACL(Access Control List) The HDFS(Hadoop Distributed File System) implements POSIX(Portable Operating System Interface) like a file permission model. It is similar to the file permission model in Linux. In Linux, we use Owner, Group, and Others which has permission for each file and directory available in our Linux environment. Owner/user Group Others rwx rwx rwx Similarly, the HDFS file system also implements a set of permissions, for this Owner, Group, and Others. In Linux we use -rwx for permission to the specific user where r is read, w is for write or append and x is for executable. But in HDFS for a file, we have r for reading, w for writing and appending and there is no sense for x i.e. for execution permission, because in HDFS all files are supposed to be data files and we don’t have any concept of executing a file in HDFS. Since we don’t have an executable concept in HDFS so we don’t have a setUID and setGID for HDFS. Similarly, we can have permission for a directory in our HDFS. Where r is used to list the content of a directory, w is used for creation or deletion of a directory and x permission is used to access the child of a directory. Here also we don’t have a setUID and setGID for HDFS. -chmod that stands for change mode command is used for changing the permission for the files in our HDFS. The first list down the directories available in our HDFS and have a look at the permission assigned to each of this directory. You can list the directory in your HDFS root with the below command. hdfs dfs -ls / Here, / represents the root directory of your HDFS. Let me first list down files present in my Hadoop_File directory. hdfs dfs -ls /Hadoop_File In above Image you can see that for file1.txt, I have only read and write permission for owner user only. So I am adding write permission to group and others also. Pre-requisite: You have to be familiar with the use of -chmod command in Linux means how to use switch for permissions for users. To add write permission to group and others use below command. hdfs dfs -chmod go+w /Hadoop_File/file1.txt Here, go stands for group and other and w means write, and + sign shows that I am adding write permission to group and other. Then list the file again to check it worked or not. hdfs dfs -ls /Hadoop_File And we have done with it, similarly, you can change the permission for any file or directory available in our HDFS(Hadoop Distributed File System). Similarly, you can change permission as per your requirement for any user. you can also change group or owner of a directory with -chgrp and -chown respectively. ACL provides a more flexible way to assign permission for a file system. It is a list of access permission for a file or a directory. We need the use of ACL in case you have made a separate user for your Hadoop single node cluster setup, or you have a multinode cluster setup where various nodes are present, and you want to change permission for other users. Because if you want to change permission for the different users, you can not do it with -chmod command. For example, for single node cluster of Hadoop your main user is root and you have created a separate user for Hadoop setup with name let say Hadoop. Now if you want to change permission for the root user for files that are present in your HDFS, you can not do it with -chmod command. Here comes ACL(Access Control List) in the picture. With ACL you can set permission for a specific named user or named group. In order to enable ACL in HDFS you need to add the below property in hdfs-site.xml file. <property><name>dfs.namenode.acls.enabled</name><value>true</value></property> Note: Don’t forget to restart all the daemons otherwise changes made to hdfs-site.xml don’t reflect. You can check the entry’s in your access control list(ACL) with -getfacl command for a directory as shown below. hdfs dfs -getfacl /Hadoop_File You can see that we have 3 different entry’s in our ACL. Suppose you want to change permission for your root user for any HDFS directory you can do it with below command. Syntax: hdfs dfs -setfacl -m user:user_name:r-x /Hadoop_File You can change permission for any user by adding it to the ACL for that directory. Below are some of the example to change permission of different named users for any HDFS file or directory. hdfs dfs -setfacl -m user:root:r-x /Hadoop_File Another example, for raj user: hdfs dfs -setfacl -m user:raj:r-x /Hadoop_File Here r-x denotes only read and executing permission for HDFS directory for that root, and raj user. In my case, I don’t have any other user so I am changing permission for my only user i.e. dikshant hdfs dfs -setfacl -m user:dikshant:rwx /Hadoop_File Then list the ACL with -getfacl command to see the changes. hdfs dfs -getfacl /Hadoop_File Here, you can see another entry in ACL of this directory with user:dikshant:rwx for new permission of dikshant user. Similarly, in case you have multiple users then you can change their permission for any HDFS directory. This is another example to change the permission of the user dikshant from r-x mode. Here, you can see that I have changed dikshant user permission from rwx to r-x. Hadoop Hadoop Hadoop Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Create Table in Hive? What is Schema On Read and Schema On Write in Hadoop? What is Hadoop Streaming? MapReduce - Understanding With Real-Life Example Apache Hive Hadoop - HDFS (Hadoop Distributed File System) Hive - Alter Table Import and Export Data using SQOOP Difference Between Hadoop and Apache Spark Difference Between Hadoop 2.x vs Hadoop 3.x
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Jul, 2020" }, { "code": null, "e": 336, "s": 28, "text": "In general, a Hadoop cluster performs security on many layers. The level of protection depends upon the organization’s requirements. In this article, we are going to Learn about Hadoop’s first level of security. It contains mainly two components. Both of these features are part of the default installation." }, { "code": null, "e": 382, "s": 336, "text": "1. File Permission2. ACL(Access Control List)" }, { "code": null, "e": 687, "s": 382, "text": "The HDFS(Hadoop Distributed File System) implements POSIX(Portable Operating System Interface) like a file permission model. It is similar to the file permission model in Linux. In Linux, we use Owner, Group, and Others which has permission for each file and directory available in our Linux environment." }, { "code": null, "e": 856, "s": 687, "text": " Owner/user Group Others\n rwx rwx rwx \n" }, { "code": null, "e": 1431, "s": 856, "text": "Similarly, the HDFS file system also implements a set of permissions, for this Owner, Group, and Others. In Linux we use -rwx for permission to the specific user where r is read, w is for write or append and x is for executable. But in HDFS for a file, we have r for reading, w for writing and appending and there is no sense for x i.e. for execution permission, because in HDFS all files are supposed to be data files and we don’t have any concept of executing a file in HDFS. Since we don’t have an executable concept in HDFS so we don’t have a setUID and setGID for HDFS." }, { "code": null, "e": 1711, "s": 1431, "text": "Similarly, we can have permission for a directory in our HDFS. Where r is used to list the content of a directory, w is used for creation or deletion of a directory and x permission is used to access the child of a directory. Here also we don’t have a setUID and setGID for HDFS." }, { "code": null, "e": 2014, "s": 1711, "text": "-chmod that stands for change mode command is used for changing the permission for the files in our HDFS. The first list down the directories available in our HDFS and have a look at the permission assigned to each of this directory. You can list the directory in your HDFS root with the below command." }, { "code": null, "e": 2029, "s": 2014, "text": "hdfs dfs -ls /" }, { "code": null, "e": 2081, "s": 2029, "text": "Here, / represents the root directory of your HDFS." }, { "code": null, "e": 2147, "s": 2081, "text": "Let me first list down files present in my Hadoop_File directory." }, { "code": null, "e": 2173, "s": 2147, "text": "hdfs dfs -ls /Hadoop_File" }, { "code": null, "e": 2337, "s": 2173, "text": "In above Image you can see that for file1.txt, I have only read and write permission for owner user only. So I am adding write permission to group and others also." }, { "code": null, "e": 2352, "s": 2337, "text": "Pre-requisite:" }, { "code": null, "e": 2530, "s": 2352, "text": "You have to be familiar with the use of -chmod command in Linux means how to use switch for permissions for users. To add write permission to group and others use below command." }, { "code": null, "e": 2575, "s": 2530, "text": "hdfs dfs -chmod go+w /Hadoop_File/file1.txt" }, { "code": null, "e": 2753, "s": 2575, "text": "Here, go stands for group and other and w means write, and + sign shows that I am adding write permission to group and other. Then list the file again to check it worked or not." }, { "code": null, "e": 2779, "s": 2753, "text": "hdfs dfs -ls /Hadoop_File" }, { "code": null, "e": 2927, "s": 2779, "text": "And we have done with it, similarly, you can change the permission for any file or directory available in our HDFS(Hadoop Distributed File System)." }, { "code": null, "e": 3089, "s": 2927, "text": "Similarly, you can change permission as per your requirement for any user. you can also change group or owner of a directory with -chgrp and -chown respectively." }, { "code": null, "e": 3449, "s": 3089, "text": "ACL provides a more flexible way to assign permission for a file system. It is a list of access permission for a file or a directory. We need the use of ACL in case you have made a separate user for your Hadoop single node cluster setup, or you have a multinode cluster setup where various nodes are present, and you want to change permission for other users." }, { "code": null, "e": 3965, "s": 3449, "text": "Because if you want to change permission for the different users, you can not do it with -chmod command. For example, for single node cluster of Hadoop your main user is root and you have created a separate user for Hadoop setup with name let say Hadoop. Now if you want to change permission for the root user for files that are present in your HDFS, you can not do it with -chmod command. Here comes ACL(Access Control List) in the picture. With ACL you can set permission for a specific named user or named group." }, { "code": null, "e": 4054, "s": 3965, "text": "In order to enable ACL in HDFS you need to add the below property in hdfs-site.xml file." }, { "code": "<property><name>dfs.namenode.acls.enabled</name><value>true</value></property>", "e": 4133, "s": 4054, "text": null }, { "code": null, "e": 4234, "s": 4133, "text": "Note: Don’t forget to restart all the daemons otherwise changes made to hdfs-site.xml don’t reflect." }, { "code": null, "e": 4347, "s": 4234, "text": "You can check the entry’s in your access control list(ACL) with -getfacl command for a directory as shown below." }, { "code": null, "e": 4378, "s": 4347, "text": "hdfs dfs -getfacl /Hadoop_File" }, { "code": null, "e": 4549, "s": 4378, "text": "You can see that we have 3 different entry’s in our ACL. Suppose you want to change permission for your root user for any HDFS directory you can do it with below command." }, { "code": null, "e": 4557, "s": 4549, "text": "Syntax:" }, { "code": null, "e": 4610, "s": 4557, "text": "hdfs dfs -setfacl -m user:user_name:r-x /Hadoop_File" }, { "code": null, "e": 4801, "s": 4610, "text": "You can change permission for any user by adding it to the ACL for that directory. Below are some of the example to change permission of different named users for any HDFS file or directory." }, { "code": null, "e": 4849, "s": 4801, "text": "hdfs dfs -setfacl -m user:root:r-x /Hadoop_File" }, { "code": null, "e": 4880, "s": 4849, "text": "Another example, for raj user:" }, { "code": null, "e": 4927, "s": 4880, "text": "hdfs dfs -setfacl -m user:raj:r-x /Hadoop_File" }, { "code": null, "e": 5027, "s": 4927, "text": "Here r-x denotes only read and executing permission for HDFS directory for that root, and raj user." }, { "code": null, "e": 5126, "s": 5027, "text": "In my case, I don’t have any other user so I am changing permission for my only user i.e. dikshant" }, { "code": null, "e": 5178, "s": 5126, "text": "hdfs dfs -setfacl -m user:dikshant:rwx /Hadoop_File" }, { "code": null, "e": 5238, "s": 5178, "text": "Then list the ACL with -getfacl command to see the changes." }, { "code": null, "e": 5269, "s": 5238, "text": "hdfs dfs -getfacl /Hadoop_File" }, { "code": null, "e": 5575, "s": 5269, "text": "Here, you can see another entry in ACL of this directory with user:dikshant:rwx for new permission of dikshant user. Similarly, in case you have multiple users then you can change their permission for any HDFS directory. This is another example to change the permission of the user dikshant from r-x mode." }, { "code": null, "e": 5655, "s": 5575, "text": "Here, you can see that I have changed dikshant user permission from rwx to r-x." }, { "code": null, "e": 5662, "s": 5655, "text": "Hadoop" }, { "code": null, "e": 5669, "s": 5662, "text": "Hadoop" }, { "code": null, "e": 5676, "s": 5669, "text": "Hadoop" }, { "code": null, "e": 5774, "s": 5676, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5803, "s": 5774, "text": "How to Create Table in Hive?" }, { "code": null, "e": 5857, "s": 5803, "text": "What is Schema On Read and Schema On Write in Hadoop?" }, { "code": null, "e": 5883, "s": 5857, "text": "What is Hadoop Streaming?" }, { "code": null, "e": 5932, "s": 5883, "text": "MapReduce - Understanding With Real-Life Example" }, { "code": null, "e": 5944, "s": 5932, "text": "Apache Hive" }, { "code": null, "e": 5991, "s": 5944, "text": "Hadoop - HDFS (Hadoop Distributed File System)" }, { "code": null, "e": 6010, "s": 5991, "text": "Hive - Alter Table" }, { "code": null, "e": 6045, "s": 6010, "text": "Import and Export Data using SQOOP" }, { "code": null, "e": 6088, "s": 6045, "text": "Difference Between Hadoop and Apache Spark" } ]
Calculate the Average, Variance and Standard Deviation in R Programming
16 Dec, 2021 R Programming Language is an open-source programming language that is widely used as a statistical software and data analysis tool. R generally comes with the Command-line interface. R is available across widely used platforms like Windows, Linux, and macOS. R language provides very easy methods to calculate the average, variance, and standard deviation. Average a number expressing the central or typical value in a set of data, in particular the mode, median, or (most commonly) the mean, which is calculated by dividing the sum of the values in the set by their number. The basic formula for the average of n numbers x1, x2, ......xn is Example: Suppose there are 8 data points, 2, 4, 4, 4, 5, 5, 7, 9 The average of these 8 data points is, To compute the average of values, R provides a pre-defined function mean(). This function takes a Numerical Vector as an argument and results in the average/mean of that Vector. Syntax: mean(x, na.rm) Parameters: x: Numeric Vector na.rm: Boolean value to ignore NA value Example 1: R # R program to get average of a list # Taking a list of elementslist = c(2, 4, 4, 4, 5, 5, 7, 9) # Calculating average using mean()print(mean(list)) Output: [1] 5 Example 2: R # R program to get average of a list # Taking a list of elementslist = c(2, 40, 2, 502, 177, 7, 9) # Calculating average using mean()print(mean(list)) Output: [1] 105.5714 Variance is the sum of squares of differences between all numbers and means. The mathematical formula for variance is as follows, where, N is the total number of elements or frequency of distribution. Example: Let’s consider the same dataset that we have taken in average. First, calculate the deviations of each data point from the mean, and square the result of each,[Tex]variance = \frac{9 + 1 + 1 + 1 + 0 + 0 + 4 + 16}{8} = 4[/Tex] One can calculate the variance by using var() function in R. Syntax: var(x) Parameters: x: numeric vector Example 1: R # R program to get variance of a list # Taking a list of elementslist = c(2, 4, 4, 4, 5, 5, 7, 9) # Calculating variance using var()print(var(list)) Output: [1] 4.571429 Example 2: R # R program to get variance of a list # Taking a list of elementslist = c(212, 231, 234, 564, 235) # Calculating variance using var()print(var(list)) Output: [1] 22666.7 Standard Deviation is the square root of variance. It is a measure of the extent to which data varies from the mean. The mathematical formula for calculating standard deviation is as follows, Example: Standard Deviation for the above data, One can calculate the standard deviation by using sd() function in R. Syntax: sd(x) Parameters: x: numeric vector Example 1: R # R program to get# standard deviation of a list # Taking a list of elementslist = c(2, 4, 4, 4, 5, 5, 7, 9) # Calculating standard# deviation using sd()print(sd(list)) Output: [1] 2.13809 Example 2: R # R program to get# standard deviation of a list # Taking a list of elementslist = c(290, 124, 127, 899) # Calculating standard# deviation using sd()print(sd(list)) Output: [1] 367.6076 kumar_satyam R Data-science R-Statistics R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Dec, 2021" }, { "code": null, "e": 385, "s": 28, "text": "R Programming Language is an open-source programming language that is widely used as a statistical software and data analysis tool. R generally comes with the Command-line interface. R is available across widely used platforms like Windows, Linux, and macOS. R language provides very easy methods to calculate the average, variance, and standard deviation." }, { "code": null, "e": 670, "s": 385, "text": "Average a number expressing the central or typical value in a set of data, in particular the mode, median, or (most commonly) the mean, which is calculated by dividing the sum of the values in the set by their number. The basic formula for the average of n numbers x1, x2, ......xn is" }, { "code": null, "e": 679, "s": 670, "text": "Example:" }, { "code": null, "e": 712, "s": 679, "text": "Suppose there are 8 data points," }, { "code": null, "e": 735, "s": 712, "text": "2, 4, 4, 4, 5, 5, 7, 9" }, { "code": null, "e": 774, "s": 735, "text": "The average of these 8 data points is," }, { "code": null, "e": 952, "s": 774, "text": "To compute the average of values, R provides a pre-defined function mean(). This function takes a Numerical Vector as an argument and results in the average/mean of that Vector." }, { "code": null, "e": 975, "s": 952, "text": "Syntax: mean(x, na.rm)" }, { "code": null, "e": 987, "s": 975, "text": "Parameters:" }, { "code": null, "e": 1005, "s": 987, "text": "x: Numeric Vector" }, { "code": null, "e": 1045, "s": 1005, "text": "na.rm: Boolean value to ignore NA value" }, { "code": null, "e": 1056, "s": 1045, "text": "Example 1:" }, { "code": null, "e": 1058, "s": 1056, "text": "R" }, { "code": "# R program to get average of a list # Taking a list of elementslist = c(2, 4, 4, 4, 5, 5, 7, 9) # Calculating average using mean()print(mean(list))", "e": 1207, "s": 1058, "text": null }, { "code": null, "e": 1216, "s": 1207, "text": " Output:" }, { "code": null, "e": 1222, "s": 1216, "text": "[1] 5" }, { "code": null, "e": 1233, "s": 1222, "text": "Example 2:" }, { "code": null, "e": 1235, "s": 1233, "text": "R" }, { "code": "# R program to get average of a list # Taking a list of elementslist = c(2, 40, 2, 502, 177, 7, 9) # Calculating average using mean()print(mean(list))", "e": 1386, "s": 1235, "text": null }, { "code": null, "e": 1395, "s": 1386, "text": " Output:" }, { "code": null, "e": 1408, "s": 1395, "text": "[1] 105.5714" }, { "code": null, "e": 1538, "s": 1408, "text": "Variance is the sum of squares of differences between all numbers and means. The mathematical formula for variance is as follows," }, { "code": null, "e": 1545, "s": 1538, "text": "where," }, { "code": null, "e": 1610, "s": 1545, "text": "N is the total number of elements or frequency of distribution. " }, { "code": null, "e": 1619, "s": 1610, "text": "Example:" }, { "code": null, "e": 1845, "s": 1619, "text": "Let’s consider the same dataset that we have taken in average. First, calculate the deviations of each data point from the mean, and square the result of each,[Tex]variance = \\frac{9 + 1 + 1 + 1 + 0 + 0 + 4 + 16}{8} = 4[/Tex]" }, { "code": null, "e": 1906, "s": 1845, "text": "One can calculate the variance by using var() function in R." }, { "code": null, "e": 1921, "s": 1906, "text": "Syntax: var(x)" }, { "code": null, "e": 1933, "s": 1921, "text": "Parameters:" }, { "code": null, "e": 1951, "s": 1933, "text": "x: numeric vector" }, { "code": null, "e": 1962, "s": 1951, "text": "Example 1:" }, { "code": null, "e": 1964, "s": 1962, "text": "R" }, { "code": "# R program to get variance of a list # Taking a list of elementslist = c(2, 4, 4, 4, 5, 5, 7, 9) # Calculating variance using var()print(var(list))", "e": 2113, "s": 1964, "text": null }, { "code": null, "e": 2122, "s": 2113, "text": " Output:" }, { "code": null, "e": 2135, "s": 2122, "text": "[1] 4.571429" }, { "code": null, "e": 2146, "s": 2135, "text": "Example 2:" }, { "code": null, "e": 2148, "s": 2146, "text": "R" }, { "code": "# R program to get variance of a list # Taking a list of elementslist = c(212, 231, 234, 564, 235) # Calculating variance using var()print(var(list))", "e": 2298, "s": 2148, "text": null }, { "code": null, "e": 2307, "s": 2298, "text": " Output:" }, { "code": null, "e": 2319, "s": 2307, "text": "[1] 22666.7" }, { "code": null, "e": 2513, "s": 2319, "text": "Standard Deviation is the square root of variance. It is a measure of the extent to which data varies from the mean. The mathematical formula for calculating standard deviation is as follows, " }, { "code": null, "e": 2522, "s": 2513, "text": "Example:" }, { "code": null, "e": 2561, "s": 2522, "text": "Standard Deviation for the above data," }, { "code": null, "e": 2631, "s": 2561, "text": "One can calculate the standard deviation by using sd() function in R." }, { "code": null, "e": 2645, "s": 2631, "text": "Syntax: sd(x)" }, { "code": null, "e": 2657, "s": 2645, "text": "Parameters:" }, { "code": null, "e": 2675, "s": 2657, "text": "x: numeric vector" }, { "code": null, "e": 2686, "s": 2675, "text": "Example 1:" }, { "code": null, "e": 2688, "s": 2686, "text": "R" }, { "code": "# R program to get# standard deviation of a list # Taking a list of elementslist = c(2, 4, 4, 4, 5, 5, 7, 9) # Calculating standard# deviation using sd()print(sd(list))", "e": 2857, "s": 2688, "text": null }, { "code": null, "e": 2866, "s": 2857, "text": " Output:" }, { "code": null, "e": 2878, "s": 2866, "text": "[1] 2.13809" }, { "code": null, "e": 2889, "s": 2878, "text": "Example 2:" }, { "code": null, "e": 2891, "s": 2889, "text": "R" }, { "code": "# R program to get# standard deviation of a list # Taking a list of elementslist = c(290, 124, 127, 899) # Calculating standard# deviation using sd()print(sd(list))", "e": 3056, "s": 2891, "text": null }, { "code": null, "e": 3065, "s": 3056, "text": " Output:" }, { "code": null, "e": 3078, "s": 3065, "text": "[1] 367.6076" }, { "code": null, "e": 3091, "s": 3078, "text": "kumar_satyam" }, { "code": null, "e": 3106, "s": 3091, "text": "R Data-science" }, { "code": null, "e": 3119, "s": 3106, "text": "R-Statistics" }, { "code": null, "e": 3130, "s": 3119, "text": "R Language" } ]
Sum of series (n/1) + (n/2) + (n/3) + (n/4) +.......+ (n/n)
20 Apr, 2021 Given a value n, find the sum of series, (n/1) + (n/2) + (n/3) + (n/4) +.......+(n/n) where the value of n can be up to 10^12. Note: Consider only integer division.Examples: Input : n = 5 Output : (5/1) + (5/2) + (5/3) + (5/4) + (5/5) = 5 + 2 + 1 + 1 + 1 = 10 Input : 7 Output : (7/1) + (7/2) + (7/3) + (7/4) + (7/5) + (7/6) + (7/7) = 7 + 3 + 2 + 1 + 1 + 1 + 1 = 16 Below is the program to find the sum of given series: C++ Java Python3 C# PHP Javascript // CPP program to find// sum of given series#include <bits/stdc++.h>using namespace std; // function to find sum of serieslong long int sum(long long int n){ long long int root = sqrt(n); long long int ans = 0; for (int i = 1; i <= root; i++) ans += n / i; ans = 2 * ans - (root * root); return ans;} // driver codeint main(){ long long int n = 35; cout << sum(n); return 0;} // Java program to find// sum of given seriesimport java.util.*; class GFG { // function to find sum of series static long sum(long n) { long root = (long)Math.sqrt(n); long ans = 0; for (int i = 1; i <= root; i++) ans += n / i; ans = 2 * ans - (root * root); return ans; } /* Driver code */ public static void main(String[] args) { long n = 35; System.out.println(sum(n)); }} // This code is contributed by Arnav Kr. Mandal. # Python 3 program to find# sum of given series import math # function to find sum of seriesdef sum(n) : root = (int)(math.sqrt(n)) ans = 0 for i in range(1, root + 1) : ans = ans + n // i ans = 2 * ans - (root * root) return ans # driver coden = 35print(sum(n)) # This code is contributed by Nikita Tiwari. // C# program to find// sum of given seriesusing System; class GFG { // Function to find sum of series static long sum(long n) { long root = (long)Math.Sqrt(n); long ans = 0; for (int i = 1; i <= root; i++) ans += n / i; ans = 2 * ans - (root * root); return ans; } // Driver code public static void Main() { long n = 35; Console.Write(sum(n)); }} // This code is contributed vt_m. <?php// PHP program to find// sum of given series // function to find// sum of seriesfunction sum($n){ $root = intval(sqrt($n)); $ans = 0; for ($i = 1; $i <= $root; $i++) $ans += intval($n / $i); $ans = (2 * $ans) - ($root * $root); return $ans;} // Driver code$n = 35;echo (sum($n)); // This code is contributed by// Manish Shaw(manishshaw1)?> <script>// Javascript program to find// sum of given series // function to find// sum of seriesfunction sum(n){ let root = parseInt(Math.sqrt(n)); let ans = 0; for (let i = 1; i <= root; i++) ans += parseInt(n / i); ans = (2 * ans) - (root * root); return ans;} // Driver codelet n = 35;document.write(sum(n)); // This code is contributed by gfgking.</script> Output: 131 Note: If observed closely, we can see that, if we take n common, series turns into an Harmonic Progression. manishshaw1 gfgking harmonic progression series Mathematical Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Merge two sorted arrays with O(1) extra space Program to print prime numbers from 1 to N. Find next greater number with same set of digits Segment Tree | Set 1 (Sum of given range) Check if a number is Palindrome Count ways to reach the n'th stair Fizz Buzz Implementation Count all possible paths from top left to bottom right of a mXn matrix Product of Array except itself
[ { "code": null, "e": 54, "s": 26, "text": "\n20 Apr, 2021" }, { "code": null, "e": 230, "s": 54, "text": "Given a value n, find the sum of series, (n/1) + (n/2) + (n/3) + (n/4) +.......+(n/n) where the value of n can be up to 10^12. Note: Consider only integer division.Examples: " }, { "code": null, "e": 484, "s": 230, "text": "Input : n = 5\nOutput : (5/1) + (5/2) + (5/3) + \n (5/4) + (5/5) = 5 + 2 + 1 + 1 + 1 \n = 10\n\nInput : 7\nOutput : (7/1) + (7/2) + (7/3) + (7/4) +\n (7/5) + (7/6) + (7/7) \n = 7 + 3 + 2 + 1 + 1 + 1 + 1 \n = 16" }, { "code": null, "e": 542, "s": 486, "text": "Below is the program to find the sum of given series: " }, { "code": null, "e": 546, "s": 542, "text": "C++" }, { "code": null, "e": 551, "s": 546, "text": "Java" }, { "code": null, "e": 559, "s": 551, "text": "Python3" }, { "code": null, "e": 562, "s": 559, "text": "C#" }, { "code": null, "e": 566, "s": 562, "text": "PHP" }, { "code": null, "e": 577, "s": 566, "text": "Javascript" }, { "code": "// CPP program to find// sum of given series#include <bits/stdc++.h>using namespace std; // function to find sum of serieslong long int sum(long long int n){ long long int root = sqrt(n); long long int ans = 0; for (int i = 1; i <= root; i++) ans += n / i; ans = 2 * ans - (root * root); return ans;} // driver codeint main(){ long long int n = 35; cout << sum(n); return 0;}", "e": 990, "s": 577, "text": null }, { "code": "// Java program to find// sum of given seriesimport java.util.*; class GFG { // function to find sum of series static long sum(long n) { long root = (long)Math.sqrt(n); long ans = 0; for (int i = 1; i <= root; i++) ans += n / i; ans = 2 * ans - (root * root); return ans; } /* Driver code */ public static void main(String[] args) { long n = 35; System.out.println(sum(n)); }} // This code is contributed by Arnav Kr. Mandal. ", "e": 1546, "s": 990, "text": null }, { "code": "# Python 3 program to find# sum of given series import math # function to find sum of seriesdef sum(n) : root = (int)(math.sqrt(n)) ans = 0 for i in range(1, root + 1) : ans = ans + n // i ans = 2 * ans - (root * root) return ans # driver coden = 35print(sum(n)) # This code is contributed by Nikita Tiwari.", "e": 1884, "s": 1546, "text": null }, { "code": "// C# program to find// sum of given seriesusing System; class GFG { // Function to find sum of series static long sum(long n) { long root = (long)Math.Sqrt(n); long ans = 0; for (int i = 1; i <= root; i++) ans += n / i; ans = 2 * ans - (root * root); return ans; } // Driver code public static void Main() { long n = 35; Console.Write(sum(n)); }} // This code is contributed vt_m.", "e": 2387, "s": 1884, "text": null }, { "code": "<?php// PHP program to find// sum of given series // function to find// sum of seriesfunction sum($n){ $root = intval(sqrt($n)); $ans = 0; for ($i = 1; $i <= $root; $i++) $ans += intval($n / $i); $ans = (2 * $ans) - ($root * $root); return $ans;} // Driver code$n = 35;echo (sum($n)); // This code is contributed by// Manish Shaw(manishshaw1)?>", "e": 2766, "s": 2387, "text": null }, { "code": "<script>// Javascript program to find// sum of given series // function to find// sum of seriesfunction sum(n){ let root = parseInt(Math.sqrt(n)); let ans = 0; for (let i = 1; i <= root; i++) ans += parseInt(n / i); ans = (2 * ans) - (root * root); return ans;} // Driver codelet n = 35;document.write(sum(n)); // This code is contributed by gfgking.</script>", "e": 3157, "s": 2766, "text": null }, { "code": null, "e": 3167, "s": 3157, "text": "Output: " }, { "code": null, "e": 3171, "s": 3167, "text": "131" }, { "code": null, "e": 3280, "s": 3171, "text": "Note: If observed closely, we can see that, if we take n common, series turns into an Harmonic Progression. " }, { "code": null, "e": 3292, "s": 3280, "text": "manishshaw1" }, { "code": null, "e": 3300, "s": 3292, "text": "gfgking" }, { "code": null, "e": 3321, "s": 3300, "text": "harmonic progression" }, { "code": null, "e": 3328, "s": 3321, "text": "series" }, { "code": null, "e": 3341, "s": 3328, "text": "Mathematical" }, { "code": null, "e": 3354, "s": 3341, "text": "Mathematical" }, { "code": null, "e": 3361, "s": 3354, "text": "series" }, { "code": null, "e": 3459, "s": 3361, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3491, "s": 3459, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 3537, "s": 3491, "text": "Merge two sorted arrays with O(1) extra space" }, { "code": null, "e": 3581, "s": 3537, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 3630, "s": 3581, "text": "Find next greater number with same set of digits" }, { "code": null, "e": 3672, "s": 3630, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 3704, "s": 3672, "text": "Check if a number is Palindrome" }, { "code": null, "e": 3739, "s": 3704, "text": "Count ways to reach the n'th stair" }, { "code": null, "e": 3764, "s": 3739, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 3835, "s": 3764, "text": "Count all possible paths from top left to bottom right of a mXn matrix" } ]
Opening Modes in Standard I/O in C/C++ with Examples
26 Nov, 2021 Pre-requisites: File Handling in C++ So far the operations using the C program are done on a prompt/terminal that is not stored anywhere. But in the software industry, most of the programs are written to store the information fetched from the program. One such way is to store the fetched information in a file. Different operations that can be performed on a file are: Creation of a new file (fopen with attributes as “a” or “a+” or “w” or “w++”).Opening an existing file (fopen).Reading from file (fscanf or fgets).Writing to a file (fprintf or fputs).Moving to a specific location in a file (fseek, rewind).Closing a file (fclose). Creation of a new file (fopen with attributes as “a” or “a+” or “w” or “w++”). Opening an existing file (fopen). Reading from file (fscanf or fgets). Writing to a file (fprintf or fputs). Moving to a specific location in a file (fseek, rewind). Closing a file (fclose). The text in the brackets denotes the functions used for performing those operations. Why files are needed? Data Preservation: Storing data in files helps to preserve data even if the program terminates. Easy Data Access: Accessing data becomes easy when there is a large amount of data and it is stored in the file, then this data can be accessed using the C commands. Portability: It becomes easier to move data from one computer to another without any changes. Types of files They are two types of files that everyone should be aware of- Text Files: Text files are the normal files that have an extension “.txt” in the file name. These can be simply created using editors like Notepad. Upon opening the files the text will be visible lie simple plain text and the content can be easily edited or deleted. These are the lowest maintenance files, easy to read. But there are a few disadvantages of text files like they are the least secure files and take bigger storage space.Binary Files: Binary files are “.bin” extension files. Data in these files are stored in the binary form i.e. 0’s and 1’s. These files can hold a large amount of data and provide a higher level of security than text files but these files are not easily readable. Text Files: Text files are the normal files that have an extension “.txt” in the file name. These can be simply created using editors like Notepad. Upon opening the files the text will be visible lie simple plain text and the content can be easily edited or deleted. These are the lowest maintenance files, easy to read. But there are a few disadvantages of text files like they are the least secure files and take bigger storage space. Binary Files: Binary files are “.bin” extension files. Data in these files are stored in the binary form i.e. 0’s and 1’s. These files can hold a large amount of data and provide a higher level of security than text files but these files are not easily readable. File Operations There are four basic operations that can be performed on a file: Creating a new file.Opening an existing file.Reading from or writing information to the file.Closing the file. Creating a new file. Opening an existing file. Reading from or writing information to the file. Closing the file. Working with files When working with the files, there is a need to declare a pointer of the type file. This file-type pointer is needed for communication between the file and the program. File *fptr; Opening a file Opening a file is done using the fopen() function in the header file stdio.h. Syntax: fptr = fopen(“file_name”, “mode”); Example: fopen(“D:\\geeksforgeeks\\newprogramgfg.txt”, “w”);fopen(“D:\\geeksforgeeks\\oldprogramgfg.bin”, “rb”); Suppose the file newprogramgfg.txt doesn’t exist in the location D:\geeksforgeeks. The first function creates a new file named newprogramgfg.txt and opens it for writing as per the mode ‘w’. The writing mode allows you to create and edit (overwrite) the contents of the file. Suppose the second binary file oldprogramgfg.bin exists in the location D:\geeksforgeeks. The second function opens the existing file for reading in binary mode ‘rb’. The reading mode only allows one to read the file, one cannot write into the file. File Opening modes in C: Closing a file The file should be closed after reading or writing. Closing a file is performed using the fclose() function. Syntax: fclose(fptr); Here, fptr is the file type pointer associated with the file to be closed. Reading and writing to a text file For reading and writing to a text file, the functions fprintf() and fscanf() are used. They are the file versions of the printf() and scanf() functions. The only difference is that the fprintf() and fscanf() expect the pointer to the structure file. Write to a text file: Syntax: FILE *filePointer;filePointer = fopen(“filename.txt”, “w”) Below is the C program to write to a text file. C // C program to implement// the above approach#include <stdio.h>#include <string.h> // Driver codeint main(){ // Declare the file pointer FILE* filePointer; // Get the data to be written in file char dataToBeWritten[50] = "GeeksforGeeks-A Computer" + " Science Portal for Geeks"; // Open the existing file GfgTest.c using fopen() // in write mode using "w" attribute filePointer = fopen("GfgTest.txt", "w"); // Check if this filePointer is null // which maybe if the file does not exist if (filePointer == NULL) { printf("GfgTest.txt file failed to open."); } else { printf("The file is now opened.\n"); // Write the dataToBeWritten into the file if (strlen(dataToBeWritten) > 0) { // writing in the file using fputs() fprintf(filePointer, dataToBeWritten); fprintf(filePointer, "\n"); } // Closing the file using fclose() fclose(filePointer); printf("Data successfully written" + " in file GfgTest.txt\n"); printf("The file is now closed."); } return 0;} Output: Read from a file: Syntax: FILE * filePointer; filePointer = fopen(“fileName.txt”, “r”); Below is the C program to read text file. C // C program to implement// the above approach#include <stdio.h>#include <string.h> // Driver codeint main(){ // Declare the file pointer FILE* filePointer; // Declare the variable for the data // to be read from file char dataToBeRead[50]; // Open the existing file GfgTest.txt // using fopen() in read mode using // "r" attribute filePointer = fopen("GfgTest.txt", "r"); // Check if this filePointer is null // which maybe if the file does not exist if (filePointer == NULL) { printf("GfgTest.txt file failed to open."); } else { printf("The file is now opened.\n"); // Read the dataToBeRead from the file // using fgets() method while (fgets(dataToBeRead, 50, filePointer) != NULL) { // Print the dataToBeRead printf("%s", dataToBeRead); } // Closing the file using fclose() fclose(filePointer); printf("Data successfully read" + " from file GfgTest.txt\n"); printf("The file is now closed."); } return 0;} Output: Reading and writing in binary file Write a binary file: Syntax: FILE *filePointer;filePointer = fopen(“fileName.bin”, “wb”); To write data to a binary file, fwrite() function is needed. This function takes four arguments: Address of data to be written in the disk.Size of data to be written on the disk.The number of such types of data.Pointer to the file where you want to write. Address of data to be written in the disk. Size of data to be written on the disk. The number of such types of data. Pointer to the file where you want to write. Syntax: fwrite(addressData, sizeofData, numbersData, pointerToFile); Below is the C program to implement the above approach: C++ // C program to implement// the above approach#include <stdio.h>#include <stdlib.h> struct threeNum { int n1, n2, n3;}; // Driver codeint main(){ int n; struct threeNum num; // Declaring the file pointer FILE* fptr; if ((fptr = fopen("C:\\GfgTest.bin", "wb")) == NULL) { printf("Error! opening file"); // Program exits if the file pointer // returns NULL. exit(1); } for (n = 1; n < 5; ++n) { num.n1 = n; num.n2 = 5 * n; num.n3 = 5 * n + 1; fwrite(&num, sizeof(struct threeNum), 1, fptr); } printf("The file GfgTest.bin is" + " written successfully"); fclose(fptr); return 0;} Read from a binary file: Syntax: FILE * filePointer;filePointer = fopen(“fileName.txt”, “rb”); To read data from a binary file, fread(0 function is used. Similar to fwrite() function, this function also takes four arguments. Syntax: fread(addressData, sizeofData, numbersData, pointerToFile); Below is the C program to implement the above approach: C++ // C program to implement// the above approach#include <stdio.h>#include <stdlib.h> struct threeNum { int n1, n2, n3;}; // Driver codeint main(){ int n; struct threeNum num; // Declaring the file pointer FILE* fptr; if ((fptr = fopen("C:\\GfgTest.bin", "rb")) == NULL) { printf("Error! opening file"); // Program exits if the file pointer // returns NULL. exit(1); } for (n = 1; n < 5; ++n) { fread(&num, sizeof(struct threeNum), 1, fptr); printf("n1: %d\tn2: %d\tn3: %d", num.n1, num.n2, num.n3); printf("\n"); } fclose(fptr); return 0;} Output: Append content in text file Syntax: FILE * filePointer;filePointer = fopen(“fileName.txt”, “a”); Once file is opened in append mode, rest of the task is same as that to write content in a text file. Below is the example to append a string to the file: C++ // C program to implement// the above approach#include <stdio.h>#include <string.h> // Driver codeint main(){ // Declare the file pointer FILE* filePointer; // Get the data to be appended in file char dataToBeWritten[100] = "It is a platform for" + " learning language" + " tech related topics"; // Open the existing file GfgTest.txt using // fopen() in append mode using "a" attribute filePointer = fopen("GfgTest.txt", "a"); // Check if this filePointer is null // which maybe if the file does not exist if (filePointer == NULL) { printf("GfgTest.txt file failed to open."); } else { printf("The file is now opened.\n"); // Append the dataToBeWritten into the file if (strlen(dataToBeWritten) > 0) { // writing in the file using fputs() fprintf(filePointer, dataToBeWritten); fprintf(filePointer, "\n"); } // Closing the file using fclose() fclose(filePointer); printf("Data successfully appended" + " in file GfgTest.txt\n"); printf("The file is now closed."); } return 0;} Output: Append content in binary file Syntax: FILE * filePointer;filePointer = fopen(“fileName.bin”, “ab”); Once file is opened in append mode, rest of the task is same as that to write content in a binary file. C++ // C program to implement// the above approach#include <stdio.h>#include <stdlib.h> struct threeNum { int n1, n2, n3;}; // Driver codeint main(){ int n; struct threeNum num; // Declaring the file pointer FILE* fptr; // Opening the file in // append mode if ((fptr = fopen("C:\\GfgTest.bin", "ab")) == NULL) { printf("Error! opening file"); // Program exits if the file pointer // returns NULL. exit(1); } for (n = 1; n < 10; ++n) { num.n1 = n; num.n2 = 5 * n; num.n3 = 5 * n + 1; fwrite(&num, sizeof(struct threeNum), 1, fptr); } printf("The file GfgTest.bin" + " is appended successfully"); fclose(fptr); return 0;} Output: Opening file for both reading and writing Syntax: FILE * filePointer;filePointer = fopen(“fileName.txt”, “r+”); The file is opened using the mode “r+'” and the file is opened in both reading and writing mode. C++ // C program to implement// the above approach#include <stdio.h>#include <string.h> // Driver codeint main(){ // Declare the file pointer FILE* filePointer; char dataToBeWritten[100] = "It is a platform for" + " learning language" + " tech related topics."; // Declare the variable for the data // to be read from file char dataToBeRead[50]; // Open the existing file GfgTest.txt // using fopen() in read mode using // "r+" attribute filePointer = fopen("GfgTest.txt", "r+"); // Check if this filePointer is null // which maybe if the file does not exist if (filePointer == NULL) { printf("GfgTest.txt file failed to open."); } else { printf("The file is now opened.\n"); // Read the dataToBeRead from the file // using fgets() method while (fgets(dataToBeRead, 50, filePointer) != NULL) { // Print the dataToBeRead printf("%s", dataToBeRead); } printf( "\nData successfully read" + " from file GfgTest.txt"); if (strlen(dataToBeWritten) > 0) { // writing in the file using fprintf() fprintf(filePointer, dataToBeWritten); fprintf(filePointer, "\n"); } printf("\nData successfully" + " written to the file"); // Closing the file using fclose() fclose(filePointer); printf("\nThe file is now closed."); } return 0;} Output: Opening file for both reading and writing in binary mode Syntax: FILE * filePointer;filePointer = fopen(“fileName.bin”, “rb+”); C++ // C program to implement// the above approach#include <stdio.h>#include <stdlib.h> struct threeNum { int n1, n2, n3;}; // Driver codeint main(){ int n; struct threeNum num; // Declaring the file pointer FILE* fptr; if ((fptr = fopen("C:\\GfgTest.bin", "rb")) == NULL) { printf("Error! opening file"); // Program exits if the file pointer // returns NULL. exit(1); } for (n = 1; n < 5; ++n) { fread(&num, sizeof(struct threeNum), 1, fptr); printf("n1: %d\tn2: %d\tn3: %d", num.n1, num.n2, num.n3); printf("\n"); } printf("Data successfully read from the file"); for (n = 1; n < 7; ++n) { num.n1 = n; num.n2 = 5 * n; num.n3 = 5 * n + 1; fwrite(&num, sizeof(struct threeNum), 1, fptr); } printf("The file GfgTest.bin" + " is written successfully"); fclose(fptr); return 0;} Output: Opening file for both reading and writing in text mode In this mode, the file is opened for both reading and writing in text mode. If the file exists, then the content is overwritten in the file, and in case the file does not exist then in that case, a new file is created. Syntax: FILE * filePointer;filePointer = fopen(“fileName.txt”, “w+”); C++ // C program to implement// the above approach#include <stdio.h>#include <string.h> // Driver codeint main(){ // Declare the file pointer FILE* filePointer; char dataToBeWritten[100] = "It is a platform" + " for learning language" + " tech related topics."; // Declare the variable for the data // to be read from file char dataToBeRead[50]; // Open the existing file GfgTest.txt // using fopen() in read mode using // "r+" attribute filePointer = fopen("GfgTest.txt", "w+"); // Check if this filePointer is null // which maybe if the file does not exist if (filePointer == NULL) { printf("GfgTest.txt file failed to open."); } else { printf("The file is now opened.\n"); if (strlen(dataToBeWritten) > 0) { // writing in the file using fprintf() fprintf(filePointer, dataToBeWritten); fprintf(filePointer, "\n"); } printf("Data successfully" + " written to the file\n"); // Read the dataToBeRead from the file // using fgets() method while (fgets(dataToBeRead, 50, filePointer) != NULL) { // Print the dataToBeRead printf("%s", dataToBeRead); } printf("\nData successfully read" + " from file GfgTest.txt"); // Closing the file using fclose() fclose(filePointer); printf("\nThe file is now closed."); } return 0;} C-File Handling cpp-file-handling C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Function Pointer in C Left Shift and Right Shift Operators in C/C++ Different Methods to Reverse a String in C++ std::string class in C++ Vector in C++ STL Map in C++ Standard Template Library (STL) Initialize a vector in C++ (7 different ways) Set in C++ Standard Template Library (STL) vector erase() and clear() in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n26 Nov, 2021" }, { "code": null, "e": 89, "s": 52, "text": "Pre-requisites: File Handling in C++" }, { "code": null, "e": 424, "s": 89, "text": "So far the operations using the C program are done on a prompt/terminal that is not stored anywhere. But in the software industry, most of the programs are written to store the information fetched from the program. One such way is to store the fetched information in a file. Different operations that can be performed on a file are: " }, { "code": null, "e": 689, "s": 424, "text": "Creation of a new file (fopen with attributes as “a” or “a+” or “w” or “w++”).Opening an existing file (fopen).Reading from file (fscanf or fgets).Writing to a file (fprintf or fputs).Moving to a specific location in a file (fseek, rewind).Closing a file (fclose)." }, { "code": null, "e": 768, "s": 689, "text": "Creation of a new file (fopen with attributes as “a” or “a+” or “w” or “w++”)." }, { "code": null, "e": 802, "s": 768, "text": "Opening an existing file (fopen)." }, { "code": null, "e": 839, "s": 802, "text": "Reading from file (fscanf or fgets)." }, { "code": null, "e": 877, "s": 839, "text": "Writing to a file (fprintf or fputs)." }, { "code": null, "e": 934, "s": 877, "text": "Moving to a specific location in a file (fseek, rewind)." }, { "code": null, "e": 959, "s": 934, "text": "Closing a file (fclose)." }, { "code": null, "e": 1044, "s": 959, "text": "The text in the brackets denotes the functions used for performing those operations." }, { "code": null, "e": 1066, "s": 1044, "text": "Why files are needed?" }, { "code": null, "e": 1162, "s": 1066, "text": "Data Preservation: Storing data in files helps to preserve data even if the program terminates." }, { "code": null, "e": 1328, "s": 1162, "text": "Easy Data Access: Accessing data becomes easy when there is a large amount of data and it is stored in the file, then this data can be accessed using the C commands." }, { "code": null, "e": 1422, "s": 1328, "text": "Portability: It becomes easier to move data from one computer to another without any changes." }, { "code": null, "e": 1437, "s": 1422, "text": "Types of files" }, { "code": null, "e": 1499, "s": 1437, "text": "They are two types of files that everyone should be aware of-" }, { "code": null, "e": 2198, "s": 1499, "text": "Text Files: Text files are the normal files that have an extension “.txt” in the file name. These can be simply created using editors like Notepad. Upon opening the files the text will be visible lie simple plain text and the content can be easily edited or deleted. These are the lowest maintenance files, easy to read. But there are a few disadvantages of text files like they are the least secure files and take bigger storage space.Binary Files: Binary files are “.bin” extension files. Data in these files are stored in the binary form i.e. 0’s and 1’s. These files can hold a large amount of data and provide a higher level of security than text files but these files are not easily readable." }, { "code": null, "e": 2635, "s": 2198, "text": "Text Files: Text files are the normal files that have an extension “.txt” in the file name. These can be simply created using editors like Notepad. Upon opening the files the text will be visible lie simple plain text and the content can be easily edited or deleted. These are the lowest maintenance files, easy to read. But there are a few disadvantages of text files like they are the least secure files and take bigger storage space." }, { "code": null, "e": 2898, "s": 2635, "text": "Binary Files: Binary files are “.bin” extension files. Data in these files are stored in the binary form i.e. 0’s and 1’s. These files can hold a large amount of data and provide a higher level of security than text files but these files are not easily readable." }, { "code": null, "e": 2914, "s": 2898, "text": "File Operations" }, { "code": null, "e": 2979, "s": 2914, "text": "There are four basic operations that can be performed on a file:" }, { "code": null, "e": 3090, "s": 2979, "text": "Creating a new file.Opening an existing file.Reading from or writing information to the file.Closing the file." }, { "code": null, "e": 3111, "s": 3090, "text": "Creating a new file." }, { "code": null, "e": 3137, "s": 3111, "text": "Opening an existing file." }, { "code": null, "e": 3186, "s": 3137, "text": "Reading from or writing information to the file." }, { "code": null, "e": 3204, "s": 3186, "text": "Closing the file." }, { "code": null, "e": 3223, "s": 3204, "text": "Working with files" }, { "code": null, "e": 3392, "s": 3223, "text": "When working with the files, there is a need to declare a pointer of the type file. This file-type pointer is needed for communication between the file and the program." }, { "code": null, "e": 3404, "s": 3392, "text": "File *fptr;" }, { "code": null, "e": 3419, "s": 3404, "text": "Opening a file" }, { "code": null, "e": 3497, "s": 3419, "text": "Opening a file is done using the fopen() function in the header file stdio.h." }, { "code": null, "e": 3505, "s": 3497, "text": "Syntax:" }, { "code": null, "e": 3540, "s": 3505, "text": "fptr = fopen(“file_name”, “mode”);" }, { "code": null, "e": 3549, "s": 3540, "text": "Example:" }, { "code": null, "e": 3653, "s": 3549, "text": "fopen(“D:\\\\geeksforgeeks\\\\newprogramgfg.txt”, “w”);fopen(“D:\\\\geeksforgeeks\\\\oldprogramgfg.bin”, “rb”);" }, { "code": null, "e": 3929, "s": 3653, "text": "Suppose the file newprogramgfg.txt doesn’t exist in the location D:\\geeksforgeeks. The first function creates a new file named newprogramgfg.txt and opens it for writing as per the mode ‘w’. The writing mode allows you to create and edit (overwrite) the contents of the file." }, { "code": null, "e": 4179, "s": 3929, "text": "Suppose the second binary file oldprogramgfg.bin exists in the location D:\\geeksforgeeks. The second function opens the existing file for reading in binary mode ‘rb’. The reading mode only allows one to read the file, one cannot write into the file." }, { "code": null, "e": 4205, "s": 4179, "text": "File Opening modes in C: " }, { "code": null, "e": 4220, "s": 4205, "text": "Closing a file" }, { "code": null, "e": 4329, "s": 4220, "text": "The file should be closed after reading or writing. Closing a file is performed using the fclose() function." }, { "code": null, "e": 4337, "s": 4329, "text": "Syntax:" }, { "code": null, "e": 4351, "s": 4337, "text": "fclose(fptr);" }, { "code": null, "e": 4426, "s": 4351, "text": "Here, fptr is the file type pointer associated with the file to be closed." }, { "code": null, "e": 4461, "s": 4426, "text": "Reading and writing to a text file" }, { "code": null, "e": 4711, "s": 4461, "text": "For reading and writing to a text file, the functions fprintf() and fscanf() are used. They are the file versions of the printf() and scanf() functions. The only difference is that the fprintf() and fscanf() expect the pointer to the structure file." }, { "code": null, "e": 4733, "s": 4711, "text": "Write to a text file:" }, { "code": null, "e": 4741, "s": 4733, "text": "Syntax:" }, { "code": null, "e": 4800, "s": 4741, "text": "FILE *filePointer;filePointer = fopen(“filename.txt”, “w”)" }, { "code": null, "e": 4848, "s": 4800, "text": "Below is the C program to write to a text file." }, { "code": null, "e": 4850, "s": 4848, "text": "C" }, { "code": "// C program to implement// the above approach#include <stdio.h>#include <string.h> // Driver codeint main(){ // Declare the file pointer FILE* filePointer; // Get the data to be written in file char dataToBeWritten[50] = \"GeeksforGeeks-A Computer\" + \" Science Portal for Geeks\"; // Open the existing file GfgTest.c using fopen() // in write mode using \"w\" attribute filePointer = fopen(\"GfgTest.txt\", \"w\"); // Check if this filePointer is null // which maybe if the file does not exist if (filePointer == NULL) { printf(\"GfgTest.txt file failed to open.\"); } else { printf(\"The file is now opened.\\n\"); // Write the dataToBeWritten into the file if (strlen(dataToBeWritten) > 0) { // writing in the file using fputs() fprintf(filePointer, dataToBeWritten); fprintf(filePointer, \"\\n\"); } // Closing the file using fclose() fclose(filePointer); printf(\"Data successfully written\" + \" in file GfgTest.txt\\n\"); printf(\"The file is now closed.\"); } return 0;}", "e": 5987, "s": 4850, "text": null }, { "code": null, "e": 5995, "s": 5987, "text": "Output:" }, { "code": null, "e": 6013, "s": 5995, "text": "Read from a file:" }, { "code": null, "e": 6021, "s": 6013, "text": "Syntax:" }, { "code": null, "e": 6041, "s": 6021, "text": "FILE * filePointer;" }, { "code": null, "e": 6083, "s": 6041, "text": "filePointer = fopen(“fileName.txt”, “r”);" }, { "code": null, "e": 6125, "s": 6083, "text": "Below is the C program to read text file." }, { "code": null, "e": 6127, "s": 6125, "text": "C" }, { "code": "// C program to implement// the above approach#include <stdio.h>#include <string.h> // Driver codeint main(){ // Declare the file pointer FILE* filePointer; // Declare the variable for the data // to be read from file char dataToBeRead[50]; // Open the existing file GfgTest.txt // using fopen() in read mode using // \"r\" attribute filePointer = fopen(\"GfgTest.txt\", \"r\"); // Check if this filePointer is null // which maybe if the file does not exist if (filePointer == NULL) { printf(\"GfgTest.txt file failed to open.\"); } else { printf(\"The file is now opened.\\n\"); // Read the dataToBeRead from the file // using fgets() method while (fgets(dataToBeRead, 50, filePointer) != NULL) { // Print the dataToBeRead printf(\"%s\", dataToBeRead); } // Closing the file using fclose() fclose(filePointer); printf(\"Data successfully read\" + \" from file GfgTest.txt\\n\"); printf(\"The file is now closed.\"); } return 0;}", "e": 7238, "s": 6127, "text": null }, { "code": null, "e": 7246, "s": 7238, "text": "Output:" }, { "code": null, "e": 7281, "s": 7246, "text": "Reading and writing in binary file" }, { "code": null, "e": 7302, "s": 7281, "text": "Write a binary file:" }, { "code": null, "e": 7310, "s": 7302, "text": "Syntax:" }, { "code": null, "e": 7371, "s": 7310, "text": "FILE *filePointer;filePointer = fopen(“fileName.bin”, “wb”);" }, { "code": null, "e": 7468, "s": 7371, "text": "To write data to a binary file, fwrite() function is needed. This function takes four arguments:" }, { "code": null, "e": 7627, "s": 7468, "text": "Address of data to be written in the disk.Size of data to be written on the disk.The number of such types of data.Pointer to the file where you want to write." }, { "code": null, "e": 7670, "s": 7627, "text": "Address of data to be written in the disk." }, { "code": null, "e": 7710, "s": 7670, "text": "Size of data to be written on the disk." }, { "code": null, "e": 7744, "s": 7710, "text": "The number of such types of data." }, { "code": null, "e": 7789, "s": 7744, "text": "Pointer to the file where you want to write." }, { "code": null, "e": 7797, "s": 7789, "text": "Syntax:" }, { "code": null, "e": 7858, "s": 7797, "text": "fwrite(addressData, sizeofData, numbersData, pointerToFile);" }, { "code": null, "e": 7914, "s": 7858, "text": "Below is the C program to implement the above approach:" }, { "code": null, "e": 7918, "s": 7914, "text": "C++" }, { "code": "// C program to implement// the above approach#include <stdio.h>#include <stdlib.h> struct threeNum { int n1, n2, n3;}; // Driver codeint main(){ int n; struct threeNum num; // Declaring the file pointer FILE* fptr; if ((fptr = fopen(\"C:\\\\GfgTest.bin\", \"wb\")) == NULL) { printf(\"Error! opening file\"); // Program exits if the file pointer // returns NULL. exit(1); } for (n = 1; n < 5; ++n) { num.n1 = n; num.n2 = 5 * n; num.n3 = 5 * n + 1; fwrite(&num, sizeof(struct threeNum), 1, fptr); } printf(\"The file GfgTest.bin is\" + \" written successfully\"); fclose(fptr); return 0;}", "e": 8651, "s": 7918, "text": null }, { "code": null, "e": 8678, "s": 8653, "text": "Read from a binary file:" }, { "code": null, "e": 8686, "s": 8678, "text": "Syntax:" }, { "code": null, "e": 8748, "s": 8686, "text": "FILE * filePointer;filePointer = fopen(“fileName.txt”, “rb”);" }, { "code": null, "e": 8878, "s": 8748, "text": "To read data from a binary file, fread(0 function is used. Similar to fwrite() function, this function also takes four arguments." }, { "code": null, "e": 8886, "s": 8878, "text": "Syntax:" }, { "code": null, "e": 8946, "s": 8886, "text": "fread(addressData, sizeofData, numbersData, pointerToFile);" }, { "code": null, "e": 9002, "s": 8946, "text": "Below is the C program to implement the above approach:" }, { "code": null, "e": 9006, "s": 9002, "text": "C++" }, { "code": "// C program to implement// the above approach#include <stdio.h>#include <stdlib.h> struct threeNum { int n1, n2, n3;}; // Driver codeint main(){ int n; struct threeNum num; // Declaring the file pointer FILE* fptr; if ((fptr = fopen(\"C:\\\\GfgTest.bin\", \"rb\")) == NULL) { printf(\"Error! opening file\"); // Program exits if the file pointer // returns NULL. exit(1); } for (n = 1; n < 5; ++n) { fread(&num, sizeof(struct threeNum), 1, fptr); printf(\"n1: %d\\tn2: %d\\tn3: %d\", num.n1, num.n2, num.n3); printf(\"\\n\"); } fclose(fptr); return 0;}", "e": 9694, "s": 9006, "text": null }, { "code": null, "e": 9702, "s": 9694, "text": "Output:" }, { "code": null, "e": 9730, "s": 9702, "text": "Append content in text file" }, { "code": null, "e": 9738, "s": 9730, "text": "Syntax:" }, { "code": null, "e": 9799, "s": 9738, "text": "FILE * filePointer;filePointer = fopen(“fileName.txt”, “a”);" }, { "code": null, "e": 9901, "s": 9799, "text": "Once file is opened in append mode, rest of the task is same as that to write content in a text file." }, { "code": null, "e": 9954, "s": 9901, "text": "Below is the example to append a string to the file:" }, { "code": null, "e": 9958, "s": 9954, "text": "C++" }, { "code": "// C program to implement// the above approach#include <stdio.h>#include <string.h> // Driver codeint main(){ // Declare the file pointer FILE* filePointer; // Get the data to be appended in file char dataToBeWritten[100] = \"It is a platform for\" + \" learning language\" + \" tech related topics\"; // Open the existing file GfgTest.txt using // fopen() in append mode using \"a\" attribute filePointer = fopen(\"GfgTest.txt\", \"a\"); // Check if this filePointer is null // which maybe if the file does not exist if (filePointer == NULL) { printf(\"GfgTest.txt file failed to open.\"); } else { printf(\"The file is now opened.\\n\"); // Append the dataToBeWritten into the file if (strlen(dataToBeWritten) > 0) { // writing in the file using fputs() fprintf(filePointer, dataToBeWritten); fprintf(filePointer, \"\\n\"); } // Closing the file using fclose() fclose(filePointer); printf(\"Data successfully appended\" + \" in file GfgTest.txt\\n\"); printf(\"The file is now closed.\"); } return 0;}", "e": 11125, "s": 9958, "text": null }, { "code": null, "e": 11133, "s": 11125, "text": "Output:" }, { "code": null, "e": 11163, "s": 11133, "text": "Append content in binary file" }, { "code": null, "e": 11171, "s": 11163, "text": "Syntax:" }, { "code": null, "e": 11233, "s": 11171, "text": "FILE * filePointer;filePointer = fopen(“fileName.bin”, “ab”);" }, { "code": null, "e": 11337, "s": 11233, "text": "Once file is opened in append mode, rest of the task is same as that to write content in a binary file." }, { "code": null, "e": 11341, "s": 11337, "text": "C++" }, { "code": "// C program to implement// the above approach#include <stdio.h>#include <stdlib.h> struct threeNum { int n1, n2, n3;}; // Driver codeint main(){ int n; struct threeNum num; // Declaring the file pointer FILE* fptr; // Opening the file in // append mode if ((fptr = fopen(\"C:\\\\GfgTest.bin\", \"ab\")) == NULL) { printf(\"Error! opening file\"); // Program exits if the file pointer // returns NULL. exit(1); } for (n = 1; n < 10; ++n) { num.n1 = n; num.n2 = 5 * n; num.n3 = 5 * n + 1; fwrite(&num, sizeof(struct threeNum), 1, fptr); } printf(\"The file GfgTest.bin\" + \" is appended successfully\"); fclose(fptr); return 0;}", "e": 12120, "s": 11341, "text": null }, { "code": null, "e": 12128, "s": 12120, "text": "Output:" }, { "code": null, "e": 12170, "s": 12128, "text": "Opening file for both reading and writing" }, { "code": null, "e": 12178, "s": 12170, "text": "Syntax:" }, { "code": null, "e": 12240, "s": 12178, "text": "FILE * filePointer;filePointer = fopen(“fileName.txt”, “r+”);" }, { "code": null, "e": 12337, "s": 12240, "text": "The file is opened using the mode “r+'” and the file is opened in both reading and writing mode." }, { "code": null, "e": 12341, "s": 12337, "text": "C++" }, { "code": "// C program to implement// the above approach#include <stdio.h>#include <string.h> // Driver codeint main(){ // Declare the file pointer FILE* filePointer; char dataToBeWritten[100] = \"It is a platform for\" + \" learning language\" + \" tech related topics.\"; // Declare the variable for the data // to be read from file char dataToBeRead[50]; // Open the existing file GfgTest.txt // using fopen() in read mode using // \"r+\" attribute filePointer = fopen(\"GfgTest.txt\", \"r+\"); // Check if this filePointer is null // which maybe if the file does not exist if (filePointer == NULL) { printf(\"GfgTest.txt file failed to open.\"); } else { printf(\"The file is now opened.\\n\"); // Read the dataToBeRead from the file // using fgets() method while (fgets(dataToBeRead, 50, filePointer) != NULL) { // Print the dataToBeRead printf(\"%s\", dataToBeRead); } printf( \"\\nData successfully read\" + \" from file GfgTest.txt\"); if (strlen(dataToBeWritten) > 0) { // writing in the file using fprintf() fprintf(filePointer, dataToBeWritten); fprintf(filePointer, \"\\n\"); } printf(\"\\nData successfully\" + \" written to the file\"); // Closing the file using fclose() fclose(filePointer); printf(\"\\nThe file is now closed.\"); } return 0;}", "e": 13865, "s": 12341, "text": null }, { "code": null, "e": 13873, "s": 13865, "text": "Output:" }, { "code": null, "e": 13930, "s": 13873, "text": "Opening file for both reading and writing in binary mode" }, { "code": null, "e": 13938, "s": 13930, "text": "Syntax:" }, { "code": null, "e": 14001, "s": 13938, "text": "FILE * filePointer;filePointer = fopen(“fileName.bin”, “rb+”);" }, { "code": null, "e": 14005, "s": 14001, "text": "C++" }, { "code": "// C program to implement// the above approach#include <stdio.h>#include <stdlib.h> struct threeNum { int n1, n2, n3;}; // Driver codeint main(){ int n; struct threeNum num; // Declaring the file pointer FILE* fptr; if ((fptr = fopen(\"C:\\\\GfgTest.bin\", \"rb\")) == NULL) { printf(\"Error! opening file\"); // Program exits if the file pointer // returns NULL. exit(1); } for (n = 1; n < 5; ++n) { fread(&num, sizeof(struct threeNum), 1, fptr); printf(\"n1: %d\\tn2: %d\\tn3: %d\", num.n1, num.n2, num.n3); printf(\"\\n\"); } printf(\"Data successfully read from the file\"); for (n = 1; n < 7; ++n) { num.n1 = n; num.n2 = 5 * n; num.n3 = 5 * n + 1; fwrite(&num, sizeof(struct threeNum), 1, fptr); } printf(\"The file GfgTest.bin\" + \" is written successfully\"); fclose(fptr); return 0;}", "e": 14994, "s": 14005, "text": null }, { "code": null, "e": 15002, "s": 14994, "text": "Output:" }, { "code": null, "e": 15057, "s": 15002, "text": "Opening file for both reading and writing in text mode" }, { "code": null, "e": 15276, "s": 15057, "text": "In this mode, the file is opened for both reading and writing in text mode. If the file exists, then the content is overwritten in the file, and in case the file does not exist then in that case, a new file is created." }, { "code": null, "e": 15284, "s": 15276, "text": "Syntax:" }, { "code": null, "e": 15346, "s": 15284, "text": "FILE * filePointer;filePointer = fopen(“fileName.txt”, “w+”);" }, { "code": null, "e": 15350, "s": 15346, "text": "C++" }, { "code": "// C program to implement// the above approach#include <stdio.h>#include <string.h> // Driver codeint main(){ // Declare the file pointer FILE* filePointer; char dataToBeWritten[100] = \"It is a platform\" + \" for learning language\" + \" tech related topics.\"; // Declare the variable for the data // to be read from file char dataToBeRead[50]; // Open the existing file GfgTest.txt // using fopen() in read mode using // \"r+\" attribute filePointer = fopen(\"GfgTest.txt\", \"w+\"); // Check if this filePointer is null // which maybe if the file does not exist if (filePointer == NULL) { printf(\"GfgTest.txt file failed to open.\"); } else { printf(\"The file is now opened.\\n\"); if (strlen(dataToBeWritten) > 0) { // writing in the file using fprintf() fprintf(filePointer, dataToBeWritten); fprintf(filePointer, \"\\n\"); } printf(\"Data successfully\" + \" written to the file\\n\"); // Read the dataToBeRead from the file // using fgets() method while (fgets(dataToBeRead, 50, filePointer) != NULL) { // Print the dataToBeRead printf(\"%s\", dataToBeRead); } printf(\"\\nData successfully read\" + \" from file GfgTest.txt\"); // Closing the file using fclose() fclose(filePointer); printf(\"\\nThe file is now closed.\"); } return 0;}", "e": 16865, "s": 15350, "text": null }, { "code": null, "e": 16881, "s": 16865, "text": "C-File Handling" }, { "code": null, "e": 16899, "s": 16881, "text": "cpp-file-handling" }, { "code": null, "e": 16910, "s": 16899, "text": "C Language" }, { "code": null, "e": 16914, "s": 16910, "text": "C++" }, { "code": null, "e": 16918, "s": 16914, "text": "CPP" }, { "code": null, "e": 17016, "s": 16918, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 17033, "s": 17016, "text": "Substring in C++" }, { "code": null, "e": 17055, "s": 17033, "text": "Function Pointer in C" }, { "code": null, "e": 17101, "s": 17055, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 17146, "s": 17101, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 17171, "s": 17146, "text": "std::string class in C++" }, { "code": null, "e": 17189, "s": 17171, "text": "Vector in C++ STL" }, { "code": null, "e": 17232, "s": 17189, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 17278, "s": 17232, "text": "Initialize a vector in C++ (7 different ways)" }, { "code": null, "e": 17321, "s": 17278, "text": "Set in C++ Standard Template Library (STL)" } ]
Creating a Simple Chat with netcat in Linux
02 Feb, 2021 Firstly, We should know that what is netcat, which is also known as TCP/IP swiss army knife a feature-rich network utility. netcat can do port scanning, transfer files, create a listener, or stream media, and many more. The netcat utility program supports a wide range of commands to manage networks and monitor the flow of traffic data between systems. Install netcat in Linux: sudo apt-get install netcat Compile Netcat From Source: 1. Download Netcat from an official source 2. To decompress it run the following command, gunzip netcat-0.7.1.tar.gz Here, “netcat-0.7.1.tar.gz” is the name of the file. 3. untar the file. tar -xf netcat-0.7.1.tar 4. Change the directory. cd netcat-0.7.1 / 5. by using the command configure the source code. ./configure 6. Compile the program by using. make 7. Now install it. make install We will follow these steps for configuring a chat. Steps 1: To create a simple chat you need two devices, d1 and d2. Step 2: Open a terminal in Linux and install Netcat on both devices. Step 3: type $ifconfig in d1 and note down your localhost IP address, ifconfig is used to get our device’s IP address. Step 4: Now in d1 run command $nc -nvlp 1234 where “1234” is port number, d1 will now act as a listener. Where: -n: nodns, Do not resolve hostname vis DNS -v: verbose, set verbosity level -l: listener, binds and listen for incoming connection -p: source-port port, Specify source port to use Step 5: in d2 type $nc <localhost IP> 1234 and hit enter. Step 6: Simple chat is now created. Picked Technical Scripter 2020 Linux-Unix Technical Scripter 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 Introduction to Linux Operating System Array Basics in Shell Scripting | Set 1 nohup Command in Linux with Examples chmod command in Linux with examples mv command in Linux with examples Basic Operators in Shell Scripting
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Feb, 2021" }, { "code": null, "e": 382, "s": 28, "text": "Firstly, We should know that what is netcat, which is also known as TCP/IP swiss army knife a feature-rich network utility. netcat can do port scanning, transfer files, create a listener, or stream media, and many more. The netcat utility program supports a wide range of commands to manage networks and monitor the flow of traffic data between systems." }, { "code": null, "e": 407, "s": 382, "text": "Install netcat in Linux:" }, { "code": null, "e": 435, "s": 407, "text": "sudo apt-get install netcat" }, { "code": null, "e": 463, "s": 435, "text": "Compile Netcat From Source:" }, { "code": null, "e": 506, "s": 463, "text": "1. Download Netcat from an official source" }, { "code": null, "e": 553, "s": 506, "text": "2. To decompress it run the following command," }, { "code": null, "e": 580, "s": 553, "text": "gunzip netcat-0.7.1.tar.gz" }, { "code": null, "e": 633, "s": 580, "text": "Here, “netcat-0.7.1.tar.gz” is the name of the file." }, { "code": null, "e": 652, "s": 633, "text": "3. untar the file." }, { "code": null, "e": 677, "s": 652, "text": "tar -xf netcat-0.7.1.tar" }, { "code": null, "e": 702, "s": 677, "text": "4. Change the directory." }, { "code": null, "e": 721, "s": 702, "text": "cd netcat-0.7.1 / " }, { "code": null, "e": 772, "s": 721, "text": "5. by using the command configure the source code." }, { "code": null, "e": 784, "s": 772, "text": "./configure" }, { "code": null, "e": 817, "s": 784, "text": "6. Compile the program by using." }, { "code": null, "e": 822, "s": 817, "text": "make" }, { "code": null, "e": 841, "s": 822, "text": "7. Now install it." }, { "code": null, "e": 854, "s": 841, "text": "make install" }, { "code": null, "e": 905, "s": 854, "text": "We will follow these steps for configuring a chat." }, { "code": null, "e": 971, "s": 905, "text": "Steps 1: To create a simple chat you need two devices, d1 and d2." }, { "code": null, "e": 1040, "s": 971, "text": "Step 2: Open a terminal in Linux and install Netcat on both devices." }, { "code": null, "e": 1159, "s": 1040, "text": "Step 3: type $ifconfig in d1 and note down your localhost IP address, ifconfig is used to get our device’s IP address." }, { "code": null, "e": 1264, "s": 1159, "text": "Step 4: Now in d1 run command $nc -nvlp 1234 where “1234” is port number, d1 will now act as a listener." }, { "code": null, "e": 1271, "s": 1264, "text": "Where:" }, { "code": null, "e": 1314, "s": 1271, "text": "-n: nodns, Do not resolve hostname vis DNS" }, { "code": null, "e": 1347, "s": 1314, "text": "-v: verbose, set verbosity level" }, { "code": null, "e": 1402, "s": 1347, "text": "-l: listener, binds and listen for incoming connection" }, { "code": null, "e": 1451, "s": 1402, "text": "-p: source-port port, Specify source port to use" }, { "code": null, "e": 1509, "s": 1451, "text": "Step 5: in d2 type $nc <localhost IP> 1234 and hit enter." }, { "code": null, "e": 1545, "s": 1509, "text": "Step 6: Simple chat is now created." }, { "code": null, "e": 1552, "s": 1545, "text": "Picked" }, { "code": null, "e": 1576, "s": 1552, "text": "Technical Scripter 2020" }, { "code": null, "e": 1587, "s": 1576, "text": "Linux-Unix" }, { "code": null, "e": 1606, "s": 1587, "text": "Technical Scripter" }, { "code": null, "e": 1704, "s": 1606, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1730, "s": 1704, "text": "Docker - COPY Instruction" }, { "code": null, "e": 1765, "s": 1730, "text": "scp command in Linux with Examples" }, { "code": null, "e": 1802, "s": 1765, "text": "chown command in Linux with Examples" }, { "code": null, "e": 1831, "s": 1802, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 1870, "s": 1831, "text": "Introduction to Linux Operating System" }, { "code": null, "e": 1910, "s": 1870, "text": "Array Basics in Shell Scripting | Set 1" }, { "code": null, "e": 1947, "s": 1910, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 1984, "s": 1947, "text": "chmod command in Linux with examples" }, { "code": null, "e": 2018, "s": 1984, "text": "mv command in Linux with examples" } ]
Excel VBA | Average() Functions
03 Jul, 2018 VBA (Visual Basic for Applications) is the programming language of Excel and other offices. It is an event-driven programming language from Microsoft. With Excel VBA, one can automate many tasks in excel and all other office softwares. It helps in generating reports, preparing various charts, graphs and moreover, it performs calculation using its various functions.Let’s see Average functions in Excel. AVERAGE It returns the arithmetic mean of all of its arguments.Syntax:=AVERAGE(number1, number2, ...)Here,number 1: This is the first number in your cell. You can specify it upto 255 numbers.number 2: This is an Optional field. You can specify it upto 255 numbers.Example:Output: AVERAGEIF: It calculates the average of only those values which meet a certain criteria.Syntax:=AVERAGEIF(range, criteria, average_range)range: It is the range of cells to be evaluated. The cells in range can be numbers, names, arrays or any other reference that contains numbers. Blank and text values are not considered.criteria: It should be in the form of a number or any expression which defines which all cells to be averaged. For instance, “mango”, C6, “<35”average_range: [Optional] If this is not mentioned, Excel will get average of only those cells on which criteria is applied, which are specified in the range argument.Notes:-> If a cell in average_range is an empty cell, it will be ignored.-> If range is a text value or blank, it will return an error.-> If a cell in criteria is empty, it will be considered as 0 value.-> If no cell meets the criteria, it will return an error.Example:Output: AVERAGEIFS: Calculate average of cells that meet multiple criteria.Syntax:=AVERAGEIFS(average_range, criteria_range1, criteria1, [criteria_range2, criteria2], ...)average_range: (Required) One or more cells to calculate average.criteria_range1: (Required) 1 to 127 ranges to evaluate the given criteria.criteria1: 1 to 127 criteria in the form of numbers, expression to be averaged. This defines which all cells in criteria_range1 are to be averaged. For instance, criteria can be like this, “>32”, “apple”, “D7”Example:Output: AVERAGE It returns the arithmetic mean of all of its arguments.Syntax:=AVERAGE(number1, number2, ...)Here,number 1: This is the first number in your cell. You can specify it upto 255 numbers.number 2: This is an Optional field. You can specify it upto 255 numbers.Example:Output: =AVERAGE(number1, number2, ...) Here,number 1: This is the first number in your cell. You can specify it upto 255 numbers.number 2: This is an Optional field. You can specify it upto 255 numbers. Example: Output: AVERAGEIF: It calculates the average of only those values which meet a certain criteria.Syntax:=AVERAGEIF(range, criteria, average_range)range: It is the range of cells to be evaluated. The cells in range can be numbers, names, arrays or any other reference that contains numbers. Blank and text values are not considered.criteria: It should be in the form of a number or any expression which defines which all cells to be averaged. For instance, “mango”, C6, “<35”average_range: [Optional] If this is not mentioned, Excel will get average of only those cells on which criteria is applied, which are specified in the range argument.Notes:-> If a cell in average_range is an empty cell, it will be ignored.-> If range is a text value or blank, it will return an error.-> If a cell in criteria is empty, it will be considered as 0 value.-> If no cell meets the criteria, it will return an error.Example:Output: Syntax: =AVERAGEIF(range, criteria, average_range) range: It is the range of cells to be evaluated. The cells in range can be numbers, names, arrays or any other reference that contains numbers. Blank and text values are not considered. criteria: It should be in the form of a number or any expression which defines which all cells to be averaged. For instance, “mango”, C6, “<35” average_range: [Optional] If this is not mentioned, Excel will get average of only those cells on which criteria is applied, which are specified in the range argument. Notes:-> If a cell in average_range is an empty cell, it will be ignored.-> If range is a text value or blank, it will return an error.-> If a cell in criteria is empty, it will be considered as 0 value.-> If no cell meets the criteria, it will return an error. Example: Output: AVERAGEIFS: Calculate average of cells that meet multiple criteria.Syntax:=AVERAGEIFS(average_range, criteria_range1, criteria1, [criteria_range2, criteria2], ...)average_range: (Required) One or more cells to calculate average.criteria_range1: (Required) 1 to 127 ranges to evaluate the given criteria.criteria1: 1 to 127 criteria in the form of numbers, expression to be averaged. This defines which all cells in criteria_range1 are to be averaged. For instance, criteria can be like this, “>32”, “apple”, “D7”Example:Output: =AVERAGEIFS(average_range, criteria_range1, criteria1, [criteria_range2, criteria2], ...) average_range: (Required) One or more cells to calculate average. criteria_range1: (Required) 1 to 127 ranges to evaluate the given criteria. criteria1: 1 to 127 criteria in the form of numbers, expression to be averaged. This defines which all cells in criteria_range1 are to be averaged. For instance, criteria can be like this, “>32”, “apple”, “D7” Example: Output: GBlog Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You! Geek Streak - 24 Days POTD Challenge What is Hashing | A Complete Tutorial GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge? GeeksforGeeks Job-A-Thon Exclusive - Hiring Challenge For Amazon Alexa How to Learn Data Science in 10 weeks? Types of Software Testing Roadmap to Learn JavaScript For Beginners What is Data Structure: Types, Classifications and Applications
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Jul, 2018" }, { "code": null, "e": 179, "s": 28, "text": "VBA (Visual Basic for Applications) is the programming language of Excel and other offices. It is an event-driven programming language from Microsoft." }, { "code": null, "e": 433, "s": 179, "text": "With Excel VBA, one can automate many tasks in excel and all other office softwares. It helps in generating reports, preparing various charts, graphs and moreover, it performs calculation using its various functions.Let’s see Average functions in Excel." }, { "code": null, "e": 2150, "s": 433, "text": "AVERAGE It returns the arithmetic mean of all of its arguments.Syntax:=AVERAGE(number1, number2, ...)Here,number 1: This is the first number in your cell. You can specify it upto 255 numbers.number 2: This is an Optional field. You can specify it upto 255 numbers.Example:Output: AVERAGEIF: It calculates the average of only those values which meet a certain criteria.Syntax:=AVERAGEIF(range, criteria, average_range)range: It is the range of cells to be evaluated. The cells in range can be numbers, names, arrays or any other reference that contains numbers. Blank and text values are not considered.criteria: It should be in the form of a number or any expression which defines which all cells to be averaged. For instance, “mango”, C6, “<35”average_range: [Optional] If this is not mentioned, Excel will get average of only those cells on which criteria is applied, which are specified in the range argument.Notes:-> If a cell in average_range is an empty cell, it will be ignored.-> If range is a text value or blank, it will return an error.-> If a cell in criteria is empty, it will be considered as 0 value.-> If no cell meets the criteria, it will return an error.Example:Output: AVERAGEIFS: Calculate average of cells that meet multiple criteria.Syntax:=AVERAGEIFS(average_range, criteria_range1, criteria1, [criteria_range2, criteria2], ...)average_range: (Required) One or more cells to calculate average.criteria_range1: (Required) 1 to 127 ranges to evaluate the given criteria.criteria1: 1 to 127 criteria in the form of numbers, expression to be averaged. This defines which all cells in criteria_range1 are to be averaged. For instance, criteria can be like this, “>32”, “apple”, “D7”Example:Output:" }, { "code": null, "e": 2430, "s": 2150, "text": "AVERAGE It returns the arithmetic mean of all of its arguments.Syntax:=AVERAGE(number1, number2, ...)Here,number 1: This is the first number in your cell. You can specify it upto 255 numbers.number 2: This is an Optional field. You can specify it upto 255 numbers.Example:Output:" }, { "code": null, "e": 2462, "s": 2430, "text": "=AVERAGE(number1, number2, ...)" }, { "code": null, "e": 2626, "s": 2462, "text": "Here,number 1: This is the first number in your cell. You can specify it upto 255 numbers.number 2: This is an Optional field. You can specify it upto 255 numbers." }, { "code": null, "e": 2635, "s": 2626, "text": "Example:" }, { "code": null, "e": 2643, "s": 2635, "text": "Output:" }, { "code": null, "e": 3554, "s": 2645, "text": "AVERAGEIF: It calculates the average of only those values which meet a certain criteria.Syntax:=AVERAGEIF(range, criteria, average_range)range: It is the range of cells to be evaluated. The cells in range can be numbers, names, arrays or any other reference that contains numbers. Blank and text values are not considered.criteria: It should be in the form of a number or any expression which defines which all cells to be averaged. For instance, “mango”, C6, “<35”average_range: [Optional] If this is not mentioned, Excel will get average of only those cells on which criteria is applied, which are specified in the range argument.Notes:-> If a cell in average_range is an empty cell, it will be ignored.-> If range is a text value or blank, it will return an error.-> If a cell in criteria is empty, it will be considered as 0 value.-> If no cell meets the criteria, it will return an error.Example:Output:" }, { "code": null, "e": 3562, "s": 3554, "text": "Syntax:" }, { "code": null, "e": 3605, "s": 3562, "text": "=AVERAGEIF(range, criteria, average_range)" }, { "code": null, "e": 3791, "s": 3605, "text": "range: It is the range of cells to be evaluated. The cells in range can be numbers, names, arrays or any other reference that contains numbers. Blank and text values are not considered." }, { "code": null, "e": 3935, "s": 3791, "text": "criteria: It should be in the form of a number or any expression which defines which all cells to be averaged. For instance, “mango”, C6, “<35”" }, { "code": null, "e": 4103, "s": 3935, "text": "average_range: [Optional] If this is not mentioned, Excel will get average of only those cells on which criteria is applied, which are specified in the range argument." }, { "code": null, "e": 4365, "s": 4103, "text": "Notes:-> If a cell in average_range is an empty cell, it will be ignored.-> If range is a text value or blank, it will return an error.-> If a cell in criteria is empty, it will be considered as 0 value.-> If no cell meets the criteria, it will return an error." }, { "code": null, "e": 4374, "s": 4365, "text": "Example:" }, { "code": null, "e": 4382, "s": 4374, "text": "Output:" }, { "code": null, "e": 4912, "s": 4384, "text": "AVERAGEIFS: Calculate average of cells that meet multiple criteria.Syntax:=AVERAGEIFS(average_range, criteria_range1, criteria1, [criteria_range2, criteria2], ...)average_range: (Required) One or more cells to calculate average.criteria_range1: (Required) 1 to 127 ranges to evaluate the given criteria.criteria1: 1 to 127 criteria in the form of numbers, expression to be averaged. This defines which all cells in criteria_range1 are to be averaged. For instance, criteria can be like this, “>32”, “apple”, “D7”Example:Output:" }, { "code": null, "e": 5002, "s": 4912, "text": "=AVERAGEIFS(average_range, criteria_range1, criteria1, [criteria_range2, criteria2], ...)" }, { "code": null, "e": 5068, "s": 5002, "text": "average_range: (Required) One or more cells to calculate average." }, { "code": null, "e": 5144, "s": 5068, "text": "criteria_range1: (Required) 1 to 127 ranges to evaluate the given criteria." }, { "code": null, "e": 5354, "s": 5144, "text": "criteria1: 1 to 127 criteria in the form of numbers, expression to be averaged. This defines which all cells in criteria_range1 are to be averaged. For instance, criteria can be like this, “>32”, “apple”, “D7”" }, { "code": null, "e": 5363, "s": 5354, "text": "Example:" }, { "code": null, "e": 5371, "s": 5363, "text": "Output:" }, { "code": null, "e": 5377, "s": 5371, "text": "GBlog" }, { "code": null, "e": 5475, "s": 5377, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5500, "s": 5475, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 5555, "s": 5500, "text": "GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!" }, { "code": null, "e": 5592, "s": 5555, "text": "Geek Streak - 24 Days POTD Challenge" }, { "code": null, "e": 5630, "s": 5592, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 5696, "s": 5630, "text": "GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?" }, { "code": null, "e": 5767, "s": 5696, "text": "GeeksforGeeks Job-A-Thon Exclusive - Hiring Challenge For Amazon Alexa" }, { "code": null, "e": 5806, "s": 5767, "text": "How to Learn Data Science in 10 weeks?" }, { "code": null, "e": 5832, "s": 5806, "text": "Types of Software Testing" }, { "code": null, "e": 5874, "s": 5832, "text": "Roadmap to Learn JavaScript For Beginners" } ]
Unix Socket - Structures
Various structures are used in Unix Socket Programming to hold information about the address and port, and other information. Most socket functions require a pointer to a socket address structure as an argument. Structures defined in this chapter are related to Internet Protocol Family. The first structure is sockaddr that holds the socket information − struct sockaddr { unsigned short sa_family; char sa_data[14]; }; This is a generic socket address structure, which will be passed in most of the socket function calls. The following table provides a description of the member fields − AF_INET AF_UNIX AF_NS AF_IMPLINK The second structure that helps you to reference to the socket's elements is as follows − struct sockaddr_in { short int sin_family; unsigned short int sin_port; struct in_addr sin_addr; unsigned char sin_zero[8]; }; Here is the description of the member fields − AF_INET AF_UNIX AF_NS AF_IMPLINK This structure is used only in the above structure as a structure field and holds 32 bit netid/hostid. struct in_addr { unsigned long s_addr; }; Here is the description of the member fields − This structure is used to keep information related to host. struct hostent { char *h_name; char **h_aliases; int h_addrtype; int h_length; char **h_addr_list #define h_addr h_addr_list[0] }; Here is the description of the member fields − NOTE − h_addr is defined as h_addr_list[0] to keep backward compatibility. This particular structure is used to keep information related to service and associated ports. struct servent { char *s_name; char **s_aliases; int s_port; char *s_proto; }; Here is the description of the member fields − TCP UDP Socket address structures are an integral part of every network program. We allocate them, fill them in, and pass pointers to them to various socket functions. Sometimes we pass a pointer to one of these structures to a socket function and it fills in the contents. We always pass these structures by reference (i.e., we pass a pointer to the structure, not the structure itself), and we always pass the size of the structure as another argument. When a socket function fills in a structure, the length is also passed by reference, so that its value can be updated by the function. We call these value-result arguments. Always, set the structure variables to NULL (i.e., '\0') by using memset() for bzero() functions, otherwise it may get unexpected junk values in your structure.
[ { "code": null, "e": 2425, "s": 2137, "text": "Various structures are used in Unix Socket Programming to hold information about the address and port, and other information. Most socket functions require a pointer to a socket address structure as an argument. Structures defined in this chapter are related to Internet Protocol Family." }, { "code": null, "e": 2493, "s": 2425, "text": "The first structure is sockaddr that holds the socket information −" }, { "code": null, "e": 2578, "s": 2493, "text": "struct sockaddr {\n unsigned short sa_family;\n char sa_data[14];\n};" }, { "code": null, "e": 2747, "s": 2578, "text": "This is a generic socket address structure, which will be passed in most of the socket function calls. The following table provides a description of the member fields −" }, { "code": null, "e": 2755, "s": 2747, "text": "AF_INET" }, { "code": null, "e": 2763, "s": 2755, "text": "AF_UNIX" }, { "code": null, "e": 2769, "s": 2763, "text": "AF_NS" }, { "code": null, "e": 2780, "s": 2769, "text": "AF_IMPLINK" }, { "code": null, "e": 2870, "s": 2780, "text": "The second structure that helps you to reference to the socket's elements is as follows −" }, { "code": null, "e": 3035, "s": 2870, "text": "struct sockaddr_in {\n short int sin_family;\n unsigned short int sin_port;\n struct in_addr sin_addr;\n unsigned char sin_zero[8];\n};" }, { "code": null, "e": 3082, "s": 3035, "text": "Here is the description of the member fields −" }, { "code": null, "e": 3090, "s": 3082, "text": "AF_INET" }, { "code": null, "e": 3098, "s": 3090, "text": "AF_UNIX" }, { "code": null, "e": 3104, "s": 3098, "text": "AF_NS" }, { "code": null, "e": 3115, "s": 3104, "text": "AF_IMPLINK" }, { "code": null, "e": 3218, "s": 3115, "text": "This structure is used only in the above structure as a structure field and holds 32 bit netid/hostid." }, { "code": null, "e": 3263, "s": 3218, "text": "struct in_addr {\n unsigned long s_addr;\n};" }, { "code": null, "e": 3310, "s": 3263, "text": "Here is the description of the member fields −" }, { "code": null, "e": 3370, "s": 3310, "text": "This structure is used to keep information related to host." }, { "code": null, "e": 3527, "s": 3370, "text": "struct hostent {\n char *h_name; \n char **h_aliases; \n int h_addrtype; \n int h_length; \n char **h_addr_list\n\t\n#define h_addr h_addr_list[0]\n};" }, { "code": null, "e": 3574, "s": 3527, "text": "Here is the description of the member fields −" }, { "code": null, "e": 3649, "s": 3574, "text": "NOTE − h_addr is defined as h_addr_list[0] to keep backward compatibility." }, { "code": null, "e": 3744, "s": 3649, "text": "This particular structure is used to keep information related to service and associated ports." }, { "code": null, "e": 3844, "s": 3744, "text": "struct servent {\n char *s_name; \n char **s_aliases; \n int s_port; \n char *s_proto;\n};" }, { "code": null, "e": 3891, "s": 3844, "text": "Here is the description of the member fields −" }, { "code": null, "e": 3895, "s": 3891, "text": "TCP" }, { "code": null, "e": 3899, "s": 3895, "text": "UDP" }, { "code": null, "e": 4165, "s": 3899, "text": "Socket address structures are an integral part of every network program. We allocate them, fill them in, and pass pointers to them to various socket functions. Sometimes we pass a pointer to one of these structures to a socket function and it fills in the contents." }, { "code": null, "e": 4346, "s": 4165, "text": "We always pass these structures by reference (i.e., we pass a pointer to the structure, not the structure itself), and we always pass the size of the structure as another argument." }, { "code": null, "e": 4519, "s": 4346, "text": "When a socket function fills in a structure, the length is also passed by reference, so that its value can be updated by the function. We call these value-result arguments." } ]
PHP | strrev() Function
11 Aug, 2021 Reversing a string is one of the most basic string operations and is used very frequently by developers and programmers. PHP comes with a built-in function to reverse strings. The strrev() function is a built-in function in PHP and is used to reverse a string. This function does not make any change in the original string passed to it as a parameter. Syntax: string strrev($inpString) Parameter: This function accepts a single parameter $inpString. This parameter is a string and it specifies the string which we want to reverse. If a number is passed to it instead of a string, it will also reverse that number. Return Value: The strrev() function returns the reversed string or the number. It does not make any change to the original string or number passed in the parameter. Examples: Input : $string = "geeks" Output : skeeg Input : $string = 143 Output : 341 Below programs illustrate the strrev() function in PHP: Program 1: PHP program to demonstrate the strrev() function when a string is passed. PHP <?php// PHP program to demonstrate the// strrev() function when a string is passed $str = "geeks"; // prints the reversed stringecho strrev($str);?> Output: skeeg Program 2: PHP program to demonstrate the strrev() function when a number is passed. PHP <?php// PHP program to demonstrate the// strrev() function when a number is passed // passing number instead of string$num = 134; // prints the reversed numberecho strrev($num);?> Output: 431 Reference: http://php.net/manual/en/function.strrev.php sumitgumber28 PHP-string 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": "\n11 Aug, 2021" }, { "code": null, "e": 204, "s": 28, "text": "Reversing a string is one of the most basic string operations and is used very frequently by developers and programmers. PHP comes with a built-in function to reverse strings." }, { "code": null, "e": 381, "s": 204, "text": "The strrev() function is a built-in function in PHP and is used to reverse a string. This function does not make any change in the original string passed to it as a parameter. " }, { "code": null, "e": 390, "s": 381, "text": "Syntax: " }, { "code": null, "e": 416, "s": 390, "text": "string strrev($inpString)" }, { "code": null, "e": 645, "s": 416, "text": "Parameter: This function accepts a single parameter $inpString. This parameter is a string and it specifies the string which we want to reverse. If a number is passed to it instead of a string, it will also reverse that number. " }, { "code": null, "e": 811, "s": 645, "text": "Return Value: The strrev() function returns the reversed string or the number. It does not make any change to the original string or number passed in the parameter. " }, { "code": null, "e": 823, "s": 811, "text": "Examples: " }, { "code": null, "e": 904, "s": 823, "text": "Input : $string = \"geeks\" \nOutput : skeeg \n\nInput : $string = 143 \nOutput : 341 " }, { "code": null, "e": 960, "s": 904, "text": "Below programs illustrate the strrev() function in PHP:" }, { "code": null, "e": 1047, "s": 960, "text": "Program 1: PHP program to demonstrate the strrev() function when a string is passed. " }, { "code": null, "e": 1051, "s": 1047, "text": "PHP" }, { "code": "<?php// PHP program to demonstrate the// strrev() function when a string is passed $str = \"geeks\"; // prints the reversed stringecho strrev($str);?>", "e": 1200, "s": 1051, "text": null }, { "code": null, "e": 1209, "s": 1200, "text": "Output: " }, { "code": null, "e": 1215, "s": 1209, "text": "skeeg" }, { "code": null, "e": 1302, "s": 1215, "text": "Program 2: PHP program to demonstrate the strrev() function when a number is passed. " }, { "code": null, "e": 1306, "s": 1302, "text": "PHP" }, { "code": "<?php// PHP program to demonstrate the// strrev() function when a number is passed // passing number instead of string$num = 134; // prints the reversed numberecho strrev($num);?>", "e": 1486, "s": 1306, "text": null }, { "code": null, "e": 1495, "s": 1486, "text": "Output: " }, { "code": null, "e": 1499, "s": 1495, "text": "431" }, { "code": null, "e": 1556, "s": 1499, "text": "Reference: http://php.net/manual/en/function.strrev.php " }, { "code": null, "e": 1570, "s": 1556, "text": "sumitgumber28" }, { "code": null, "e": 1581, "s": 1570, "text": "PHP-string" }, { "code": null, "e": 1585, "s": 1581, "text": "PHP" }, { "code": null, "e": 1602, "s": 1585, "text": "Web Technologies" }, { "code": null, "e": 1606, "s": 1602, "text": "PHP" } ]
Draw Boxplot with Mean in R
29 Jun, 2021 In this article, we will discuss how to draw a boxplot with the mean in the R programming language. In this approach for drawing the boxplot with a mean value of the data on it, the user needs to call the boxplot() function with the required parameters for drawing the simple boxplot of the given data, and with this user needs to call the points() function to point out the mean value of every boxplot plotted and further with the help of the text() function with the required parameters it will be possible to get the mean value on the plot of the boxplot in the R programming language. Points(): This is a generic function to draw a sequence of points at the specified coordinates. Syntax: points(x, y = NULL, type = “p”, ...) Text function helps to draw the strings given in the vector labels at the coordinates given by x and y. Syntax: text (x, y = NULL, labels = seq_along(x$x), adj = NULL, pos = NULL, offset = 0.5, vfont = NULL, cex = 1, col = NULL, font = NULL, ...) Example: R gfg=data.frame(A=c(1,5,1,5,6,6,4,1,1,5,4,1,8,1,1), B=c(1,8,6,6,6,4,5,7,8,1,7,4,4,1,6), C=c(9,5,1,5,4,1,8,6,4,8,4,4,5,7,6)) gfg_mean=colMeans(gfg) boxplot(gfg) points(x = 1:ncol(gfg),y = gfg_mean, col = "green") text(x = 1:ncol(gfg),y =gfg_mean - 0.20, labels = paste("Mean:", round(gfg_mean, 1)), col = "green") Output: In this approach to drawing the boxplot with the mean, the user first needs to import and install the ggplot2 package to the R console as in this approach the used function is from the ggplot2 package, then the user needs to call the geom_boxplot() function with the required parameters which will lead to the normal plotting of the boxplot of the data provided and then further the user needs to call the stat_summary() which will find the mean of every boxplot and label it on the plot in the R programming language. geom_boxplot() function is used to plot the Box and whiskers plot. Syntax: geom_boxplot( mapping = NULL, data = NULL, stat = “boxplot”, position = “dodge2”, ..., outlier.colour = NULL, outlier.color = NULL,outlier.fill = NULL, outlier.shape = 19, outlier.size = 1.5, outlier.stroke = 0.5, outlier.alpha = NULL, notch = FALSE,notchwidth = 0.5, varwidth = FALSE, na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE) stat_summary() function allows for tremendous flexibility in the specification of summary functions Syntax: stat_summary(mapping = NULL, data = NULL, geom = “pointrange”, position = “identity”, ...) Example: R library(ggplot2) gfg=data.frame(values=c(1,8,6,6,6,4,5,7,8,1,7,4,4,1,6), group =LETTERS[1:3]) ggplot(gfg, aes(x = group, y = values)) + geom_boxplot() + stat_summary(fun = mean, geom = "point", col = "green") + stat_summary(fun = mean, geom = "text", col = "green", vjust = 1.5, aes(label = paste("Mean:", round(..y.., digits = 1)))) Output: Picked R-Charts R-Graphs R-plots 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? R - if statement Logistic Regression in R Programming How to filter R DataFrame by values in a column? 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": "\n29 Jun, 2021" }, { "code": null, "e": 128, "s": 28, "text": "In this article, we will discuss how to draw a boxplot with the mean in the R programming language." }, { "code": null, "e": 617, "s": 128, "text": "In this approach for drawing the boxplot with a mean value of the data on it, the user needs to call the boxplot() function with the required parameters for drawing the simple boxplot of the given data, and with this user needs to call the points() function to point out the mean value of every boxplot plotted and further with the help of the text() function with the required parameters it will be possible to get the mean value on the plot of the boxplot in the R programming language." }, { "code": null, "e": 713, "s": 617, "text": "Points(): This is a generic function to draw a sequence of points at the specified coordinates." }, { "code": null, "e": 721, "s": 713, "text": "Syntax:" }, { "code": null, "e": 758, "s": 721, "text": "points(x, y = NULL, type = “p”, ...)" }, { "code": null, "e": 862, "s": 758, "text": "Text function helps to draw the strings given in the vector labels at the coordinates given by x and y." }, { "code": null, "e": 870, "s": 862, "text": "Syntax:" }, { "code": null, "e": 1005, "s": 870, "text": "text (x, y = NULL, labels = seq_along(x$x), adj = NULL, pos = NULL, offset = 0.5, vfont = NULL, cex = 1, col = NULL, font = NULL, ...)" }, { "code": null, "e": 1014, "s": 1005, "text": "Example:" }, { "code": null, "e": 1016, "s": 1014, "text": "R" }, { "code": "gfg=data.frame(A=c(1,5,1,5,6,6,4,1,1,5,4,1,8,1,1), B=c(1,8,6,6,6,4,5,7,8,1,7,4,4,1,6), C=c(9,5,1,5,4,1,8,6,4,8,4,4,5,7,6)) gfg_mean=colMeans(gfg) boxplot(gfg) points(x = 1:ncol(gfg),y = gfg_mean, col = \"green\") text(x = 1:ncol(gfg),y =gfg_mean - 0.20, labels = paste(\"Mean:\", round(gfg_mean, 1)), col = \"green\")", "e": 1365, "s": 1016, "text": null }, { "code": null, "e": 1373, "s": 1365, "text": "Output:" }, { "code": null, "e": 1892, "s": 1373, "text": "In this approach to drawing the boxplot with the mean, the user first needs to import and install the ggplot2 package to the R console as in this approach the used function is from the ggplot2 package, then the user needs to call the geom_boxplot() function with the required parameters which will lead to the normal plotting of the boxplot of the data provided and then further the user needs to call the stat_summary() which will find the mean of every boxplot and label it on the plot in the R programming language." }, { "code": null, "e": 1959, "s": 1892, "text": "geom_boxplot() function is used to plot the Box and whiskers plot." }, { "code": null, "e": 1967, "s": 1959, "text": "Syntax:" }, { "code": null, "e": 2324, "s": 1967, "text": "geom_boxplot( mapping = NULL, data = NULL, stat = “boxplot”, position = “dodge2”, ..., outlier.colour = NULL, outlier.color = NULL,outlier.fill = NULL, outlier.shape = 19, outlier.size = 1.5, outlier.stroke = 0.5, outlier.alpha = NULL, notch = FALSE,notchwidth = 0.5, varwidth = FALSE, na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE)" }, { "code": null, "e": 2424, "s": 2324, "text": "stat_summary() function allows for tremendous flexibility in the specification of summary functions" }, { "code": null, "e": 2432, "s": 2424, "text": "Syntax:" }, { "code": null, "e": 2523, "s": 2432, "text": "stat_summary(mapping = NULL, data = NULL, geom = “pointrange”, position = “identity”, ...)" }, { "code": null, "e": 2532, "s": 2523, "text": "Example:" }, { "code": null, "e": 2534, "s": 2532, "text": "R" }, { "code": "library(ggplot2) gfg=data.frame(values=c(1,8,6,6,6,4,5,7,8,1,7,4,4,1,6), group =LETTERS[1:3]) ggplot(gfg, aes(x = group, y = values)) + geom_boxplot() + stat_summary(fun = mean, geom = \"point\", col = \"green\") + stat_summary(fun = mean, geom = \"text\", col = \"green\", vjust = 1.5, aes(label = paste(\"Mean:\", round(..y.., digits = 1))))", "e": 2889, "s": 2534, "text": null }, { "code": null, "e": 2897, "s": 2889, "text": "Output:" }, { "code": null, "e": 2904, "s": 2897, "text": "Picked" }, { "code": null, "e": 2913, "s": 2904, "text": "R-Charts" }, { "code": null, "e": 2922, "s": 2913, "text": "R-Graphs" }, { "code": null, "e": 2930, "s": 2922, "text": "R-plots" }, { "code": null, "e": 2941, "s": 2930, "text": "R Language" }, { "code": null, "e": 3039, "s": 2941, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3091, "s": 3039, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 3149, "s": 3091, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 3184, "s": 3149, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 3222, "s": 3184, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 3239, "s": 3222, "text": "R - if statement" }, { "code": null, "e": 3276, "s": 3239, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 3325, "s": 3276, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 3368, "s": 3325, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 3405, "s": 3368, "text": "How to import an Excel File into R ?" } ]
Python Program for Cutting a Rod | DP-13
17 Jan, 2022 Given a rod of length n inches and an array of prices that contains prices of all pieces of size smaller than n. Determine the maximum value obtainable by cutting up the rod and selling the pieces. For example, if length of the rod is 8 and the values of different pieces are given as following, then the maximum obtainable value is 22 (by cutting in two pieces of lengths 2 and 6) length | 1 2 3 4 5 6 7 8 -------------------------------------------- price | 1 5 8 9 10 17 17 20 And if the prices are as following, then the maximum obtainable value is 24 (by cutting in eight pieces of length 1) length | 1 2 3 4 5 6 7 8 -------------------------------------------- price | 3 5 8 9 10 17 17 20 Following is simple recursive implementation of the Rod Cutting problem. The implementation simply follows the recursive structure mentioned above. Python3 # A Naive recursive solution# for Rod cutting problemimport sys # A utility function to get the# maximum of two integersdef max(a, b): return a if (a > b) else b # Returns the best obtainable price for a rod of length n# and price[] as prices of different piecesdef cutRod(price, n): if(n <= 0): return 0 max_val = -sys.maxsize-1 # Recursively cut the rod in different pieces # and compare different configurations for i in range(0, n): max_val = max(max_val, price[i] + cutRod(price, n - i - 1)) return max_val # Driver codearr = [1, 5, 8, 9, 10, 17, 17, 20]size = len(arr)print("Maximum Obtainable Value is", cutRod(arr, size)) # This code is contributed by 'Smitha Dinesh Semwal' Maximum Obtainable Value is 22 Considering the above implementation, following is recursion tree for a Rod of length 4. cR() ---> cutRod() cR(4) / / / / cR(3) cR(2) cR(1) cR(0) / | / | / | / | cR(2) cR(1) cR(0) cR(1) cR(0) cR(0) / | | / | | cR(1) cR(0) cR(0) cR(0) / / CR(0) In the above partial recursion tree, cR(2) is being solved twice. We can see that there are many subproblems which are solved again and again. Since same subproblems are called again, this problem has Overlapping Subproblems property. So the Rod Cutting problem has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, recomputations of same subproblems can be avoided by constructing a temporary array val[] in bottom up manner. Python3 # A Dynamic Programming solution for Rod cutting problemINT_MIN = -32767 # Returns the best obtainable price for a rod of length n and# price[] as prices of different piecesdef cutRod(price, n): val = [0 for x in range(n + 1)] val[0] = 0 # Build the table val[] in bottom up manner and return # the last entry from the table for i in range(1, n + 1): max_val = INT_MIN for j in range(i): max_val = max(max_val, price[j] + val[i-j-1]) val[i] = max_val return val[n] # Driver program to test above functionsarr = [1, 5, 8, 9, 10, 17, 17, 20]size = len(arr)print("Maximum Obtainable Value is " + str(cutRod(arr, size))) # This code is contributed by Bhavya Jain Maximum Obtainable Value is 22 Please refer complete article on Cutting a Rod | DP-13 for more details! anikakapoor amartyaghoshgfg Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Program to check Armstrong Number Python program to interchange first and last elements in a list Differences and Applications of List, Tuple, Set and Dictionary in Python Appending to list in Python dictionary Python Program for simple interest Python Program for Merge Sort Python Program for n-th Fibonacci number Python | Find most frequent element in a list Python | Remove spaces from a string Python Program to find largest element in an array
[ { "code": null, "e": 54, "s": 26, "text": "\n17 Jan, 2022" }, { "code": null, "e": 437, "s": 54, "text": "Given a rod of length n inches and an array of prices that contains prices of all pieces of size smaller than n. Determine the maximum value obtainable by cutting up the rod and selling the pieces. For example, if length of the rod is 8 and the values of different pieces are given as following, then the maximum obtainable value is 22 (by cutting in two pieces of lengths 2 and 6) " }, { "code": null, "e": 566, "s": 437, "text": "length | 1 2 3 4 5 6 7 8 \n--------------------------------------------\nprice | 1 5 8 9 10 17 17 20" }, { "code": null, "e": 683, "s": 566, "text": "And if the prices are as following, then the maximum obtainable value is 24 (by cutting in eight pieces of length 1)" }, { "code": null, "e": 812, "s": 683, "text": "length | 1 2 3 4 5 6 7 8 \n--------------------------------------------\nprice | 3 5 8 9 10 17 17 20" }, { "code": null, "e": 960, "s": 812, "text": "Following is simple recursive implementation of the Rod Cutting problem. The implementation simply follows the recursive structure mentioned above." }, { "code": null, "e": 968, "s": 960, "text": "Python3" }, { "code": "# A Naive recursive solution# for Rod cutting problemimport sys # A utility function to get the# maximum of two integersdef max(a, b): return a if (a > b) else b # Returns the best obtainable price for a rod of length n# and price[] as prices of different piecesdef cutRod(price, n): if(n <= 0): return 0 max_val = -sys.maxsize-1 # Recursively cut the rod in different pieces # and compare different configurations for i in range(0, n): max_val = max(max_val, price[i] + cutRod(price, n - i - 1)) return max_val # Driver codearr = [1, 5, 8, 9, 10, 17, 17, 20]size = len(arr)print(\"Maximum Obtainable Value is\", cutRod(arr, size)) # This code is contributed by 'Smitha Dinesh Semwal'", "e": 1717, "s": 968, "text": null }, { "code": null, "e": 1748, "s": 1717, "text": "Maximum Obtainable Value is 22" }, { "code": null, "e": 1839, "s": 1750, "text": "Considering the above implementation, following is recursion tree for a Rod of length 4." }, { "code": null, "e": 2246, "s": 1839, "text": "cR() ---> cutRod() \n\n cR(4)\n / / \n / / \n cR(3) cR(2) cR(1) cR(0)\n / | / |\n / | / | \n cR(2) cR(1) cR(0) cR(1) cR(0) cR(0)\n / | |\n / | | \n cR(1) cR(0) cR(0) cR(0)\n /\n /\nCR(0)" }, { "code": null, "e": 2746, "s": 2246, "text": "In the above partial recursion tree, cR(2) is being solved twice. We can see that there are many subproblems which are solved again and again. Since same subproblems are called again, this problem has Overlapping Subproblems property. So the Rod Cutting problem has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, recomputations of same subproblems can be avoided by constructing a temporary array val[] in bottom up manner." }, { "code": null, "e": 2754, "s": 2746, "text": "Python3" }, { "code": "# A Dynamic Programming solution for Rod cutting problemINT_MIN = -32767 # Returns the best obtainable price for a rod of length n and# price[] as prices of different piecesdef cutRod(price, n): val = [0 for x in range(n + 1)] val[0] = 0 # Build the table val[] in bottom up manner and return # the last entry from the table for i in range(1, n + 1): max_val = INT_MIN for j in range(i): max_val = max(max_val, price[j] + val[i-j-1]) val[i] = max_val return val[n] # Driver program to test above functionsarr = [1, 5, 8, 9, 10, 17, 17, 20]size = len(arr)print(\"Maximum Obtainable Value is \" + str(cutRod(arr, size))) # This code is contributed by Bhavya Jain", "e": 3466, "s": 2754, "text": null }, { "code": null, "e": 3497, "s": 3466, "text": "Maximum Obtainable Value is 22" }, { "code": null, "e": 3573, "s": 3499, "text": "Please refer complete article on Cutting a Rod | DP-13 for more details! " }, { "code": null, "e": 3585, "s": 3573, "text": "anikakapoor" }, { "code": null, "e": 3601, "s": 3585, "text": "amartyaghoshgfg" }, { "code": null, "e": 3617, "s": 3601, "text": "Python Programs" }, { "code": null, "e": 3715, "s": 3617, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3756, "s": 3715, "text": "Python Program to check Armstrong Number" }, { "code": null, "e": 3820, "s": 3756, "text": "Python program to interchange first and last elements in a list" }, { "code": null, "e": 3894, "s": 3820, "text": "Differences and Applications of List, Tuple, Set and Dictionary in Python" }, { "code": null, "e": 3933, "s": 3894, "text": "Appending to list in Python dictionary" }, { "code": null, "e": 3968, "s": 3933, "text": "Python Program for simple interest" }, { "code": null, "e": 3998, "s": 3968, "text": "Python Program for Merge Sort" }, { "code": null, "e": 4039, "s": 3998, "text": "Python Program for n-th Fibonacci number" }, { "code": null, "e": 4085, "s": 4039, "text": "Python | Find most frequent element in a list" }, { "code": null, "e": 4122, "s": 4085, "text": "Python | Remove spaces from a string" } ]
How to use SearchView in the Toolbar in Kotlin?
This example demonstrates how to use SearchView in the Toolbar in Kotlin. Step 1 − Create a new project in Android Studio, go to File ⇉ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <androidx.appcompat.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="?attr/colorBackgroundFloating" android:minHeight="?attr/actionBarSize" /> <ListView android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="wrap_content" /> <TextView android:id="@+id/emptyView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="No Results" android:textSize="20sp" android:visibility="gone" /> </RelativeLayout> Step 3 − Open res/strings.xml and add the following code− <resources> <string name="app_name">Q38</string> <string-array name="months_array"> <item>January</item> <item>February</item> <item>March</item> <item>April</item> <item>May</item> <item>June</item> <item>July</item> <item>August</item> <item>September</item> <item>October</item> <item>November</item> <item>December</item> </string-array> </resources> Step 4 − Add the following code to MainActivity.kt import android.os.Bundle import android.view.Menu import android.widget.* import android.widget.AdapterView.OnItemClickListener import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar class MainActivity : AppCompatActivity() { private lateinit var toolbar: Toolbar lateinit var adapter: ArrayAdapter<*> private lateinit var listView: ListView private lateinit var emptyView: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" toolbar = findViewById(R.id.toolbar) listView = findViewById(R.id.listView) emptyView = findViewById(R.id.emptyView) adapter = ArrayAdapter<Any?>(this, android.R.layout.simple_list_item_1, resources.getStringArray(R.array.months_array)) listView.adapter = adapter listView.onItemClickListener = OnItemClickListener { adapterView, _, i, _ -> Toast.makeText(this@MainActivity, adapterView.getItemAtPosition(i).toString(), Toast.LENGTH_SHORT).show() } listView.emptyView = emptyView } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu, menu) val search = menu.findItem(R.id.appSearchBar) val searchView = search.actionView as SearchView searchView.queryHint = "Search" searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String?): Boolean { return false } override fun onQueryTextChange(newText: String?): Boolean { adapter.filter.filter(newText) return true } }) return super.onCreateOptionsMenu(menu) } } Step 5 − Create a Android resource folder (menu) and create a menu resource file (menu.xml) and add the following code− <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <item android:id="@+id/appSearchBar" android:icon="@drawable/ic_search" android:title="Search" app:actionViewClass="android.widget.SearchView" app:showAsAction="ifRoom|withText" /> </menu> Step 6 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.q36"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − Click here to download the project code.
[ { "code": null, "e": 1136, "s": 1062, "text": "This example demonstrates how to use SearchView in the Toolbar in Kotlin." }, { "code": null, "e": 1265, "s": 1136, "text": "Step 1 − Create a new project in Android Studio, go to File ⇉ New Project and fill all required details to create a new project." }, { "code": null, "e": 1330, "s": 1265, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2332, "s": 1330, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <androidx.appcompat.widget.Toolbar\n android:id=\"@+id/toolbar\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:background=\"?attr/colorBackgroundFloating\"\n android:minHeight=\"?attr/actionBarSize\" />\n <ListView\n android:id=\"@+id/listView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\" />\n <TextView\n android:id=\"@+id/emptyView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:text=\"No Results\"\n android:textSize=\"20sp\"\n android:visibility=\"gone\" />\n</RelativeLayout>" }, { "code": null, "e": 2390, "s": 2332, "text": "Step 3 − Open res/strings.xml and add the following code−" }, { "code": null, "e": 2826, "s": 2390, "text": "<resources>\n <string name=\"app_name\">Q38</string>\n <string-array name=\"months_array\">\n <item>January</item>\n <item>February</item>\n <item>March</item>\n <item>April</item>\n <item>May</item>\n <item>June</item>\n <item>July</item>\n <item>August</item>\n <item>September</item>\n <item>October</item>\n <item>November</item>\n <item>December</item>\n </string-array>\n</resources>" }, { "code": null, "e": 2877, "s": 2826, "text": "Step 4 − Add the following code to MainActivity.kt" }, { "code": null, "e": 4674, "s": 2877, "text": "import android.os.Bundle\nimport android.view.Menu\nimport android.widget.*\nimport android.widget.AdapterView.OnItemClickListener\nimport androidx.appcompat.app.AppCompatActivity\nimport androidx.appcompat.widget.Toolbar\nclass MainActivity : AppCompatActivity() {\n private lateinit var toolbar: Toolbar\n lateinit var adapter: ArrayAdapter<*>\n private lateinit var listView: ListView\n private lateinit var emptyView: TextView\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n toolbar = findViewById(R.id.toolbar)\n listView = findViewById(R.id.listView)\n emptyView = findViewById(R.id.emptyView)\n adapter = ArrayAdapter<Any?>(this, android.R.layout.simple_list_item_1,\n resources.getStringArray(R.array.months_array))\n listView.adapter = adapter\n listView.onItemClickListener = OnItemClickListener { adapterView, _, i, _ ->\n Toast.makeText(this@MainActivity, adapterView.getItemAtPosition(i).toString(),\n Toast.LENGTH_SHORT).show()\n }\n listView.emptyView = emptyView\n }\n override fun onCreateOptionsMenu(menu: Menu): Boolean {\n menuInflater.inflate(R.menu.menu, menu)\n val search = menu.findItem(R.id.appSearchBar)\n val searchView = search.actionView as SearchView\n searchView.queryHint = \"Search\"\n searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {\n override fun onQueryTextSubmit(query: String?): Boolean {\n return false\n }\n override fun onQueryTextChange(newText: String?): Boolean {\n adapter.filter.filter(newText)\n return true\n }\n })\n return super.onCreateOptionsMenu(menu)\n }\n}" }, { "code": null, "e": 4794, "s": 4674, "text": "Step 5 − Create a Android resource folder (menu) and create a menu resource file (menu.xml) and add the following code−" }, { "code": null, "e": 5176, "s": 4794, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<menu xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\">\n <item\n android:id=\"@+id/appSearchBar\"\n android:icon=\"@drawable/ic_search\"\n android:title=\"Search\"\n app:actionViewClass=\"android.widget.SearchView\"\n app:showAsAction=\"ifRoom|withText\" />\n</menu>" }, { "code": null, "e": 5231, "s": 5176, "text": "Step 6 − Add the following code to androidManifest.xml" }, { "code": null, "e": 5901, "s": 5231, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.q36\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 6252, "s": 5901, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 6293, "s": 6252, "text": "Click here to download the project code." } ]
Tryit Editor v3.7 - Show Java
static void Main(string[] args) { string firstName = "John "; string lastName = "Doe"; string name = string.Concat(firstName, lastName);
[]
How to change the color of points in a scatterplot using ggplot2 in R?
To color the points in a scatterplot using ggplot2, we can use colour argument inside geom_point with aes. The color can be passed in multiple ways, one such way is to name the particular color and the other way is to giving a range or using a variable. If range or a variable will be used then the color of the points will be in different shades. Live Demo Consider the below data frame − x<−rnorm(20,5,2) y<−rnorm(20,5,1.25) df<−data.frame(x,y) df x y 1 6.3184535 5.548867 2 3.4643698 6.247067 3 7.8930528 2.259042 4 7.6517535 4.606704 5 1.7838941 3.605288 6 0.3985215 6.183794 7 5.2738435 3.857376 8 4.7734419 3.389663 9 3.9727197 5.662962 10 3.3976335 5.172815 11 4.1068840 4.379264 12 6.7723590 5.914132 13 3.0944360 4.184177 14 7.0857100 5.266121 15 2.6391362 4.433864 16 5.2571231 4.144391 17 5.8119542 4.725406 18 5.3608015 4.828909 19 9.7308286 6.489042 20 2.3823201 6.916862 Loading ggplot2 package and creating a scatterplot − library(ggplot2) ggplot(df,aes(x,y,col=x))+geom_point() Creating the scatterplot by using the variable x − ggplot(df,aes(x,y))+geom_point(aes(colour=x))
[ { "code": null, "e": 1410, "s": 1062, "text": "To color the points in a scatterplot using ggplot2, we can use colour argument inside geom_point with aes. The color can be passed in multiple ways, one such way is to name the particular color and the other way is to giving a range or using a variable. If range or a variable will be used then the color of the points will be in different shades." }, { "code": null, "e": 1421, "s": 1410, "text": " Live Demo" }, { "code": null, "e": 1453, "s": 1421, "text": "Consider the below data frame −" }, { "code": null, "e": 1513, "s": 1453, "text": "x<−rnorm(20,5,2)\ny<−rnorm(20,5,1.25)\ndf<−data.frame(x,y)\ndf" }, { "code": null, "e": 1960, "s": 1513, "text": " x y\n1 6.3184535 5.548867\n2 3.4643698 6.247067\n3 7.8930528 2.259042\n4 7.6517535 4.606704\n5 1.7838941 3.605288\n6 0.3985215 6.183794\n7 5.2738435 3.857376\n8 4.7734419 3.389663\n9 3.9727197 5.662962\n10 3.3976335 5.172815\n11 4.1068840 4.379264\n12 6.7723590 5.914132\n13 3.0944360 4.184177\n14 7.0857100 5.266121\n15 2.6391362 4.433864\n16 5.2571231 4.144391\n17 5.8119542 4.725406\n18 5.3608015 4.828909\n19 9.7308286 6.489042\n20 2.3823201 6.916862" }, { "code": null, "e": 2013, "s": 1960, "text": "Loading ggplot2 package and creating a scatterplot −" }, { "code": null, "e": 2069, "s": 2013, "text": "library(ggplot2)\nggplot(df,aes(x,y,col=x))+geom_point()" }, { "code": null, "e": 2120, "s": 2069, "text": "Creating the scatterplot by using the variable x −" }, { "code": null, "e": 2166, "s": 2120, "text": "ggplot(df,aes(x,y))+geom_point(aes(colour=x))" } ]
How to get a list of all the keys from a Python dictionary?
To get a list of all keys from a dictionary, you can simply use the dict.keys() function. my_dict = {'name': 'TutorialsPoint', 'time': '15 years', 'location': 'India'} key_list = list(my_dict.keys()) print(key_list) This will give the output − ['name', 'time', 'location'] You can also get a list of all keys in a dictionary using a list comprehension. my_dict = {'name': 'TutorialsPoint', 'time': '15 years', 'location': 'India'} key_list = [key for key in my_dict] print(key_list) This will give the output − ['name', 'time', 'location']
[ { "code": null, "e": 1153, "s": 1062, "text": "To get a list of all keys from a dictionary, you can simply use the dict.keys() function. " }, { "code": null, "e": 1279, "s": 1153, "text": "my_dict = {'name': 'TutorialsPoint', 'time': '15 years', 'location': 'India'}\nkey_list = list(my_dict.keys())\nprint(key_list)" }, { "code": null, "e": 1307, "s": 1279, "text": "This will give the output −" }, { "code": null, "e": 1336, "s": 1307, "text": "['name', 'time', 'location']" }, { "code": null, "e": 1417, "s": 1336, "text": "You can also get a list of all keys in a dictionary using a list comprehension. " }, { "code": null, "e": 1547, "s": 1417, "text": "my_dict = {'name': 'TutorialsPoint', 'time': '15 years', 'location': 'India'}\nkey_list = [key for key in my_dict]\nprint(key_list)" }, { "code": null, "e": 1575, "s": 1547, "text": "This will give the output −" }, { "code": null, "e": 1604, "s": 1575, "text": "['name', 'time', 'location']" } ]
Byte Class in Java
The Byte class wraps a value of primitive type byte in an object. An object of type Byte contains a single field whose type is byte. Following are some of the methods of the Byte class − Let us now see an example− Live Demo import java.lang.*; public class Demo { public static void main(String[] args){ Byte b1, b2; int i1, i2; b1 = new Byte("1"); b2 = new Byte("-1"); i1 = b1.intValue(); i2 = b2.intValue(); String str1 = "int value of Byte " + b1 + " is " + i1; String str2 = "int value of Byte " + b2 + " is " + i2; System.out.println( str1 ); System.out.println( str2 ); } } int value of Byte 1 is 1 int value of Byte -1 is -1 Let us now see another example − Live Demo import java.lang.*; public class Demo { public static void main(String[] args){ Byte b1, b2; String s1, s2; b1 = new Byte("-123"); b2 = new Byte("0"); s1 = b1.toString(); s2 = b2.toString(); String str1 = "String value of Byte " + b1 + " is " + s1; String str2 = "String value of Byte " + b2 + " is " + s2; System.out.println( str1 ); System.out.println( str2 ); } } String value of Byte -123 is -123 String value of Byte 0 is 0
[ { "code": null, "e": 1195, "s": 1062, "text": "The Byte class wraps a value of primitive type byte in an object. An object of type Byte contains a single field whose type is byte." }, { "code": null, "e": 1249, "s": 1195, "text": "Following are some of the methods of the Byte class −" }, { "code": null, "e": 1276, "s": 1249, "text": "Let us now see an example−" }, { "code": null, "e": 1287, "s": 1276, "text": " Live Demo" }, { "code": null, "e": 1709, "s": 1287, "text": "import java.lang.*;\npublic class Demo {\n public static void main(String[] args){\n Byte b1, b2;\n int i1, i2;\n b1 = new Byte(\"1\");\n b2 = new Byte(\"-1\");\n i1 = b1.intValue();\n i2 = b2.intValue();\n String str1 = \"int value of Byte \" + b1 + \" is \" + i1;\n String str2 = \"int value of Byte \" + b2 + \" is \" + i2;\n System.out.println( str1 );\n System.out.println( str2 );\n }\n}" }, { "code": null, "e": 1761, "s": 1709, "text": "int value of Byte 1 is 1\nint value of Byte -1 is -1" }, { "code": null, "e": 1794, "s": 1761, "text": "Let us now see another example −" }, { "code": null, "e": 1805, "s": 1794, "text": " Live Demo" }, { "code": null, "e": 2238, "s": 1805, "text": "import java.lang.*;\npublic class Demo {\n public static void main(String[] args){\n Byte b1, b2;\n String s1, s2;\n b1 = new Byte(\"-123\");\n b2 = new Byte(\"0\");\n s1 = b1.toString();\n s2 = b2.toString();\n String str1 = \"String value of Byte \" + b1 + \" is \" + s1;\n String str2 = \"String value of Byte \" + b2 + \" is \" + s2;\n System.out.println( str1 );\n System.out.println( str2 );\n }\n}" }, { "code": null, "e": 2300, "s": 2238, "text": "String value of Byte -123 is -123\nString value of Byte 0 is 0" } ]
Material - Action Icons
This chapter explains the usage of Google's (Material) Action Icons. Assume that custom is the CSS class name where we defined the size and color, as shown in the example given below. <!DOCTYPE html> <html> <head> <link href = "https://fonts.googleapis.com/icon?family=Material+Icons" rel = "stylesheet"> <style> i.custom {font-size: 2em; color: green;} </style> </head> <body> <i class = "material-icons custom">accessibility</i> </body> </html> The following table contains the usage and results of Google's (Material) Action Icons. Replace the < body > tag of the above program with the code given in the table to get the respective outputs − 26 Lectures 2 hours Neha Gupta 20 Lectures 2 hours Asif Hussain 43 Lectures 5 hours Sharad Kumar 411 Lectures 38.5 hours In28Minutes Official 71 Lectures 10 hours Chaand Sheikh 207 Lectures 33 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2750, "s": 2566, "text": "This chapter explains the usage of Google's (Material) Action Icons. Assume that custom is the CSS class name where we defined the size and color, as shown in the example given below." }, { "code": null, "e": 3068, "s": 2750, "text": "<!DOCTYPE html>\n<html>\n <head>\n <link href = \"https://fonts.googleapis.com/icon?family=Material+Icons\" rel = \"stylesheet\">\n\t\t\n <style>\n i.custom {font-size: 2em; color: green;}\n </style>\n\t\t\n </head>\n\t\n <body>\n <i class = \"material-icons custom\">accessibility</i>\n </body>\n\t\n</html>" }, { "code": null, "e": 3267, "s": 3068, "text": "The following table contains the usage and results of Google's (Material) Action Icons. Replace the < body > tag of the above program with the code given in the table to get the respective outputs −" }, { "code": null, "e": 3300, "s": 3267, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 3312, "s": 3300, "text": " Neha Gupta" }, { "code": null, "e": 3345, "s": 3312, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 3359, "s": 3345, "text": " Asif Hussain" }, { "code": null, "e": 3392, "s": 3359, "text": "\n 43 Lectures \n 5 hours \n" }, { "code": null, "e": 3406, "s": 3392, "text": " Sharad Kumar" }, { "code": null, "e": 3443, "s": 3406, "text": "\n 411 Lectures \n 38.5 hours \n" }, { "code": null, "e": 3465, "s": 3443, "text": " In28Minutes Official" }, { "code": null, "e": 3499, "s": 3465, "text": "\n 71 Lectures \n 10 hours \n" }, { "code": null, "e": 3514, "s": 3499, "text": " Chaand Sheikh" }, { "code": null, "e": 3549, "s": 3514, "text": "\n 207 Lectures \n 33 hours \n" }, { "code": null, "e": 3577, "s": 3549, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3584, "s": 3577, "text": " Print" }, { "code": null, "e": 3595, "s": 3584, "text": " Add Notes" } ]
Sum of an Infinite Geometric Progression ( GP ) - GeeksforGeeks
07 May, 2021 Given two integers A and R, representing the first term and the common ratio of a geometric sequence, the task is to find the sum of the infinite geometric series formed by the given first term and the common ratio. Examples: Input: A = 1, R = 0.5Output: 2 Input: A = 1, R = -0.25Output: 0.8 Approach: The given problem can be solved based on the following observations: If absolute of value of R is greater than equal to 1, then the sum will be infinite. Otherwise, the sum of the Geometric series with infinite terms can be calculated using the formula Therefore, if the absolute value of R is greater than equal to 1, then print “Infinite”. Otherwise, print the value as the resultant sum. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Function to calculate the sum of // an infinite Geometric Progression void findSumOfGP(double a, double r) { // Case for Infinite Sum if (abs(r) >= 1) { cout << "Infinite"; return; } // Store the sum of GP Series double sum = a / (1 - r); // Print the value of sum cout << sum; } // Driver Code int main() { double A = 1, R = 0.5; findSumOfGP(A, R); return 0; } // Java program for the above approach import java.util.*; class GFG{ // Function to calculate the sum of // an infinite Geometric Progression static void findSumOfGP(double a, double r) { // Case for Infinite Sum if (Math.abs(r) >= 1) { System.out.print("Infinite"); return; } // Store the sum of GP Series double sum = a / (1 - r); // Print the value of sum System.out.print(sum); } // Driver Code public static void main(String[] args) { double A = 1, R = 0.5; findSumOfGP(A, R); } } // This code is contributed by 29AjayKumar # Python3 program for the above approach # Function to calculate the sum of # an infinite Geometric Progression def findSumOfGP(a, r): # Case for Infinite Sum if (abs(r) >= 1): print("Infinite") return # Store the sum of GP Series sum = a / (1 - r) # Print the value of sum print(int(sum)) # Driver Code if __name__ == '__main__': A, R = 1, 0.5 findSumOfGP(A, R) # This code is contributed by mohit kumar 29. // C# program for the above approach using System; class GFG { // Function to calculate the sum of // an infinite Geometric Progression static void findSumOfGP(double a, double r) { // Case for Infinite Sum if (Math.Abs(r) >= 1) { Console.Write("Infinite"); return; } // Store the sum of GP Series double sum = a / (1 - r); // Print the value of sum Console.Write(sum); } // Driver Code public static void Main() { double A = 1, R = 0.5; findSumOfGP(A, R); } } // This code is contributed by ukasp. <script> // JavaScript program for the above approach // Function to calculate the sum of // an infinite Geometric Progression function findSumOfGP(a, r) { // Case for Infinite Sum if (Math.abs(r) >= 1) { document.write("Infinite"); return; } // Store the sum of GP Series let sum = a / (1 - r); // Print the value of sum document.write(sum); } // Driver Code let A = 1, R = 0.5; findSumOfGP(A, R); // This code is contributed by sanjoy_62 </script> 2 Time Complexity: O(1)Auxiliary Space: O(1) mohit kumar 29 ukasp sanjoy_62 29AjayKumar Geometric Progression Sequence and Series series series-sum Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Program to convert a given number to words Program to multiply two matrices Modular multiplicative inverse Program to print prime numbers from 1 to N. Count ways to reach the n'th stair Check if a number is Palindrome Singular Value Decomposition (SVD) Fizz Buzz Implementation Find first and last digits of a number
[ { "code": null, "e": 24686, "s": 24655, "text": " \n07 May, 2021\n" }, { "code": null, "e": 24902, "s": 24686, "text": "Given two integers A and R, representing the first term and the common ratio of a geometric sequence, the task is to find the sum of the infinite geometric series formed by the given first term and the common ratio." }, { "code": null, "e": 24912, "s": 24902, "text": "Examples:" }, { "code": null, "e": 24943, "s": 24912, "text": "Input: A = 1, R = 0.5Output: 2" }, { "code": null, "e": 24978, "s": 24943, "text": "Input: A = 1, R = -0.25Output: 0.8" }, { "code": null, "e": 25057, "s": 24978, "text": "Approach: The given problem can be solved based on the following observations:" }, { "code": null, "e": 25142, "s": 25057, "text": "If absolute of value of R is greater than equal to 1, then the sum will be infinite." }, { "code": null, "e": 25241, "s": 25142, "text": "Otherwise, the sum of the Geometric series with infinite terms can be calculated using the formula" }, { "code": null, "e": 25379, "s": 25241, "text": "Therefore, if the absolute value of R is greater than equal to 1, then print “Infinite”. Otherwise, print the value as the resultant sum." }, { "code": null, "e": 25430, "s": 25379, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 25434, "s": 25430, "text": "C++" }, { "code": null, "e": 25439, "s": 25434, "text": "Java" }, { "code": null, "e": 25447, "s": 25439, "text": "Python3" }, { "code": null, "e": 25450, "s": 25447, "text": "C#" }, { "code": null, "e": 25461, "s": 25450, "text": "Javascript" }, { "code": "\n\n\n\n\n\n\n// C++ program for the above approach\n \n#include <bits/stdc++.h>\nusing namespace std;\n \n// Function to calculate the sum of\n// an infinite Geometric Progression\nvoid findSumOfGP(double a, double r)\n{\n // Case for Infinite Sum\n if (abs(r) >= 1) {\n cout << \"Infinite\";\n return;\n }\n \n // Store the sum of GP Series\n double sum = a / (1 - r);\n \n // Print the value of sum\n cout << sum;\n}\n \n// Driver Code\nint main()\n{\n double A = 1, R = 0.5;\n findSumOfGP(A, R);\n \n return 0;\n}\n\n\n\n\n\n", "e": 26001, "s": 25471, "text": null }, { "code": "\n\n\n\n\n\n\n// Java program for the above approach\nimport java.util.*;\n \nclass GFG{\n \n// Function to calculate the sum of\n// an infinite Geometric Progression\nstatic void findSumOfGP(double a, double r)\n{\n \n // Case for Infinite Sum\n if (Math.abs(r) >= 1)\n {\n System.out.print(\"Infinite\");\n return;\n }\n \n // Store the sum of GP Series\n double sum = a / (1 - r);\n \n // Print the value of sum\n System.out.print(sum);\n}\n \n// Driver Code\npublic static void main(String[] args)\n{\n double A = 1, R = 0.5;\n findSumOfGP(A, R);\n}\n}\n \n// This code is contributed by 29AjayKumar\n\n\n\n\n\n", "e": 26628, "s": 26011, "text": null }, { "code": "\n\n\n\n\n\n\n# Python3 program for the above approach\n \n# Function to calculate the sum of\n# an infinite Geometric Progression\ndef findSumOfGP(a, r):\n \n # Case for Infinite Sum\n if (abs(r) >= 1):\n print(\"Infinite\")\n return\n \n # Store the sum of GP Series\n sum = a / (1 - r)\n \n # Print the value of sum\n print(int(sum))\n \n# Driver Code\nif __name__ == '__main__':\n A, R = 1, 0.5\n findSumOfGP(A, R)\n \n# This code is contributed by mohit kumar 29.\n\n\n\n\n\n", "e": 27122, "s": 26638, "text": null }, { "code": "\n\n\n\n\n\n\n// C# program for the above approach\nusing System;\nclass GFG\n{\n \n // Function to calculate the sum of\n // an infinite Geometric Progression\n static void findSumOfGP(double a, double r)\n {\n \n // Case for Infinite Sum\n if (Math.Abs(r) >= 1) {\n Console.Write(\"Infinite\");\n return;\n }\n \n // Store the sum of GP Series\n double sum = a / (1 - r);\n \n // Print the value of sum\n Console.Write(sum);\n }\n \n // Driver Code\n public static void Main()\n {\n double A = 1, R = 0.5;\n findSumOfGP(A, R);\n }\n}\n \n// This code is contributed by ukasp.\n\n\n\n\n\n", "e": 27796, "s": 27132, "text": null }, { "code": "\n\n\n\n\n\n\n<script>\n \n// JavaScript program for the above approach\n \n// Function to calculate the sum of\n// an infinite Geometric Progression\nfunction findSumOfGP(a, r)\n{\n \n // Case for Infinite Sum\n if (Math.abs(r) >= 1)\n {\n document.write(\"Infinite\");\n return;\n }\n \n // Store the sum of GP Series\n let sum = a / (1 - r);\n \n // Print the value of sum\n document.write(sum);\n}\n \n// Driver Code\nlet A = 1, R = 0.5;\n \nfindSumOfGP(A, R);\n \n// This code is contributed by sanjoy_62\n \n</script>\n\n\n\n\n\n", "e": 28343, "s": 27806, "text": null }, { "code": null, "e": 28345, "s": 28343, "text": "2" }, { "code": null, "e": 28390, "s": 28347, "text": "Time Complexity: O(1)Auxiliary Space: O(1)" }, { "code": null, "e": 28405, "s": 28390, "text": "mohit kumar 29" }, { "code": null, "e": 28411, "s": 28405, "text": "ukasp" }, { "code": null, "e": 28421, "s": 28411, "text": "sanjoy_62" }, { "code": null, "e": 28433, "s": 28421, "text": "29AjayKumar" }, { "code": null, "e": 28457, "s": 28433, "text": "\nGeometric Progression\n" }, { "code": null, "e": 28479, "s": 28457, "text": "\nSequence and Series\n" }, { "code": null, "e": 28488, "s": 28479, "text": "\nseries\n" }, { "code": null, "e": 28501, "s": 28488, "text": "\nseries-sum\n" }, { "code": null, "e": 28516, "s": 28501, "text": "\nMathematical\n" }, { "code": null, "e": 28721, "s": 28516, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 28753, "s": 28721, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 28796, "s": 28753, "text": "Program to convert a given number to words" }, { "code": null, "e": 28829, "s": 28796, "text": "Program to multiply two matrices" }, { "code": null, "e": 28860, "s": 28829, "text": "Modular multiplicative inverse" }, { "code": null, "e": 28904, "s": 28860, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 28939, "s": 28904, "text": "Count ways to reach the n'th stair" }, { "code": null, "e": 28971, "s": 28939, "text": "Check if a number is Palindrome" }, { "code": null, "e": 29006, "s": 28971, "text": "Singular Value Decomposition (SVD)" }, { "code": null, "e": 29031, "s": 29006, "text": "Fizz Buzz Implementation" } ]
Create Your Resume with Pagedown Package in R | by Abhinav Malasi | Towards Data Science
In the past, I always dreamt of making my resume using LaTeX, but the learning curve to achieve that polished looked never materialized. So, I always ended up making my resume using word documents and silently endured the alignment struggles that entailed. Recently, I was going through the same cycle of updating my resume and spent a lot of time on alignment. Then I thought, let’s see if there is a permanent solution to this, and by chance, I pondered upon this lovely blog by Nick Strayer, which provides a very simple solution to automate resume building by dividing sections of resume into different CSV files. And further adding an option to choose sub-sections to show up on the resume. This style gives the flexibility to create targeted resumes for different job types. The built-in resume template from the pagedown package takes care of the formatting of the resume. So, in a way, this is a hassle-free solution that I had been looking for long. Inspired by the blog, I created this detailed tutorial to build the resume adding details which I felt were not adequately covered in the blog (people like me with no or very less knowledge of CSS). Power your data portfolio with R pagedown package resume template. We will divide the resume building into the following 4 sections: Resume essentialsTemplate customizationPrint to PdfData automation Resume essentials Template customization Print to Pdf Data automation The final goal is to get the customized template up and running as shown. To make your resume in RStudio first you have to install the pagedown package if not already done. The package comes with an inbuilt resume template. Start by creating a new R Markdown document after installing the pagedown package. A new window pops up on which choose the From Template option and then HTML Resume template by pagedown package and click OK. This will open the default version of the Resume on your RStudio. Knit the document, it might ask you to save the document first and after that, it will compile the resume and a new window will pop up with the resume. The default resume will look like this. The resume is divided into 2 panels: the main panel and the side panel. In total 8 areas have been labeled in the above image that will be explained below which will later help you to build your resume. So for the time being we will leave the YAML header part and will get back to it later. After the YAML header chunk follows the Aside heading that is labeled as a sidebar and Main heading labeled as the Main panel in the above image. Points 1–5 are from the Main panel of the resume and Points 6–8 are from the sidebar. Let us go point by point (refer to the above image): Point 1: The place holder for your name or the main heading. Point 2: This is the sub-heading of your resume (highlight important details that you want your recruiter or hiring manager to notice). Point 3: The summary section. You guys know well what to fill in here. Points 1–3 are highlighted below. Main================================================================================Lijia Yu {#title} [POINT 1: heading]--------------------------------------------------------------------------------### Currently searching for a PhD student position [POINT 2: sub-heading]TEXT SUMMARY [POINT 3: summary] In case you are not very familiar with the Markdown syntax for section headings, a series of = under a heading is equivalent to # before a heading, and a series of — is equivalent to ##. (Text from Pagedown manual) Point 4: This is divided into 2 parts: one is defining the heading of the section (in this case it is Education) and the other is identifying an icon to represent it (graduation cap for education). This section can be repeated to write about: Work experience, research experience, certifications, educations, etc., and the pattern will be the same. So this chunk of text can be copied repeatedly. The icons used in the resume template are from Font Awesome website. Point 5: Once you have defined a section, it can further be broken down into a number of subsections. The subsection has 5 fields to fill in of which the first 4 are mandatory fields. First is the title of the sub-section, second is the sub-title of the sub-section, third is the location, fourth is the time period. The time period can be just a year like 2021 or it can be a range like 02/2020–03/2021 or 2020–2021. The fifth field is not mandatory is for supporting text and can be left empty. Points 4 and 5 are explained below: Education {data-icon=graduation-cap} [POINT 4: section heading]--------------------------------------------------------------------------------### Beijing University of Chemical Technology [POINT 5: subsection heading]B.S. in Information and Computing Sciences [POINT 5: subtitle] Beijing, China [POINT 5: location]2010 [POINT 5: time period] Thesis: Dyadic wavelet and its application in edge detection [POINT 5: supporting text] Out of the 4 mandatory fields, only the sub-title, location, and time period fields can be skipped by filling in N/A. The fifth field is to add details to your subsections. By default, the text will be published as a single column but the display can be changed to 2-columns by using :::concise block as shown below. :::concise- sentence 1- sentence 2- sentence 3- sentence 4::: Now let's move on to the sidebar that covers points 6–8. Point 6: By default, a logo is inserted in the template which can be changed by any image just by adding the correct path in the text. Aside================================================================================![Lijia Yu](https://avatars1.githubusercontent.com/u/895125?s=400&v=4){width=80%} Point 7: The contact info section is where you can highlight your social media pages or blogs and personal contact info. Again the icons are from Font Awesome webpage. The information in contact info can be added in the following way: - <i class="fa fa-github"></i> [github.com/yulijia](https://github.com/yulijia) Point 8: The skills section is where you can jot down all the skills. If you want to list the skills it can be done in the following way: Skills {#skills}--------------------------------------------------------------------------------- skill 1- skill 2- skill 3 Till now we have covered the essential building blocks for creating the resume. The compiled resume will give you an idea of how it will look. If you are satisfied with the current version then you can skip to the end. If you are unsure of the looks of it, then let’s get to the customization part of it. At first glance, if you think there is plenty of white space along the borders, or, the sidebar is too thick, or even you think the font style is way off according to your style then you need to customize it. You can even play with the colors of the timelines on the left side and the background color of the sidebar. To address all these issues you need to know CSS. If you are a person like me with no background in CSS then read on. Page margins: To override a predefined function, an asterisk (* )needs to be added before the function as shown in the below text. This way new margin values for the page can be defined. * { /* Override default margins*/ --pagedjs-margin-right: 0.2in; --pagedjs-margin-left: 0.2in; --pagedjs-margin-top: 0.2in; --pagedjs-margin-bottom: 0.2in;} Sidebar width: In the root function, the default value for sidebar width is 15 rem. This value can be changed to get the desired width of the sidebar. For the current case, it has been assigned to 12 rem. --sidebar-width: 12rem; Sidebar color: In the root function, the sidebar background color can also be changed. For demonstration purposes, the color is switched from #f2f2f2 to #a2e2e2. --sidebar-background-color: #a2e2e2; Color of timeline: The timeline on the left side of the resume consists of vertical lines connecting dots under the same section. Both the thickness and color of the vertical lines can be changed as shown below. --decorator-border: 2px solid #a2e2e2; /* change color and thickness of timeline */ Further, the background color of the dots can be changed as shown below. background-color: #a2e2e2; /* change color timeline dots */ Font type: The font type can be changed in the body function by defining the font family. In this example, I changed the font from Open Sans to Roboto both from sans-serif. /* Define the font family here */body{ font-family: "Roboto", sans-serif;} All the changes to be made for customization are defined in override.css file. The complete code is here: To incorporate all the changes in the CSS file, we can override the existing CSS file completely or certain rules with a new one in the YAML header. This is done by adding the new file name with the CSS extension. The new CSS file created should be kept in the folder with the markdown file. The location of the original CSS file will be ...Resume_demo_files\paged-0.13\css\resume.css . The folder will be created when the markdown file is knit in its default condition. output: pagedown::html_resume: css: - override.css # OVERIDE CERTAIN FUNCTIONS OF CSS - resume # DEFAULT FILE You will notice when you knit the markdown file a window will pop up displaying the resume with the Open in Browser option on the top left. On clicking this option it will just open a blank tab on your browser. For the resume to display on the browser tab, one has to change the YAML setting from the default value of FALSE to TRUE. This can be done by setting self_contained: false to self_contained: true. Then the pdf can be generated by printing the displayed resume on the browser tab. Another option to create pdf file is to add knit: pagedown::chrome_print to YAML header. Now coming to the best part of the resume building where you can automate the data filling. Thanks to Nick Strayer for getting my resume from being just customized to being fully data automated. As always, you need to create the master data CSV files for all the sections of your resume. The master data can be done in 2 ways: CSV files: Create CSV files and keep updating them as per your needs. The CSV files can be made on your personal device or on google sheets. Separate files can be made for work, skills, and contact details.Hybrid approach: If you are in a hurry then you can directly fill in the fields in the markdown file of the resume template and will give the desired output as shown in the default resume template or with the customizations that have been incorporated. And maybe for some cases use the CSV files for adding the data. As I did in my case since I was inclined on using the skill bars to highlight the level of proficiency of my programming skills rather than just add them as a mere text. So I choose the hybrid approach. CSV files: Create CSV files and keep updating them as per your needs. The CSV files can be made on your personal device or on google sheets. Separate files can be made for work, skills, and contact details. Hybrid approach: If you are in a hurry then you can directly fill in the fields in the markdown file of the resume template and will give the desired output as shown in the default resume template or with the customizations that have been incorporated. And maybe for some cases use the CSV files for adding the data. As I did in my case since I was inclined on using the skill bars to highlight the level of proficiency of my programming skills rather than just add them as a mere text. So I choose the hybrid approach. So let me demonstrate to you what it means to automate resume building by using the text from the default resume template. The first step is to create the CSV files. Here is the example for the CSV file details of work and education history. Once you have created the files you can use the resume template, link at the end. There are two R files associated with the template. The gather_data.R looks for the data source if it has to read from google sheets or CSV files. The preference for this is indicated in the markdown file. The parsing_functions.R glues the relevant information in the markdown file when the functions related to education, work history, contact info, skills, etc. are called upon. If the color of the skill bar needs to be changed then refer the parsing_functions.R file and look for build_skill_bars() function. In this article, I showed step by step to customize the default resume template from the pagedown package. This was achieved by breaking the workflow of the template. In the first section, the basic building blocks of the template were explained and the regions that needed attention. The second part focused on template customization finding the possible pitfalls and customizing them according to my needs. The third section was to generate a pdf version of the resume. The fourth or the last section was on automating the data filling in the resume based on Nick Strayer’s work. In this section, I tried explaining the basic features that needed to be focused on to get the resume up and running in no time. This way you can showcase your data skills and data portfolio powered by R pagedown package. Customized resume: Link Customized resume with automation: Link https://livefreeordichotomize.com/2019/09/04/building_a_data_driven_cv_with_r/https://pagedown.rbind.io/https://fontawesome.com/ https://livefreeordichotomize.com/2019/09/04/building_a_data_driven_cv_with_r/ https://pagedown.rbind.io/ https://fontawesome.com/ You can connect with me on LinkedIn and Twitter to follow my data science and data visualization journey.
[ { "code": null, "e": 428, "s": 171, "text": "In the past, I always dreamt of making my resume using LaTeX, but the learning curve to achieve that polished looked never materialized. So, I always ended up making my resume using word documents and silently endured the alignment struggles that entailed." }, { "code": null, "e": 1130, "s": 428, "text": "Recently, I was going through the same cycle of updating my resume and spent a lot of time on alignment. Then I thought, let’s see if there is a permanent solution to this, and by chance, I pondered upon this lovely blog by Nick Strayer, which provides a very simple solution to automate resume building by dividing sections of resume into different CSV files. And further adding an option to choose sub-sections to show up on the resume. This style gives the flexibility to create targeted resumes for different job types. The built-in resume template from the pagedown package takes care of the formatting of the resume. So, in a way, this is a hassle-free solution that I had been looking for long." }, { "code": null, "e": 1329, "s": 1130, "text": "Inspired by the blog, I created this detailed tutorial to build the resume adding details which I felt were not adequately covered in the blog (people like me with no or very less knowledge of CSS)." }, { "code": null, "e": 1396, "s": 1329, "text": "Power your data portfolio with R pagedown package resume template." }, { "code": null, "e": 1462, "s": 1396, "text": "We will divide the resume building into the following 4 sections:" }, { "code": null, "e": 1529, "s": 1462, "text": "Resume essentialsTemplate customizationPrint to PdfData automation" }, { "code": null, "e": 1547, "s": 1529, "text": "Resume essentials" }, { "code": null, "e": 1570, "s": 1547, "text": "Template customization" }, { "code": null, "e": 1583, "s": 1570, "text": "Print to Pdf" }, { "code": null, "e": 1599, "s": 1583, "text": "Data automation" }, { "code": null, "e": 1673, "s": 1599, "text": "The final goal is to get the customized template up and running as shown." }, { "code": null, "e": 1906, "s": 1673, "text": "To make your resume in RStudio first you have to install the pagedown package if not already done. The package comes with an inbuilt resume template. Start by creating a new R Markdown document after installing the pagedown package." }, { "code": null, "e": 2032, "s": 1906, "text": "A new window pops up on which choose the From Template option and then HTML Resume template by pagedown package and click OK." }, { "code": null, "e": 2290, "s": 2032, "text": "This will open the default version of the Resume on your RStudio. Knit the document, it might ask you to save the document first and after that, it will compile the resume and a new window will pop up with the resume. The default resume will look like this." }, { "code": null, "e": 2493, "s": 2290, "text": "The resume is divided into 2 panels: the main panel and the side panel. In total 8 areas have been labeled in the above image that will be explained below which will later help you to build your resume." }, { "code": null, "e": 2866, "s": 2493, "text": "So for the time being we will leave the YAML header part and will get back to it later. After the YAML header chunk follows the Aside heading that is labeled as a sidebar and Main heading labeled as the Main panel in the above image. Points 1–5 are from the Main panel of the resume and Points 6–8 are from the sidebar. Let us go point by point (refer to the above image):" }, { "code": null, "e": 2927, "s": 2866, "text": "Point 1: The place holder for your name or the main heading." }, { "code": null, "e": 3063, "s": 2927, "text": "Point 2: This is the sub-heading of your resume (highlight important details that you want your recruiter or hiring manager to notice)." }, { "code": null, "e": 3134, "s": 3063, "text": "Point 3: The summary section. You guys know well what to fill in here." }, { "code": null, "e": 3168, "s": 3134, "text": "Points 1–3 are highlighted below." }, { "code": null, "e": 3537, "s": 3168, "text": "Main================================================================================Lijia Yu {#title} [POINT 1: heading]--------------------------------------------------------------------------------### Currently searching for a PhD student position [POINT 2: sub-heading]TEXT SUMMARY [POINT 3: summary]" }, { "code": null, "e": 3752, "s": 3537, "text": "In case you are not very familiar with the Markdown syntax for section headings, a series of = under a heading is equivalent to # before a heading, and a series of — is equivalent to ##. (Text from Pagedown manual)" }, { "code": null, "e": 3950, "s": 3752, "text": "Point 4: This is divided into 2 parts: one is defining the heading of the section (in this case it is Education) and the other is identifying an icon to represent it (graduation cap for education)." }, { "code": null, "e": 4149, "s": 3950, "text": "This section can be repeated to write about: Work experience, research experience, certifications, educations, etc., and the pattern will be the same. So this chunk of text can be copied repeatedly." }, { "code": null, "e": 4218, "s": 4149, "text": "The icons used in the resume template are from Font Awesome website." }, { "code": null, "e": 4751, "s": 4218, "text": "Point 5: Once you have defined a section, it can further be broken down into a number of subsections. The subsection has 5 fields to fill in of which the first 4 are mandatory fields. First is the title of the sub-section, second is the sub-title of the sub-section, third is the location, fourth is the time period. The time period can be just a year like 2021 or it can be a range like 02/2020–03/2021 or 2020–2021. The fifth field is not mandatory is for supporting text and can be left empty. Points 4 and 5 are explained below:" }, { "code": null, "e": 5328, "s": 4751, "text": "Education {data-icon=graduation-cap} [POINT 4: section heading]--------------------------------------------------------------------------------### Beijing University of Chemical Technology [POINT 5: subsection heading]B.S. in Information and Computing Sciences [POINT 5: subtitle] Beijing, China [POINT 5: location]2010 [POINT 5: time period] Thesis: Dyadic wavelet and its application in edge detection [POINT 5: supporting text]" }, { "code": null, "e": 5446, "s": 5328, "text": "Out of the 4 mandatory fields, only the sub-title, location, and time period fields can be skipped by filling in N/A." }, { "code": null, "e": 5645, "s": 5446, "text": "The fifth field is to add details to your subsections. By default, the text will be published as a single column but the display can be changed to 2-columns by using :::concise block as shown below." }, { "code": null, "e": 5707, "s": 5645, "text": ":::concise- sentence 1- sentence 2- sentence 3- sentence 4:::" }, { "code": null, "e": 5764, "s": 5707, "text": "Now let's move on to the sidebar that covers points 6–8." }, { "code": null, "e": 5899, "s": 5764, "text": "Point 6: By default, a logo is inserted in the template which can be changed by any image just by adding the correct path in the text." }, { "code": null, "e": 6066, "s": 5899, "text": "Aside================================================================================![Lijia Yu](https://avatars1.githubusercontent.com/u/895125?s=400&v=4){width=80%}" }, { "code": null, "e": 6301, "s": 6066, "text": "Point 7: The contact info section is where you can highlight your social media pages or blogs and personal contact info. Again the icons are from Font Awesome webpage. The information in contact info can be added in the following way:" }, { "code": null, "e": 6381, "s": 6301, "text": "- <i class=\"fa fa-github\"></i> [github.com/yulijia](https://github.com/yulijia)" }, { "code": null, "e": 6519, "s": 6381, "text": "Point 8: The skills section is where you can jot down all the skills. If you want to list the skills it can be done in the following way:" }, { "code": null, "e": 6643, "s": 6519, "text": "Skills {#skills}--------------------------------------------------------------------------------- skill 1- skill 2- skill 3" }, { "code": null, "e": 6948, "s": 6643, "text": "Till now we have covered the essential building blocks for creating the resume. The compiled resume will give you an idea of how it will look. If you are satisfied with the current version then you can skip to the end. If you are unsure of the looks of it, then let’s get to the customization part of it." }, { "code": null, "e": 7266, "s": 6948, "text": "At first glance, if you think there is plenty of white space along the borders, or, the sidebar is too thick, or even you think the font style is way off according to your style then you need to customize it. You can even play with the colors of the timelines on the left side and the background color of the sidebar." }, { "code": null, "e": 7384, "s": 7266, "text": "To address all these issues you need to know CSS. If you are a person like me with no background in CSS then read on." }, { "code": null, "e": 7571, "s": 7384, "text": "Page margins: To override a predefined function, an asterisk (* )needs to be added before the function as shown in the below text. This way new margin values for the page can be defined." }, { "code": null, "e": 7733, "s": 7571, "text": "* { /* Override default margins*/ --pagedjs-margin-right: 0.2in; --pagedjs-margin-left: 0.2in; --pagedjs-margin-top: 0.2in; --pagedjs-margin-bottom: 0.2in;}" }, { "code": null, "e": 7938, "s": 7733, "text": "Sidebar width: In the root function, the default value for sidebar width is 15 rem. This value can be changed to get the desired width of the sidebar. For the current case, it has been assigned to 12 rem." }, { "code": null, "e": 7964, "s": 7938, "text": " --sidebar-width: 12rem;" }, { "code": null, "e": 8126, "s": 7964, "text": "Sidebar color: In the root function, the sidebar background color can also be changed. For demonstration purposes, the color is switched from #f2f2f2 to #a2e2e2." }, { "code": null, "e": 8163, "s": 8126, "text": "--sidebar-background-color: #a2e2e2;" }, { "code": null, "e": 8375, "s": 8163, "text": "Color of timeline: The timeline on the left side of the resume consists of vertical lines connecting dots under the same section. Both the thickness and color of the vertical lines can be changed as shown below." }, { "code": null, "e": 8459, "s": 8375, "text": "--decorator-border: 2px solid #a2e2e2; /* change color and thickness of timeline */" }, { "code": null, "e": 8532, "s": 8459, "text": "Further, the background color of the dots can be changed as shown below." }, { "code": null, "e": 8594, "s": 8532, "text": " background-color: #a2e2e2; /* change color timeline dots */" }, { "code": null, "e": 8767, "s": 8594, "text": "Font type: The font type can be changed in the body function by defining the font family. In this example, I changed the font from Open Sans to Roboto both from sans-serif." }, { "code": null, "e": 8843, "s": 8767, "text": "/* Define the font family here */body{ font-family: \"Roboto\", sans-serif;}" }, { "code": null, "e": 8949, "s": 8843, "text": "All the changes to be made for customization are defined in override.css file. The complete code is here:" }, { "code": null, "e": 9420, "s": 8949, "text": "To incorporate all the changes in the CSS file, we can override the existing CSS file completely or certain rules with a new one in the YAML header. This is done by adding the new file name with the CSS extension. The new CSS file created should be kept in the folder with the markdown file. The location of the original CSS file will be ...Resume_demo_files\\paged-0.13\\css\\resume.css . The folder will be created when the markdown file is knit in its default condition." }, { "code": null, "e": 9567, "s": 9420, "text": "output: pagedown::html_resume: css: - override.css # OVERIDE CERTAIN FUNCTIONS OF CSS - resume # DEFAULT FILE" }, { "code": null, "e": 10058, "s": 9567, "text": "You will notice when you knit the markdown file a window will pop up displaying the resume with the Open in Browser option on the top left. On clicking this option it will just open a blank tab on your browser. For the resume to display on the browser tab, one has to change the YAML setting from the default value of FALSE to TRUE. This can be done by setting self_contained: false to self_contained: true. Then the pdf can be generated by printing the displayed resume on the browser tab." }, { "code": null, "e": 10147, "s": 10058, "text": "Another option to create pdf file is to add knit: pagedown::chrome_print to YAML header." }, { "code": null, "e": 10474, "s": 10147, "text": "Now coming to the best part of the resume building where you can automate the data filling. Thanks to Nick Strayer for getting my resume from being just customized to being fully data automated. As always, you need to create the master data CSV files for all the sections of your resume. The master data can be done in 2 ways:" }, { "code": null, "e": 11200, "s": 10474, "text": "CSV files: Create CSV files and keep updating them as per your needs. The CSV files can be made on your personal device or on google sheets. Separate files can be made for work, skills, and contact details.Hybrid approach: If you are in a hurry then you can directly fill in the fields in the markdown file of the resume template and will give the desired output as shown in the default resume template or with the customizations that have been incorporated. And maybe for some cases use the CSV files for adding the data. As I did in my case since I was inclined on using the skill bars to highlight the level of proficiency of my programming skills rather than just add them as a mere text. So I choose the hybrid approach." }, { "code": null, "e": 11407, "s": 11200, "text": "CSV files: Create CSV files and keep updating them as per your needs. The CSV files can be made on your personal device or on google sheets. Separate files can be made for work, skills, and contact details." }, { "code": null, "e": 11927, "s": 11407, "text": "Hybrid approach: If you are in a hurry then you can directly fill in the fields in the markdown file of the resume template and will give the desired output as shown in the default resume template or with the customizations that have been incorporated. And maybe for some cases use the CSV files for adding the data. As I did in my case since I was inclined on using the skill bars to highlight the level of proficiency of my programming skills rather than just add them as a mere text. So I choose the hybrid approach." }, { "code": null, "e": 12169, "s": 11927, "text": "So let me demonstrate to you what it means to automate resume building by using the text from the default resume template. The first step is to create the CSV files. Here is the example for the CSV file details of work and education history." }, { "code": null, "e": 12632, "s": 12169, "text": "Once you have created the files you can use the resume template, link at the end. There are two R files associated with the template. The gather_data.R looks for the data source if it has to read from google sheets or CSV files. The preference for this is indicated in the markdown file. The parsing_functions.R glues the relevant information in the markdown file when the functions related to education, work history, contact info, skills, etc. are called upon." }, { "code": null, "e": 12764, "s": 12632, "text": "If the color of the skill bar needs to be changed then refer the parsing_functions.R file and look for build_skill_bars() function." }, { "code": null, "e": 13236, "s": 12764, "text": "In this article, I showed step by step to customize the default resume template from the pagedown package. This was achieved by breaking the workflow of the template. In the first section, the basic building blocks of the template were explained and the regions that needed attention. The second part focused on template customization finding the possible pitfalls and customizing them according to my needs. The third section was to generate a pdf version of the resume." }, { "code": null, "e": 13475, "s": 13236, "text": "The fourth or the last section was on automating the data filling in the resume based on Nick Strayer’s work. In this section, I tried explaining the basic features that needed to be focused on to get the resume up and running in no time." }, { "code": null, "e": 13568, "s": 13475, "text": "This way you can showcase your data skills and data portfolio powered by R pagedown package." }, { "code": null, "e": 13592, "s": 13568, "text": "Customized resume: Link" }, { "code": null, "e": 13632, "s": 13592, "text": "Customized resume with automation: Link" }, { "code": null, "e": 13761, "s": 13632, "text": "https://livefreeordichotomize.com/2019/09/04/building_a_data_driven_cv_with_r/https://pagedown.rbind.io/https://fontawesome.com/" }, { "code": null, "e": 13840, "s": 13761, "text": "https://livefreeordichotomize.com/2019/09/04/building_a_data_driven_cv_with_r/" }, { "code": null, "e": 13867, "s": 13840, "text": "https://pagedown.rbind.io/" }, { "code": null, "e": 13892, "s": 13867, "text": "https://fontawesome.com/" } ]
Kotlin Break and Continue
The break statement is used to jump out of a loop. This example jumps out of the loop when i is equal to 4: var i = 0 while (i < 10) { println(i) i++ if (i == 4) { break } } The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop. This example skips the value of 4: var i = 0 while (i < 10) { if (i == 4) { i++ continue } println(i) i++} 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": 52, "s": 0, "text": "The break statement is used to jump out of a \nloop." }, { "code": null, "e": 109, "s": 52, "text": "This example jumps out of the loop when i is equal to 4:" }, { "code": null, "e": 187, "s": 109, "text": "var i = 0\nwhile (i < 10) {\n println(i)\n i++\n if (i == 4) {\n break\n }\n}" }, { "code": null, "e": 330, "s": 187, "text": "The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop." }, { "code": null, "e": 365, "s": 330, "text": "This example skips the value of 4:" }, { "code": null, "e": 453, "s": 365, "text": "var i = 0\nwhile (i < 10) {\n if (i == 4) {\n i++\n continue\n }\n println(i)\n i++}" }, { "code": null, "e": 486, "s": 453, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 528, "s": 486, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 635, "s": 528, "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": 654, "s": 635, "text": "help@w3schools.com" } ]
BFS for Disconnected Graph in C++
Disconnected graph is a Graph in which one or more nodes are not the endpoints of the graph i.e. they are not connected. A disconnected graph... Now, the Simple BFS is applicable only when the graph is connected i.e. all vertices of the graph are accessible from one node of the graph. in the above disconnected graph technique is not possible as a few laws are not accessible so the following changed program would be better for performing breadth first search in a disconnected graph. #include<bits/stdc++.h> using namespace std; void insertnode(vector<int> adj[], int u, int v) { adj[u].push_back(v); } void breathFirstSearch(int u, vector<int> adj[], vector<bool> &visited) { list<int> q; visited[u] = true; q.push_back(u); while(!q.empty()) { u = q.front(); cout << u << " "; q.pop_front(); for (int i = 0; i != adj[u].size(); ++i) { if (!visited[adj[u][i]]) { visited[adj[u][i]] = true; q.push_back(adj[u][i]); } } } } void BFSdisc(vector<int> adj[], int V) { vector<bool> visited(V, false); for (int u=0; u<V; u++) if (visited[u] == false) breathFirstSearch(u, adj, visited); } int main() { int V = 5; vector<int> adj[V]; insertnode(adj, 0, 23); insertnode(adj, 0, 4); insertnode(adj, 1, 2); insertnode(adj, 1, 3); insertnode(adj, 1, 4); insertnode(adj, 2, 3); insertnode(adj, 3, 4); BFSdisc(adj, V); return 0; } 0 4 1 2 3
[ { "code": null, "e": 1183, "s": 1062, "text": "Disconnected graph is a Graph in which one or more nodes are not the endpoints of the graph i.e. they are not connected." }, { "code": null, "e": 1207, "s": 1183, "text": "A disconnected graph..." }, { "code": null, "e": 1549, "s": 1207, "text": "Now, the Simple BFS is applicable only when the graph is connected i.e. all vertices of the graph are accessible from one node of the graph. in the above disconnected graph technique is not possible as a few laws are not accessible so the following changed program would be better for performing breadth first search in a disconnected graph." }, { "code": null, "e": 2517, "s": 1549, "text": "#include<bits/stdc++.h>\nusing namespace std;\nvoid insertnode(vector<int> adj[], int u, int v) {\n adj[u].push_back(v);\n}\nvoid breathFirstSearch(int u, vector<int> adj[], vector<bool> &visited) {\n list<int> q;\n visited[u] = true;\n q.push_back(u);\n while(!q.empty()) {\n u = q.front();\n cout << u << \" \";\n q.pop_front();\n for (int i = 0; i != adj[u].size(); ++i) {\n if (!visited[adj[u][i]]) {\n visited[adj[u][i]] = true;\n q.push_back(adj[u][i]);\n }\n }\n }\n}\nvoid BFSdisc(vector<int> adj[], int V) {\n vector<bool> visited(V, false);\n for (int u=0; u<V; u++)\n if (visited[u] == false)\n breathFirstSearch(u, adj, visited);\n}\nint main() {\n int V = 5;\n vector<int> adj[V];\n insertnode(adj, 0, 23);\n insertnode(adj, 0, 4);\n insertnode(adj, 1, 2);\n insertnode(adj, 1, 3);\n insertnode(adj, 1, 4);\n insertnode(adj, 2, 3);\n insertnode(adj, 3, 4);\n BFSdisc(adj, V);\n return 0;\n}" }, { "code": null, "e": 2527, "s": 2517, "text": "0 4 1 2 3" } ]
Count the number of contiguous increasing and decreasing subsequences in a sequence - GeeksforGeeks
13 May, 2021 For a given distinct integer sequence of size N, the task is to count the number of contiguous increasing subsequence and contiguous decreasing subsequence in this sequence.Examples: Input: arr[] = { 80, 50, 60, 70, 40 } Output: 1 2 Explanation: The only one increasing subsequence is (50, 60, 70) and two decreasing subsequences are (80, 50) and (70, 40).Input: arr[] = { 10, 20, 23, 12, 5, 4, 61, 67, 87, 9 } Output: 2 2 Explanation: The increasing subsequences are (10, 20, 23) and (4, 61, 67, 87) whereas the decreasing subsequences are (23, 12, 5, 4) and (87, 9). Approach: The idea behind solving this problem is to use two arrays which keeps the track of increasing or decreasing indices based on next elements. Define two arrays max and min, such that the index of an element of the array is stored. For the first element of the array, if it is greater than its next element, it’s index is stored in the max array, else it is stored in the min array and so on.For the last element of the array, if it is greater than the previous element, it’s index is stored in the max array, else it is stored in min array.After this, all the maximal contiguous increasing subsequences are matched from (min to max), while all the maximal contiguous decreasing subsequences are matched from (max to min).Finally, if the index of the first element of array is stored in the first index of min array, then the number of maximal contiguous increasing subsequence possible is size of min array and maximal contiguous decreasing subsequences possible is (size of max array – 1).If the index of the first element of the array is stored in the first index of the max array, then the number of maximal contiguous increasing subsequence possible is(size of the max array -1) and maximal contiguous decreasing subsequences possible is the size of min array. Define two arrays max and min, such that the index of an element of the array is stored. For the first element of the array, if it is greater than its next element, it’s index is stored in the max array, else it is stored in the min array and so on. For the last element of the array, if it is greater than the previous element, it’s index is stored in the max array, else it is stored in min array. After this, all the maximal contiguous increasing subsequences are matched from (min to max), while all the maximal contiguous decreasing subsequences are matched from (max to min). Finally, if the index of the first element of array is stored in the first index of min array, then the number of maximal contiguous increasing subsequence possible is size of min array and maximal contiguous decreasing subsequences possible is (size of max array – 1). If the index of the first element of the array is stored in the first index of the max array, then the number of maximal contiguous increasing subsequence possible is(size of the max array -1) and maximal contiguous decreasing subsequences possible is the size of min array. Below is the implementation of the above approach. C++ Java Python3 C# Javascript // C++ implementation of the above approach. #include <bits/stdc++.h>using namespace std; // Function to count the number of maximal contiguous// increasing and decreasing subsequencesvoid numOfSubseq(int arr[], int n) { int i, inc_count, dec_count; int max[n], min[n]; // k2, k1 are used to store the // count of max and min array int k1 = 0, k2 = 0; // Comparison to store the index of // first element of array if (arr[0] < arr[1]) min[k1++] = 0; else max[k2++] = 0; // Comparison to store the index // from second to second last // index of array for (i = 1; i < n - 1; i++) { if (arr[i] < arr[i - 1] && arr[i] < arr[i + 1]) min[k1++] = i; if (arr[i] > arr[i - 1] && arr[i] > arr[i + 1]) max[k2++] = i; } // Comparison to store the index // of last element of array if (arr[n - 1] < arr[n - 2]) min[k1++] = n - 1; else max[k2++] = n - 1; // Count of number of maximal contiguous // increasing and decreasing subsequences if (min[0] == 0) { inc_count = k2; dec_count = k1 - 1; } else { inc_count = k2 - 1; dec_count = k1; } cout << "Increasing Subsequence Count: " << inc_count << "\n"; cout << "Decreasing Subsequence Count: " << dec_count << "\n";} // Driver program to test aboveint main(){ int arr[] = { 12, 8, 11, 13, 10, 15, 14, 16, 20 }; int n = sizeof(arr) / sizeof(arr[0]); numOfSubseq(arr, n); return 0;} // Java implementation of the above approach.class GFG{ // Function to count the number of maximal contiguous // increasing and decreasing subsequences static void numOfSubseq(int arr[], int n) { int i, inc_count, dec_count; int max[] = new int[n]; int min[] = new int[n]; // k2, k1 are used to store the // count of max and min array int k1 = 0, k2 = 0; // Comparison to store the index of // first element of array if (arr[0] < arr[1]) min[k1++] = 0; else max[k2++] = 0; // Comparison to store the index // from second to second last // index of array for (i = 1; i < n - 1; i++) { if (arr[i] < arr[i - 1] && arr[i] < arr[i + 1]) min[k1++] = i; if (arr[i] > arr[i - 1] && arr[i] > arr[i + 1]) max[k2++] = i; } // Comparison to store the index // of last element of array if (arr[n - 1] < arr[n - 2]) min[k1++] = n - 1; else max[k2++] = n - 1; // Count of number of maximal contiguous // increasing and decreasing subsequences if (min[0] == 0) { inc_count = k2; dec_count = k1 - 1; } else { inc_count = k2 - 1; dec_count = k1; } System.out.println("Increasing Subsequence" + " Count: " + inc_count) ; System.out.println("Decreasing Subsequence" + " Count: " + dec_count) ; } // Driver code public static void main (String[] args) { int arr[] = { 12, 8, 11, 13, 10, 15, 14, 16, 20 }; int n = arr.length; numOfSubseq(arr, n); }} // This code is contributed by AnkitRai01 # Python3 implementation of the above approach. # Function to count the number of maximal contiguous# increasing and decreasing subsequencesdef numOfSubseq(arr, n): i, inc_count, dec_count = 0, 0, 0; max = [0]*n; min = [0]*n; # k2, k1 are used to store the # count of max and min array k1 = 0; k2 = 0; # Comparison to store the index of # first element of array if (arr[0] < arr[1]): min[k1] = 0; k1 += 1; else: max[k2] = 0; k2 += 1; # Comparison to store the index # from second to second last # index of array for i in range(1, n-1): if (arr[i] < arr[i - 1] and arr[i] < arr[i + 1]): min[k1] = i; k1 += 1; if (arr[i] > arr[i - 1] and arr[i] > arr[i + 1]): max[k2] = i; k2 += 1; # Comparison to store the index # of last element of array if (arr[n - 1] < arr[n - 2]): min[k1] = n - 1; k1 += 1; else: max[k2] = n - 1; k2 += 1; # Count of number of maximal contiguous # increasing and decreasing subsequences if (min[0] == 0): inc_count = k2; dec_count = k1 - 1; else: inc_count = k2 - 1; dec_count = k1; print("Increasing Subsequence Count: " , inc_count); print("Decreasing Subsequence Count: " , dec_count); # Driver codeif __name__ == '__main__': arr = [ 12, 8, 11, 13, 10, 15, 14, 16, 20 ]; n = len(arr); numOfSubseq(arr, n); # This code is contributed by 29AjayKumar // C# implementation of the above approach.using System; class GFG{ // Function to count the number of maximal contiguous// increasing and decreasing subsequencesstatic void numOfSubseq(int []arr, int n) { int i, inc_count, dec_count; int []max = new int[n]; int []min = new int[n]; // k2, k1 are used to store the // count of max and min array int k1 = 0, k2 = 0; // Comparison to store the index of // first element of array if (arr[0] < arr[1]) min[k1++] = 0; else max[k2++] = 0; // Comparison to store the index // from second to second last // index of array for (i = 1; i < n - 1; i++) { if (arr[i] < arr[i - 1] && arr[i] < arr[i + 1]) min[k1++] = i; if (arr[i] > arr[i - 1] && arr[i] > arr[i + 1]) max[k2++] = i; } // Comparison to store the index // of last element of array if (arr[n - 1] < arr[n - 2]) min[k1++] = n - 1; else max[k2++] = n - 1; // Count of number of maximal contiguous // increasing and decreasing subsequences if (min[0] == 0) { inc_count = k2; dec_count = k1 - 1; } else { inc_count = k2 - 1; dec_count = k1; } Console.WriteLine("Increasing Subsequence" + " Count: " + inc_count) ; Console.WriteLine("Decreasing Subsequence" + " Count: " + dec_count) ;} // Driver codestatic public void Main (){ int []arr = { 12, 8, 11, 13, 10, 15, 14, 16, 20 }; int n = arr.Length; numOfSubseq(arr, n);}} // This code is contributed by ajit. <script> // Javascript implementation of the above approach. // Function to count the number of maximal contiguous // increasing and decreasing subsequences function numOfSubseq(arr, n) { let i, inc_count, dec_count; let max = new Array(n); max.fill(0); let min = new Array(n); min.fill(0); // k2, k1 are used to store the // count of max and min array let k1 = 0, k2 = 0; // Comparison to store the index of // first element of array if (arr[0] < arr[1]) min[k1++] = 0; else max[k2++] = 0; // Comparison to store the index // from second to second last // index of array for (i = 1; i < n - 1; i++) { if (arr[i] < arr[i - 1] && arr[i] < arr[i + 1]) min[k1++] = i; if (arr[i] > arr[i - 1] && arr[i] > arr[i + 1]) max[k2++] = i; } // Comparison to store the index // of last element of array if (arr[n - 1] < arr[n - 2]) min[k1++] = n - 1; else max[k2++] = n - 1; // Count of number of maximal contiguous // increasing and decreasing subsequences if (min[0] == 0) { inc_count = k2; dec_count = k1 - 1; } else { inc_count = k2 - 1; dec_count = k1; } document.write("Increasing Subsequence" + " Count: " + inc_count + "</br>") ; document.write("Decreasing Subsequence" + " Count: " + dec_count + "</br>") ; } let arr = [ 12, 8, 11, 13, 10, 15, 14, 16, 20 ]; let n = arr.length; numOfSubseq(arr, n); // This code is contributed by suresh07.</script> Increasing Subsequence Count: 3 Decreasing Subsequence Count: 3 Time Complexity: O(N) ankthon jit_t 29AjayKumar suresh07 subsequence Arrays Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java Linear Search Linked List vs Array Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Python | Using 2D arrays/lists the right way Search an element in a sorted and rotated array
[ { "code": null, "e": 26563, "s": 26535, "text": "\n13 May, 2021" }, { "code": null, "e": 26748, "s": 26563, "text": "For a given distinct integer sequence of size N, the task is to count the number of contiguous increasing subsequence and contiguous decreasing subsequence in this sequence.Examples: " }, { "code": null, "e": 27136, "s": 26748, "text": "Input: arr[] = { 80, 50, 60, 70, 40 } Output: 1 2 Explanation: The only one increasing subsequence is (50, 60, 70) and two decreasing subsequences are (80, 50) and (70, 40).Input: arr[] = { 10, 20, 23, 12, 5, 4, 61, 67, 87, 9 } Output: 2 2 Explanation: The increasing subsequences are (10, 20, 23) and (4, 61, 67, 87) whereas the decreasing subsequences are (23, 12, 5, 4) and (87, 9). " }, { "code": null, "e": 27290, "s": 27138, "text": "Approach: The idea behind solving this problem is to use two arrays which keeps the track of increasing or decreasing indices based on next elements. " }, { "code": null, "e": 28413, "s": 27290, "text": "Define two arrays max and min, such that the index of an element of the array is stored. For the first element of the array, if it is greater than its next element, it’s index is stored in the max array, else it is stored in the min array and so on.For the last element of the array, if it is greater than the previous element, it’s index is stored in the max array, else it is stored in min array.After this, all the maximal contiguous increasing subsequences are matched from (min to max), while all the maximal contiguous decreasing subsequences are matched from (max to min).Finally, if the index of the first element of array is stored in the first index of min array, then the number of maximal contiguous increasing subsequence possible is size of min array and maximal contiguous decreasing subsequences possible is (size of max array – 1).If the index of the first element of the array is stored in the first index of the max array, then the number of maximal contiguous increasing subsequence possible is(size of the max array -1) and maximal contiguous decreasing subsequences possible is the size of min array." }, { "code": null, "e": 28663, "s": 28413, "text": "Define two arrays max and min, such that the index of an element of the array is stored. For the first element of the array, if it is greater than its next element, it’s index is stored in the max array, else it is stored in the min array and so on." }, { "code": null, "e": 28813, "s": 28663, "text": "For the last element of the array, if it is greater than the previous element, it’s index is stored in the max array, else it is stored in min array." }, { "code": null, "e": 28995, "s": 28813, "text": "After this, all the maximal contiguous increasing subsequences are matched from (min to max), while all the maximal contiguous decreasing subsequences are matched from (max to min)." }, { "code": null, "e": 29265, "s": 28995, "text": "Finally, if the index of the first element of array is stored in the first index of min array, then the number of maximal contiguous increasing subsequence possible is size of min array and maximal contiguous decreasing subsequences possible is (size of max array – 1)." }, { "code": null, "e": 29540, "s": 29265, "text": "If the index of the first element of the array is stored in the first index of the max array, then the number of maximal contiguous increasing subsequence possible is(size of the max array -1) and maximal contiguous decreasing subsequences possible is the size of min array." }, { "code": null, "e": 29593, "s": 29540, "text": "Below is the implementation of the above approach. " }, { "code": null, "e": 29597, "s": 29593, "text": "C++" }, { "code": null, "e": 29602, "s": 29597, "text": "Java" }, { "code": null, "e": 29610, "s": 29602, "text": "Python3" }, { "code": null, "e": 29613, "s": 29610, "text": "C#" }, { "code": null, "e": 29624, "s": 29613, "text": "Javascript" }, { "code": "// C++ implementation of the above approach. #include <bits/stdc++.h>using namespace std; // Function to count the number of maximal contiguous// increasing and decreasing subsequencesvoid numOfSubseq(int arr[], int n) { int i, inc_count, dec_count; int max[n], min[n]; // k2, k1 are used to store the // count of max and min array int k1 = 0, k2 = 0; // Comparison to store the index of // first element of array if (arr[0] < arr[1]) min[k1++] = 0; else max[k2++] = 0; // Comparison to store the index // from second to second last // index of array for (i = 1; i < n - 1; i++) { if (arr[i] < arr[i - 1] && arr[i] < arr[i + 1]) min[k1++] = i; if (arr[i] > arr[i - 1] && arr[i] > arr[i + 1]) max[k2++] = i; } // Comparison to store the index // of last element of array if (arr[n - 1] < arr[n - 2]) min[k1++] = n - 1; else max[k2++] = n - 1; // Count of number of maximal contiguous // increasing and decreasing subsequences if (min[0] == 0) { inc_count = k2; dec_count = k1 - 1; } else { inc_count = k2 - 1; dec_count = k1; } cout << \"Increasing Subsequence Count: \" << inc_count << \"\\n\"; cout << \"Decreasing Subsequence Count: \" << dec_count << \"\\n\";} // Driver program to test aboveint main(){ int arr[] = { 12, 8, 11, 13, 10, 15, 14, 16, 20 }; int n = sizeof(arr) / sizeof(arr[0]); numOfSubseq(arr, n); return 0;}", "e": 31171, "s": 29624, "text": null }, { "code": "// Java implementation of the above approach.class GFG{ // Function to count the number of maximal contiguous // increasing and decreasing subsequences static void numOfSubseq(int arr[], int n) { int i, inc_count, dec_count; int max[] = new int[n]; int min[] = new int[n]; // k2, k1 are used to store the // count of max and min array int k1 = 0, k2 = 0; // Comparison to store the index of // first element of array if (arr[0] < arr[1]) min[k1++] = 0; else max[k2++] = 0; // Comparison to store the index // from second to second last // index of array for (i = 1; i < n - 1; i++) { if (arr[i] < arr[i - 1] && arr[i] < arr[i + 1]) min[k1++] = i; if (arr[i] > arr[i - 1] && arr[i] > arr[i + 1]) max[k2++] = i; } // Comparison to store the index // of last element of array if (arr[n - 1] < arr[n - 2]) min[k1++] = n - 1; else max[k2++] = n - 1; // Count of number of maximal contiguous // increasing and decreasing subsequences if (min[0] == 0) { inc_count = k2; dec_count = k1 - 1; } else { inc_count = k2 - 1; dec_count = k1; } System.out.println(\"Increasing Subsequence\" + \" Count: \" + inc_count) ; System.out.println(\"Decreasing Subsequence\" + \" Count: \" + dec_count) ; } // Driver code public static void main (String[] args) { int arr[] = { 12, 8, 11, 13, 10, 15, 14, 16, 20 }; int n = arr.length; numOfSubseq(arr, n); }} // This code is contributed by AnkitRai01", "e": 33083, "s": 31171, "text": null }, { "code": "# Python3 implementation of the above approach. # Function to count the number of maximal contiguous# increasing and decreasing subsequencesdef numOfSubseq(arr, n): i, inc_count, dec_count = 0, 0, 0; max = [0]*n; min = [0]*n; # k2, k1 are used to store the # count of max and min array k1 = 0; k2 = 0; # Comparison to store the index of # first element of array if (arr[0] < arr[1]): min[k1] = 0; k1 += 1; else: max[k2] = 0; k2 += 1; # Comparison to store the index # from second to second last # index of array for i in range(1, n-1): if (arr[i] < arr[i - 1] and arr[i] < arr[i + 1]): min[k1] = i; k1 += 1; if (arr[i] > arr[i - 1] and arr[i] > arr[i + 1]): max[k2] = i; k2 += 1; # Comparison to store the index # of last element of array if (arr[n - 1] < arr[n - 2]): min[k1] = n - 1; k1 += 1; else: max[k2] = n - 1; k2 += 1; # Count of number of maximal contiguous # increasing and decreasing subsequences if (min[0] == 0): inc_count = k2; dec_count = k1 - 1; else: inc_count = k2 - 1; dec_count = k1; print(\"Increasing Subsequence Count: \" , inc_count); print(\"Decreasing Subsequence Count: \" , dec_count); # Driver codeif __name__ == '__main__': arr = [ 12, 8, 11, 13, 10, 15, 14, 16, 20 ]; n = len(arr); numOfSubseq(arr, n); # This code is contributed by 29AjayKumar", "e": 34608, "s": 33083, "text": null }, { "code": "// C# implementation of the above approach.using System; class GFG{ // Function to count the number of maximal contiguous// increasing and decreasing subsequencesstatic void numOfSubseq(int []arr, int n) { int i, inc_count, dec_count; int []max = new int[n]; int []min = new int[n]; // k2, k1 are used to store the // count of max and min array int k1 = 0, k2 = 0; // Comparison to store the index of // first element of array if (arr[0] < arr[1]) min[k1++] = 0; else max[k2++] = 0; // Comparison to store the index // from second to second last // index of array for (i = 1; i < n - 1; i++) { if (arr[i] < arr[i - 1] && arr[i] < arr[i + 1]) min[k1++] = i; if (arr[i] > arr[i - 1] && arr[i] > arr[i + 1]) max[k2++] = i; } // Comparison to store the index // of last element of array if (arr[n - 1] < arr[n - 2]) min[k1++] = n - 1; else max[k2++] = n - 1; // Count of number of maximal contiguous // increasing and decreasing subsequences if (min[0] == 0) { inc_count = k2; dec_count = k1 - 1; } else { inc_count = k2 - 1; dec_count = k1; } Console.WriteLine(\"Increasing Subsequence\" + \" Count: \" + inc_count) ; Console.WriteLine(\"Decreasing Subsequence\" + \" Count: \" + dec_count) ;} // Driver codestatic public void Main (){ int []arr = { 12, 8, 11, 13, 10, 15, 14, 16, 20 }; int n = arr.Length; numOfSubseq(arr, n);}} // This code is contributed by ajit.", "e": 36243, "s": 34608, "text": null }, { "code": "<script> // Javascript implementation of the above approach. // Function to count the number of maximal contiguous // increasing and decreasing subsequences function numOfSubseq(arr, n) { let i, inc_count, dec_count; let max = new Array(n); max.fill(0); let min = new Array(n); min.fill(0); // k2, k1 are used to store the // count of max and min array let k1 = 0, k2 = 0; // Comparison to store the index of // first element of array if (arr[0] < arr[1]) min[k1++] = 0; else max[k2++] = 0; // Comparison to store the index // from second to second last // index of array for (i = 1; i < n - 1; i++) { if (arr[i] < arr[i - 1] && arr[i] < arr[i + 1]) min[k1++] = i; if (arr[i] > arr[i - 1] && arr[i] > arr[i + 1]) max[k2++] = i; } // Comparison to store the index // of last element of array if (arr[n - 1] < arr[n - 2]) min[k1++] = n - 1; else max[k2++] = n - 1; // Count of number of maximal contiguous // increasing and decreasing subsequences if (min[0] == 0) { inc_count = k2; dec_count = k1 - 1; } else { inc_count = k2 - 1; dec_count = k1; } document.write(\"Increasing Subsequence\" + \" Count: \" + inc_count + \"</br>\") ; document.write(\"Decreasing Subsequence\" + \" Count: \" + dec_count + \"</br>\") ; } let arr = [ 12, 8, 11, 13, 10, 15, 14, 16, 20 ]; let n = arr.length; numOfSubseq(arr, n); // This code is contributed by suresh07.</script>", "e": 38083, "s": 36243, "text": null }, { "code": null, "e": 38147, "s": 38083, "text": "Increasing Subsequence Count: 3\nDecreasing Subsequence Count: 3" }, { "code": null, "e": 38172, "s": 38149, "text": "Time Complexity: O(N) " }, { "code": null, "e": 38180, "s": 38172, "text": "ankthon" }, { "code": null, "e": 38186, "s": 38180, "text": "jit_t" }, { "code": null, "e": 38198, "s": 38186, "text": "29AjayKumar" }, { "code": null, "e": 38207, "s": 38198, "text": "suresh07" }, { "code": null, "e": 38219, "s": 38207, "text": "subsequence" }, { "code": null, "e": 38226, "s": 38219, "text": "Arrays" }, { "code": null, "e": 38233, "s": 38226, "text": "Arrays" }, { "code": null, "e": 38331, "s": 38233, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38399, "s": 38331, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 38443, "s": 38399, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 38491, "s": 38443, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 38514, "s": 38491, "text": "Introduction to Arrays" }, { "code": null, "e": 38546, "s": 38514, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 38560, "s": 38546, "text": "Linear Search" }, { "code": null, "e": 38581, "s": 38560, "text": "Linked List vs Array" }, { "code": null, "e": 38666, "s": 38581, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 38711, "s": 38666, "text": "Python | Using 2D arrays/lists the right way" } ]
HBase - Create Data
This chapter demonstrates how to create data in an HBase table. To create data in an HBase table, the following commands and methods are used: put command, put command, add() method of Put class, and add() method of Put class, and put() method of HTable class. put() method of HTable class. As an example, we are going to create the following table in HBase. Using put command, you can insert rows into a table. Its syntax is as follows: put ’<table name>’,’row1’,’<colfamily:colname>’,’<value>’ Let us insert the first row values into the emp table as shown below. hbase(main):005:0> put 'emp','1','personal data:name','raju' 0 row(s) in 0.6600 seconds hbase(main):006:0> put 'emp','1','personal data:city','hyderabad' 0 row(s) in 0.0410 seconds hbase(main):007:0> put 'emp','1','professional data:designation','manager' 0 row(s) in 0.0240 seconds hbase(main):007:0> put 'emp','1','professional data:salary','50000' 0 row(s) in 0.0240 seconds Insert the remaining rows using the put command in the same way. If you insert the whole table, you will get the following output. hbase(main):022:0> scan 'emp' ROW COLUMN+CELL 1 column=personal data:city, timestamp=1417524216501, value=hyderabad 1 column=personal data:name, timestamp=1417524185058, value=ramu 1 column=professional data:designation, timestamp=1417524232601, value=manager 1 column=professional data:salary, timestamp=1417524244109, value=50000 2 column=personal data:city, timestamp=1417524574905, value=chennai 2 column=personal data:name, timestamp=1417524556125, value=ravi 2 column=professional data:designation, timestamp=1417524592204, value=sr:engg 2 column=professional data:salary, timestamp=1417524604221, value=30000 3 column=personal data:city, timestamp=1417524681780, value=delhi 3 column=personal data:name, timestamp=1417524672067, value=rajesh 3 column=professional data:designation, timestamp=1417524693187, value=jr:engg 3 column=professional data:salary, timestamp=1417524702514, value=25000 You can insert data into Hbase using the add() method of the Put class. You can save it using the put() method of the HTable class. These classes belong to the org.apache.hadoop.hbase.client package. Below given are the steps to create data in a Table of HBase. The Configuration class adds HBase configuration files to its object. You can create a configuration object using the create() method of the HbaseConfiguration class as shown below. Configuration conf = HbaseConfiguration.create(); You have a class called HTable, an implementation of Table in HBase. This class is used to communicate with a single HBase table. While instantiating this class, it accepts configuration object and table name as parameters. You can instantiate HTable class as shown below. HTable hTable = new HTable(conf, tableName); To insert data into an HBase table, the add() method and its variants are used. This method belongs to Put, therefore instantiate the put class. This class requires the row name you want to insert the data into, in string format. You can instantiate the Put class as shown below. Put p = new Put(Bytes.toBytes("row1")); The add() method of Put class is used to insert data. It requires 3 byte arrays representing column family, column qualifier (column name), and the value to be inserted, respectively. Insert data into the HBase table using the add() method as shown below. p.add(Bytes.toBytes("coloumn family "), Bytes.toBytes("column name"),Bytes.toBytes("value")); After inserting the required rows, save the changes by adding the put instance to the put() method of HTable class as shown below. hTable.put(p); After creating data in the HBase Table, close the HTable instance using the close() method as shown below. hTable.close(); Given below is the complete program to create data in HBase Table. import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.util.Bytes; public class InsertData{ public static void main(String[] args) throws IOException { // Instantiating Configuration class Configuration config = HBaseConfiguration.create(); // Instantiating HTable class HTable hTable = new HTable(config, "emp"); // Instantiating Put class // accepts a row name. Put p = new Put(Bytes.toBytes("row1")); // adding values using add() method // accepts column family name, qualifier/row name ,value p.add(Bytes.toBytes("personal"), Bytes.toBytes("name"),Bytes.toBytes("raju")); p.add(Bytes.toBytes("personal"), Bytes.toBytes("city"),Bytes.toBytes("hyderabad")); p.add(Bytes.toBytes("professional"),Bytes.toBytes("designation"), Bytes.toBytes("manager")); p.add(Bytes.toBytes("professional"),Bytes.toBytes("salary"), Bytes.toBytes("50000")); // Saving the put Instance to the HTable. hTable.put(p); System.out.println("data inserted"); // closing HTable hTable.close(); } } Compile and execute the above program as shown below. $javac InsertData.java $java InsertData The following should be the output: data inserted Print Add Notes Bookmark this page
[ { "code": null, "e": 2180, "s": 2037, "text": "This chapter demonstrates how to create data in an HBase table. To create data in an HBase table, the following commands and methods are used:" }, { "code": null, "e": 2193, "s": 2180, "text": "put command," }, { "code": null, "e": 2206, "s": 2193, "text": "put command," }, { "code": null, "e": 2237, "s": 2206, "text": "add() method of Put class, and" }, { "code": null, "e": 2268, "s": 2237, "text": "add() method of Put class, and" }, { "code": null, "e": 2298, "s": 2268, "text": "put() method of HTable class." }, { "code": null, "e": 2328, "s": 2298, "text": "put() method of HTable class." }, { "code": null, "e": 2396, "s": 2328, "text": "As an example, we are going to create the following table in HBase." }, { "code": null, "e": 2475, "s": 2396, "text": "Using put command, you can insert rows into a table. Its syntax is as follows:" }, { "code": null, "e": 2534, "s": 2475, "text": "put ’<table name>’,’row1’,’<colfamily:colname>’,’<value>’\n" }, { "code": null, "e": 2604, "s": 2534, "text": "Let us insert the first row values into the emp table as shown below." }, { "code": null, "e": 2983, "s": 2604, "text": "hbase(main):005:0> put 'emp','1','personal data:name','raju'\n0 row(s) in 0.6600 seconds\nhbase(main):006:0> put 'emp','1','personal data:city','hyderabad'\n0 row(s) in 0.0410 seconds\nhbase(main):007:0> put 'emp','1','professional\ndata:designation','manager'\n0 row(s) in 0.0240 seconds\nhbase(main):007:0> put 'emp','1','professional data:salary','50000'\n0 row(s) in 0.0240 seconds\n" }, { "code": null, "e": 3114, "s": 2983, "text": "Insert the remaining rows using the put command in the same way. If you insert the whole table, you will get the following output." }, { "code": null, "e": 4061, "s": 3114, "text": "hbase(main):022:0> scan 'emp'\n\n ROW COLUMN+CELL\n1 column=personal data:city, timestamp=1417524216501, value=hyderabad\n\n1 column=personal data:name, timestamp=1417524185058, value=ramu\n\n1 column=professional data:designation, timestamp=1417524232601,\n\n value=manager\n \n1 column=professional data:salary, timestamp=1417524244109, value=50000\n\n2 column=personal data:city, timestamp=1417524574905, value=chennai\n\n2 column=personal data:name, timestamp=1417524556125, value=ravi\n\n2 column=professional data:designation, timestamp=1417524592204,\n\n value=sr:engg\n \n2 column=professional data:salary, timestamp=1417524604221, value=30000\n\n3 column=personal data:city, timestamp=1417524681780, value=delhi\n\n3 column=personal data:name, timestamp=1417524672067, value=rajesh\n\n3 column=professional data:designation, timestamp=1417524693187,\n\nvalue=jr:engg\n3 column=professional data:salary, timestamp=1417524702514,\n\nvalue=25000 \n" }, { "code": null, "e": 4323, "s": 4061, "text": "You can insert data into Hbase using the add() method of the Put class. You can save it using the put() method of the HTable class. These classes belong to the org.apache.hadoop.hbase.client package. Below given are the steps to create data in a Table of HBase." }, { "code": null, "e": 4505, "s": 4323, "text": "The Configuration class adds HBase configuration files to its object. You can create a configuration object using the create() method of the HbaseConfiguration class as shown below." }, { "code": null, "e": 4556, "s": 4505, "text": "Configuration conf = HbaseConfiguration.create();\n" }, { "code": null, "e": 4829, "s": 4556, "text": "You have a class called HTable, an implementation of Table in HBase. This class is used to communicate with a single HBase table. While instantiating this class, it accepts configuration object and table name as parameters. You can instantiate HTable class as shown below." }, { "code": null, "e": 4875, "s": 4829, "text": "HTable hTable = new HTable(conf, tableName);\n" }, { "code": null, "e": 5155, "s": 4875, "text": "To insert data into an HBase table, the add() method and its variants are used. This method belongs to Put, therefore instantiate the put class. This class requires the row name you want to insert the data into, in string format. You can instantiate the Put class as shown below." }, { "code": null, "e": 5196, "s": 5155, "text": "Put p = new Put(Bytes.toBytes(\"row1\"));\n" }, { "code": null, "e": 5452, "s": 5196, "text": "The add() method of Put class is used to insert data. It requires 3 byte arrays representing column family, column qualifier (column name), and the value to be inserted, respectively. Insert data into the HBase table using the add() method as shown below." }, { "code": null, "e": 5547, "s": 5452, "text": "p.add(Bytes.toBytes(\"coloumn family \"), Bytes.toBytes(\"column\nname\"),Bytes.toBytes(\"value\"));\n" }, { "code": null, "e": 5678, "s": 5547, "text": "After inserting the required rows, save the changes by adding the put instance to the put() method of HTable class as shown below." }, { "code": null, "e": 5695, "s": 5678, "text": "hTable.put(p); \n" }, { "code": null, "e": 5802, "s": 5695, "text": "After creating data in the HBase Table, close the HTable instance using the close() method as shown below." }, { "code": null, "e": 5820, "s": 5802, "text": "hTable.close(); \n" }, { "code": null, "e": 5887, "s": 5820, "text": "Given below is the complete program to create data in HBase Table." }, { "code": null, "e": 7211, "s": 5887, "text": "import java.io.IOException;\n\nimport org.apache.hadoop.conf.Configuration;\n\nimport org.apache.hadoop.hbase.HBaseConfiguration;\nimport org.apache.hadoop.hbase.client.HTable;\nimport org.apache.hadoop.hbase.client.Put;\nimport org.apache.hadoop.hbase.util.Bytes;\n\npublic class InsertData{\n\n public static void main(String[] args) throws IOException {\n\n // Instantiating Configuration class\n Configuration config = HBaseConfiguration.create();\n\n // Instantiating HTable class\n HTable hTable = new HTable(config, \"emp\");\n\n // Instantiating Put class\n // accepts a row name.\n Put p = new Put(Bytes.toBytes(\"row1\")); \n\n // adding values using add() method\n // accepts column family name, qualifier/row name ,value\n p.add(Bytes.toBytes(\"personal\"),\n Bytes.toBytes(\"name\"),Bytes.toBytes(\"raju\"));\n\n p.add(Bytes.toBytes(\"personal\"),\n Bytes.toBytes(\"city\"),Bytes.toBytes(\"hyderabad\"));\n\n p.add(Bytes.toBytes(\"professional\"),Bytes.toBytes(\"designation\"),\n Bytes.toBytes(\"manager\"));\n\n p.add(Bytes.toBytes(\"professional\"),Bytes.toBytes(\"salary\"),\n Bytes.toBytes(\"50000\"));\n \n // Saving the put Instance to the HTable.\n hTable.put(p);\n System.out.println(\"data inserted\");\n \n // closing HTable\n hTable.close();\n }\n}" }, { "code": null, "e": 7265, "s": 7211, "text": "Compile and execute the above program as shown below." }, { "code": null, "e": 7306, "s": 7265, "text": "$javac InsertData.java\n$java InsertData\n" }, { "code": null, "e": 7342, "s": 7306, "text": "The following should be the output:" }, { "code": null, "e": 7357, "s": 7342, "text": "data inserted\n" }, { "code": null, "e": 7364, "s": 7357, "text": " Print" }, { "code": null, "e": 7375, "s": 7364, "text": " Add Notes" } ]
How to write "Hello World" in C#?
To print “Hello World” in C#, use the Console.WriteLine. Let us see a basic C# program to display a text − Live Demo using System; using System.Collections.Generic; using System.Text; namespace Program { class MyApplication { static void Main(string[] args) { Console.WriteLine("Hello World"); Console.Read(); } } } Hello World Above, we displayed the text “Hello World” using the WriteLine() method. The output is displayed using the Console − Console.WriteLine("Hello World");
[ { "code": null, "e": 1119, "s": 1062, "text": "To print “Hello World” in C#, use the Console.WriteLine." }, { "code": null, "e": 1169, "s": 1119, "text": "Let us see a basic C# program to display a text −" }, { "code": null, "e": 1180, "s": 1169, "text": " Live Demo" }, { "code": null, "e": 1416, "s": 1180, "text": "using System;\nusing System.Collections.Generic;\nusing System.Text;\n\nnamespace Program {\n class MyApplication {\n static void Main(string[] args) {\n Console.WriteLine(\"Hello World\");\n Console.Read();\n }\n }\n}" }, { "code": null, "e": 1428, "s": 1416, "text": "Hello World" }, { "code": null, "e": 1545, "s": 1428, "text": "Above, we displayed the text “Hello World” using the WriteLine() method. The output is displayed using the Console −" }, { "code": null, "e": 1579, "s": 1545, "text": "Console.WriteLine(\"Hello World\");" } ]
Check if a destination is reachable from source with two movements allowed - GeeksforGeeks
22 Oct, 2021 Given coordinates of a source point (x1, y1) determine if it is possible to reach the destination point (x2, y2). From any point (x, y) there only two types of valid movements: (x, x + y) and (x + y, y). Return a boolean true if it is possible else return false. Note: All coordinates are positive. Asked in: Expedia, TelstraExamples: Input : (x1, y1) = (2, 10) (x2, y2) = (26, 12) Output : True (2, 10)->(2, 12)->(14, 12)->(26, 12) is a valid path. Input : (x1, y1) = (20, 10) (x2, y2) = (6, 12) Output : False No such path is possible because x1 > x2 and coordinates are positive The problem can be solved using simple recursion. Base case would be to check if current x or y coordinate is greater than that of destination, in which case we return false. If it is not the destination point yet we make two calls for both valid movements from that point. If any of them yields a path we return true else return false. C++ Java Python3 C# PHP Javascript // C++ program to check if a destination is reachable// from source with two movements allowed#include <bits/stdc++.h>using namespace std; bool isReachable(int sx, int sy, int dx, int dy){ // base case if (sx > dx || sy > dy) return false; // current point is equal to destination if (sx == dx && sy == dy) return true; // check for other 2 possibilities return (isReachable(sx + sy, sy, dx, dy) || isReachable(sx, sy + sx, dx, dy));} // Driver codeint main(){ int source_x = 2, source_y = 10; int dest_x = 26, dest_y = 12; if (isReachable(source_x, source_y, dest_x, dest_y)) cout << "True\n"; else cout << "False\n"; return 0;} // Java program to check if a destination is// reachable from source with two movements// allowed class GFG { static boolean isReachable(int sx, int sy, int dx, int dy) { // base case if (sx > dx || sy > dy) return false; // current point is equal to destination if (sx == dx && sy == dy) return true; // check for other 2 possibilities return (isReachable(sx + sy, sy, dx, dy) || isReachable(sx, sy + sx, dx, dy)); } //driver code public static void main(String arg[]) { int source_x = 2, source_y = 10; int dest_x = 26, dest_y = 12; if (isReachable(source_x, source_y, dest_x, dest_y)) System.out.print("True\n"); else System.out.print("False\n"); }} // This code is contributed by Anant Agarwal. # Python3 program to check if# a destination is reachable# from source with two movements allowed def isReachable(sx, sy, dx, dy): # base case if (sx > dx or sy > dy): return False # current point is equal to destination if (sx == dx and sy == dy): return True # check for other 2 possibilities return (isReachable(sx + sy, sy, dx, dy) or isReachable(sx, sy + sx, dx, dy)) # Driver codesource_x, source_y = 2, 10dest_x, dest_y = 26, 12if (isReachable(source_x, source_y, dest_x, dest_y)): print("True")else: print("False") # This code is contributed by Anant Agarwal. // C# program to check if a destination is// reachable from source with two movements// allowedusing System; class GFG { static bool isReachable(int sx, int sy, int dx, int dy) { // base case if (sx > dx || sy > dy) return false; // current point is equal to destination if (sx == dx && sy == dy) return true; // check for other 2 possibilities return (isReachable(sx + sy, sy, dx, dy) || isReachable(sx, sy + sx, dx, dy)); } //driver code public static void Main() { int source_x = 2, source_y = 10; int dest_x = 26, dest_y = 12; if (isReachable(source_x, source_y, dest_x, dest_y)) Console.Write("True\n"); else Console.Write("False\n"); }} // This code is contributed by Anant Agarwal. <?php// PHP program to check if a// destination is reachable// from source with two movements// allowed function isReachable($sx, $sy, $dx, $dy){ // base case if ($sx > $dx || $sy > $dy) return false; // current point is equal // to destination if ($sx == $dx && $sy == $dy) return true; // check for other 2 possibilities return (isReachable($sx + $sy, $sy, $dx, $dy) || isReachable($sx, $sy + $sx, $dx, $dy));} // Driver code $source_x = 2; $source_y = 10; $dest_x = 26; $dest_y = 12; if (isReachable($source_x, $source_y, $dest_x, $dest_y)) echo "True\n"; else echo "False\n"; // This code is contributed by Sam007?> <script> // Javascript program to check if a destination is// reachable from source with two movements// allowed function isReachable(sx, sy, dx, dy) { // base case if (sx > dx || sy > dy) return false; // current point is equal to destination if (sx == dx && sy == dy) return true; // check for other 2 possibilities return (isReachable(sx + sy, sy, dx, dy) || isReachable(sx, sy + sx, dx, dy)); } // driver program let source_x = 2, source_y = 10; let dest_x = 26, dest_y = 12; if (isReachable(source_x, source_y, dest_x, dest_y)) document.write("True\n"); else document.write("False\n"); </script> Output: True This article is contributed by Aditi Sharma. 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 sanjoy_62 khushboogoyal499 Expedia Telstra Recursion Expedia Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Backtracking | Introduction Recursive Functions Print all subsequences of a string Check if a number is Palindrome Count all possible paths from top left to bottom right of a mXn matrix Combinational Sum Recursive Bubble Sort Reverse a stack using recursion 3 Different ways to print Fibonacci series in Java Flood fill Algorithm - how to implement fill() in paint?
[ { "code": null, "e": 25710, "s": 25682, "text": "\n22 Oct, 2021" }, { "code": null, "e": 26047, "s": 25710, "text": "Given coordinates of a source point (x1, y1) determine if it is possible to reach the destination point (x2, y2). From any point (x, y) there only two types of valid movements: (x, x + y) and (x + y, y). Return a boolean true if it is possible else return false. Note: All coordinates are positive. Asked in: Expedia, TelstraExamples: " }, { "code": null, "e": 26312, "s": 26047, "text": "Input : (x1, y1) = (2, 10)\n (x2, y2) = (26, 12)\nOutput : True\n(2, 10)->(2, 12)->(14, 12)->(26, 12) \nis a valid path.\n\nInput : (x1, y1) = (20, 10)\n (x2, y2) = (6, 12)\nOutput : False\nNo such path is possible because x1 > x2\nand coordinates are positive" }, { "code": null, "e": 26653, "s": 26314, "text": "The problem can be solved using simple recursion. Base case would be to check if current x or y coordinate is greater than that of destination, in which case we return false. If it is not the destination point yet we make two calls for both valid movements from that point. If any of them yields a path we return true else return false. " }, { "code": null, "e": 26657, "s": 26653, "text": "C++" }, { "code": null, "e": 26662, "s": 26657, "text": "Java" }, { "code": null, "e": 26670, "s": 26662, "text": "Python3" }, { "code": null, "e": 26673, "s": 26670, "text": "C#" }, { "code": null, "e": 26677, "s": 26673, "text": "PHP" }, { "code": null, "e": 26688, "s": 26677, "text": "Javascript" }, { "code": "// C++ program to check if a destination is reachable// from source with two movements allowed#include <bits/stdc++.h>using namespace std; bool isReachable(int sx, int sy, int dx, int dy){ // base case if (sx > dx || sy > dy) return false; // current point is equal to destination if (sx == dx && sy == dy) return true; // check for other 2 possibilities return (isReachable(sx + sy, sy, dx, dy) || isReachable(sx, sy + sx, dx, dy));} // Driver codeint main(){ int source_x = 2, source_y = 10; int dest_x = 26, dest_y = 12; if (isReachable(source_x, source_y, dest_x, dest_y)) cout << \"True\\n\"; else cout << \"False\\n\"; return 0;}", "e": 27392, "s": 26688, "text": null }, { "code": "// Java program to check if a destination is// reachable from source with two movements// allowed class GFG { static boolean isReachable(int sx, int sy, int dx, int dy) { // base case if (sx > dx || sy > dy) return false; // current point is equal to destination if (sx == dx && sy == dy) return true; // check for other 2 possibilities return (isReachable(sx + sy, sy, dx, dy) || isReachable(sx, sy + sx, dx, dy)); } //driver code public static void main(String arg[]) { int source_x = 2, source_y = 10; int dest_x = 26, dest_y = 12; if (isReachable(source_x, source_y, dest_x, dest_y)) System.out.print(\"True\\n\"); else System.out.print(\"False\\n\"); }} // This code is contributed by Anant Agarwal.", "e": 28344, "s": 27392, "text": null }, { "code": "# Python3 program to check if# a destination is reachable# from source with two movements allowed def isReachable(sx, sy, dx, dy): # base case if (sx > dx or sy > dy): return False # current point is equal to destination if (sx == dx and sy == dy): return True # check for other 2 possibilities return (isReachable(sx + sy, sy, dx, dy) or isReachable(sx, sy + sx, dx, dy)) # Driver codesource_x, source_y = 2, 10dest_x, dest_y = 26, 12if (isReachable(source_x, source_y, dest_x, dest_y)): print(\"True\")else: print(\"False\") # This code is contributed by Anant Agarwal.", "e": 28968, "s": 28344, "text": null }, { "code": "// C# program to check if a destination is// reachable from source with two movements// allowedusing System; class GFG { static bool isReachable(int sx, int sy, int dx, int dy) { // base case if (sx > dx || sy > dy) return false; // current point is equal to destination if (sx == dx && sy == dy) return true; // check for other 2 possibilities return (isReachable(sx + sy, sy, dx, dy) || isReachable(sx, sy + sx, dx, dy)); } //driver code public static void Main() { int source_x = 2, source_y = 10; int dest_x = 26, dest_y = 12; if (isReachable(source_x, source_y, dest_x, dest_y)) Console.Write(\"True\\n\"); else Console.Write(\"False\\n\"); }} // This code is contributed by Anant Agarwal.", "e": 29908, "s": 28968, "text": null }, { "code": "<?php// PHP program to check if a// destination is reachable// from source with two movements// allowed function isReachable($sx, $sy, $dx, $dy){ // base case if ($sx > $dx || $sy > $dy) return false; // current point is equal // to destination if ($sx == $dx && $sy == $dy) return true; // check for other 2 possibilities return (isReachable($sx + $sy, $sy, $dx, $dy) || isReachable($sx, $sy + $sx, $dx, $dy));} // Driver code $source_x = 2; $source_y = 10; $dest_x = 26; $dest_y = 12; if (isReachable($source_x, $source_y, $dest_x, $dest_y)) echo \"True\\n\"; else echo \"False\\n\"; // This code is contributed by Sam007?>", "e": 30647, "s": 29908, "text": null }, { "code": "<script> // Javascript program to check if a destination is// reachable from source with two movements// allowed function isReachable(sx, sy, dx, dy) { // base case if (sx > dx || sy > dy) return false; // current point is equal to destination if (sx == dx && sy == dy) return true; // check for other 2 possibilities return (isReachable(sx + sy, sy, dx, dy) || isReachable(sx, sy + sx, dx, dy)); } // driver program let source_x = 2, source_y = 10; let dest_x = 26, dest_y = 12; if (isReachable(source_x, source_y, dest_x, dest_y)) document.write(\"True\\n\"); else document.write(\"False\\n\"); </script>", "e": 31457, "s": 30647, "text": null }, { "code": null, "e": 31467, "s": 31457, "text": "Output: " }, { "code": null, "e": 31472, "s": 31467, "text": "True" }, { "code": null, "e": 31893, "s": 31472, "text": "This article is contributed by Aditi Sharma. 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": 31900, "s": 31893, "text": "Sam007" }, { "code": null, "e": 31910, "s": 31900, "text": "sanjoy_62" }, { "code": null, "e": 31927, "s": 31910, "text": "khushboogoyal499" }, { "code": null, "e": 31935, "s": 31927, "text": "Expedia" }, { "code": null, "e": 31943, "s": 31935, "text": "Telstra" }, { "code": null, "e": 31953, "s": 31943, "text": "Recursion" }, { "code": null, "e": 31961, "s": 31953, "text": "Expedia" }, { "code": null, "e": 31971, "s": 31961, "text": "Recursion" }, { "code": null, "e": 32069, "s": 31971, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32097, "s": 32069, "text": "Backtracking | Introduction" }, { "code": null, "e": 32117, "s": 32097, "text": "Recursive Functions" }, { "code": null, "e": 32152, "s": 32117, "text": "Print all subsequences of a string" }, { "code": null, "e": 32184, "s": 32152, "text": "Check if a number is Palindrome" }, { "code": null, "e": 32255, "s": 32184, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 32273, "s": 32255, "text": "Combinational Sum" }, { "code": null, "e": 32295, "s": 32273, "text": "Recursive Bubble Sort" }, { "code": null, "e": 32327, "s": 32295, "text": "Reverse a stack using recursion" }, { "code": null, "e": 32378, "s": 32327, "text": "3 Different ways to print Fibonacci series in Java" } ]
Creating Custom Aggregations to Use with Pandas groupby | by Rose Day | Towards Data Science
Pandas groupby is a function you can utilize on dataframes to split the object, apply a function, and combine the results. This function is useful when you want to group large amounts of data and compute different operations for each group. If you are using an aggregation function with your groupby, this aggregation will return a single value for each group per function run. After forming your groups, you can run one or many aggregations on the grouped data. The dataset I am using today is Amazon Top 50 Bestselling Books on Kaggle. This dataset has some nice numeric columns and categories that we can work with. Importing that dataset, we can quickly look at one example of the data using head(1) to grab the first row and .T to transpose the data. Here we can see that Genre is a great category column to groupby, and we can aggregate the user ratings, reviews, price, and year. df = pd.read_csv("bestsellers_with_categories.csv")print(df.head(1).T)>>> 0>>> Name 10-Day Green Smoothie Cleanse>>> Author JJ Smith>>> User Rating 4.7>>> Reviews 17350>>> Price 8>>> Year 2016>>> Genre Non Fiction Now that we have taken a quick look at the columns, we can use groupby to group Genre’s data. Before applying groupby, we can see two Genre categories in this dataset, Non-Fiction, and Fiction, meaning we will have two groups of data to work with. We can play around with the groups if we wanted to consider the author or book title, but we will stick with Genre for now. df.Genre.unique()>>> array(['Non Fiction', 'Fiction'], dtype=object)group_cols = ['Genre']ex = df.groupby(group_cols) After setting up our groups, we can begin to create custom aggregations. I have used custom aggregations in functions like this to filter specific values out before performing calculations or aggregations under different conditions. When I am testing out aggregation functions, I like to start with a small series to validate the output, such as the one below. ser = pd.Series([1,10,4,2,10,10]) Once we have a series of data to test with, we can begin creating our aggregation functions. Below I have created three aggregation functions. The first and second functions are non_nan_mean, and standard_deviation which validate the series is not empty, remove any NA values, and perform a mean or standard deviation calculation. The last aggregation is a mean_lower_rating, which eliminates any upper values greater than five and calculates the mean on the lower values. def non_nan_mean(x): if x.empty: return None else: x = x.dropna() return np.mean(x)def standard_deviation(x): if x.empty: return None else: x = x.dropna() return np.nanstd(x) def mean_lower_rating(x): upper = [] for val in x: if val > 5: continue else: upper.append(val) return np.mean(upper) Once you have defined your aggregation functions, as many or little as you need, you can apply your series to them to test. I printed my values out to look them over, like below. print(non_nan_mean(ser))print(standard_deviation(ser))print(mean_lower_rating(ser))>>> 6.166666666666667>>> 3.9334745737353156>>> 2.3333333333333335 After understanding the dataset you are working with and testing out the aggregation functions using a small series of data, you can apply the aggregation functions created using the agg function mentioned earlier. This function works on dataframes, which allows us to aggregate data over a specified axis. A simple way to apply these aggregations is to create a list and pass that list as an argument. This method will apply your aggregations to all numeric columns within your group dataframe, as shown in example one below. In this example, you can see I am calling ex, which is the grouped output from earlier. aggs = [non_nan_mean, standard_deviation,mean_lower_rating]ex2 = ex.agg(aggs)print(ex2) As can be seen with the output, the mean_lower_rating aggregation does not perform well on specific columns, caused by the function designed for a particular column in mind, which was User Rating. Considering this, we can look at different ways to pass aggregation arguments into the agg function, which will clean this output up. Another way to pass arguments to agg is to develop a dictionary. The dictionary maps the column names to aggregation functions to run. An example of this method is seen in example two. aggs_by_col = {'Reviews': [non_nan_mean], 'Price': [non_nan_mean,standard_deviation], 'User Rating': [mean_lower_rating]}ex1 = ex.agg(aggs_by_col)print(ex1) This method is preferred if you do not want to apply all aggregations across all columns, as mentioned previously, with the mean_lower_rating aggregation. The process of defining which columns your aggregation applies to can be very beneficial for large datasets as it cleans up the output, providing you just the data you want to see. This method of applying the aggregations allowed me to specify the mean_lower_rating aggregation only for User Rating, and the other aggregations to their respective columns. Using Pandas groupby with the agg function will allow you to group your data into different categories and aggregate your numeric columns into one value per aggregation function. If you have use cases to create custom aggregation functions, you can write those functions to take in a series of data and then pass them to agg using a list or dictionary. You can pass a list if you want all aggregations applied to all numeric columns, and you can pass a dictionary if you’re going to specify what aggregations apply to what columns. You can also use lambda functions to create your aggregations if you prefer, which I did not cover in this article. pandas.DataFrame.groupby documentation pandas.core.groupby.DataFrameGroupBy.aggregate documentation Group by: split-apply-combine documentation pandas.DataFrame.agg documentation If you would like to read more, check out some of my other articles below!
[ { "code": null, "e": 634, "s": 171, "text": "Pandas groupby is a function you can utilize on dataframes to split the object, apply a function, and combine the results. This function is useful when you want to group large amounts of data and compute different operations for each group. If you are using an aggregation function with your groupby, this aggregation will return a single value for each group per function run. After forming your groups, you can run one or many aggregations on the grouped data." }, { "code": null, "e": 1058, "s": 634, "text": "The dataset I am using today is Amazon Top 50 Bestselling Books on Kaggle. This dataset has some nice numeric columns and categories that we can work with. Importing that dataset, we can quickly look at one example of the data using head(1) to grab the first row and .T to transpose the data. Here we can see that Genre is a great category column to groupby, and we can aggregate the user ratings, reviews, price, and year." }, { "code": null, "e": 1456, "s": 1058, "text": "df = pd.read_csv(\"bestsellers_with_categories.csv\")print(df.head(1).T)>>> 0>>> Name 10-Day Green Smoothie Cleanse>>> Author JJ Smith>>> User Rating 4.7>>> Reviews 17350>>> Price 8>>> Year 2016>>> Genre Non Fiction" }, { "code": null, "e": 1828, "s": 1456, "text": "Now that we have taken a quick look at the columns, we can use groupby to group Genre’s data. Before applying groupby, we can see two Genre categories in this dataset, Non-Fiction, and Fiction, meaning we will have two groups of data to work with. We can play around with the groups if we wanted to consider the author or book title, but we will stick with Genre for now." }, { "code": null, "e": 1946, "s": 1828, "text": "df.Genre.unique()>>> array(['Non Fiction', 'Fiction'], dtype=object)group_cols = ['Genre']ex = df.groupby(group_cols)" }, { "code": null, "e": 2307, "s": 1946, "text": "After setting up our groups, we can begin to create custom aggregations. I have used custom aggregations in functions like this to filter specific values out before performing calculations or aggregations under different conditions. When I am testing out aggregation functions, I like to start with a small series to validate the output, such as the one below." }, { "code": null, "e": 2341, "s": 2307, "text": "ser = pd.Series([1,10,4,2,10,10])" }, { "code": null, "e": 2814, "s": 2341, "text": "Once we have a series of data to test with, we can begin creating our aggregation functions. Below I have created three aggregation functions. The first and second functions are non_nan_mean, and standard_deviation which validate the series is not empty, remove any NA values, and perform a mean or standard deviation calculation. The last aggregation is a mean_lower_rating, which eliminates any upper values greater than five and calculates the mean on the lower values." }, { "code": null, "e": 3214, "s": 2814, "text": "def non_nan_mean(x): if x.empty: return None else: x = x.dropna() return np.mean(x)def standard_deviation(x): if x.empty: return None else: x = x.dropna() return np.nanstd(x) def mean_lower_rating(x): upper = [] for val in x: if val > 5: continue else: upper.append(val) return np.mean(upper)" }, { "code": null, "e": 3393, "s": 3214, "text": "Once you have defined your aggregation functions, as many or little as you need, you can apply your series to them to test. I printed my values out to look them over, like below." }, { "code": null, "e": 3542, "s": 3393, "text": "print(non_nan_mean(ser))print(standard_deviation(ser))print(mean_lower_rating(ser))>>> 6.166666666666667>>> 3.9334745737353156>>> 2.3333333333333335" }, { "code": null, "e": 4157, "s": 3542, "text": "After understanding the dataset you are working with and testing out the aggregation functions using a small series of data, you can apply the aggregation functions created using the agg function mentioned earlier. This function works on dataframes, which allows us to aggregate data over a specified axis. A simple way to apply these aggregations is to create a list and pass that list as an argument. This method will apply your aggregations to all numeric columns within your group dataframe, as shown in example one below. In this example, you can see I am calling ex, which is the grouped output from earlier." }, { "code": null, "e": 4245, "s": 4157, "text": "aggs = [non_nan_mean, standard_deviation,mean_lower_rating]ex2 = ex.agg(aggs)print(ex2)" }, { "code": null, "e": 4576, "s": 4245, "text": "As can be seen with the output, the mean_lower_rating aggregation does not perform well on specific columns, caused by the function designed for a particular column in mind, which was User Rating. Considering this, we can look at different ways to pass aggregation arguments into the agg function, which will clean this output up." }, { "code": null, "e": 4761, "s": 4576, "text": "Another way to pass arguments to agg is to develop a dictionary. The dictionary maps the column names to aggregation functions to run. An example of this method is seen in example two." }, { "code": null, "e": 4947, "s": 4761, "text": "aggs_by_col = {'Reviews': [non_nan_mean], 'Price': [non_nan_mean,standard_deviation], 'User Rating': [mean_lower_rating]}ex1 = ex.agg(aggs_by_col)print(ex1)" }, { "code": null, "e": 5458, "s": 4947, "text": "This method is preferred if you do not want to apply all aggregations across all columns, as mentioned previously, with the mean_lower_rating aggregation. The process of defining which columns your aggregation applies to can be very beneficial for large datasets as it cleans up the output, providing you just the data you want to see. This method of applying the aggregations allowed me to specify the mean_lower_rating aggregation only for User Rating, and the other aggregations to their respective columns." }, { "code": null, "e": 6106, "s": 5458, "text": "Using Pandas groupby with the agg function will allow you to group your data into different categories and aggregate your numeric columns into one value per aggregation function. If you have use cases to create custom aggregation functions, you can write those functions to take in a series of data and then pass them to agg using a list or dictionary. You can pass a list if you want all aggregations applied to all numeric columns, and you can pass a dictionary if you’re going to specify what aggregations apply to what columns. You can also use lambda functions to create your aggregations if you prefer, which I did not cover in this article." }, { "code": null, "e": 6145, "s": 6106, "text": "pandas.DataFrame.groupby documentation" }, { "code": null, "e": 6206, "s": 6145, "text": "pandas.core.groupby.DataFrameGroupBy.aggregate documentation" }, { "code": null, "e": 6250, "s": 6206, "text": "Group by: split-apply-combine documentation" }, { "code": null, "e": 6285, "s": 6250, "text": "pandas.DataFrame.agg documentation" } ]
HTML <input type=”radio”>
15 Dec, 2021 The HTML <input type=”radio”> is used to define a Radio Button. Radio Buttons are used to let the user select exactly one option from a list of predefined options. Radio Button input controls are created by using the “input” element with a type attribute having value as “radio”. Syntax: <input type="radio"> Example: In this example, we simply select the correct option from the given options using the radio button. HTML <!DOCTYPE html><html> <body> <h2>Welcome To GeeksforGeeks</h2> <p>Select a Technology Brand:</p> <div> <input type="radio" id="Netflix" name="brand" value="Netflix"> <label for="Netflix">Netflix</label> </div> <div> <input type="radio" id="Audi" name="brand" value="Audi"> <label for="Audi">Audi</label> </div> <div> <input type="radio" id="Microsoft" name="brand" value="Microsoft" checked> <label for="Microsoft">Microsoft</label> </div> </body> </html> Output: <input type=”radio”> Example: This example explains the HTML input type as radio button by specifying its value as true. HTML <!DOCTYPE html><html> <head> <title> HTML input type radio </title> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1> GeeksforGeeks </h1> <h2> HTML <Input type= "radio"> </h2> Radio Button: <input type="radio" checked=true id="radioID" value="Geeks_radio" name="Geek_radio"> </body> </html> Output: <input type=”radio”> Supported Browsers: Google Chrome Internet Explorer Firefox Safari Opera Microsoft Edge 12 and above shubhamyadav4 bhaskargeeksforgeeks HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? REST API (Introduction) CSS to put icon inside an input element in a form Design a Tribute Page using HTML & CSS Types of CSS (Cascading Style Sheet) 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": 53, "s": 25, "text": "\n15 Dec, 2021" }, { "code": null, "e": 333, "s": 53, "text": "The HTML <input type=”radio”> is used to define a Radio Button. Radio Buttons are used to let the user select exactly one option from a list of predefined options. Radio Button input controls are created by using the “input” element with a type attribute having value as “radio”." }, { "code": null, "e": 341, "s": 333, "text": "Syntax:" }, { "code": null, "e": 362, "s": 341, "text": "<input type=\"radio\">" }, { "code": null, "e": 471, "s": 362, "text": "Example: In this example, we simply select the correct option from the given options using the radio button." }, { "code": null, "e": 476, "s": 471, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <h2>Welcome To GeeksforGeeks</h2> <p>Select a Technology Brand:</p> <div> <input type=\"radio\" id=\"Netflix\" name=\"brand\" value=\"Netflix\"> <label for=\"Netflix\">Netflix</label> </div> <div> <input type=\"radio\" id=\"Audi\" name=\"brand\" value=\"Audi\"> <label for=\"Audi\">Audi</label> </div> <div> <input type=\"radio\" id=\"Microsoft\" name=\"brand\" value=\"Microsoft\" checked> <label for=\"Microsoft\">Microsoft</label> </div> </body> </html>", "e": 969, "s": 476, "text": null }, { "code": null, "e": 977, "s": 969, "text": "Output:" }, { "code": null, "e": 998, "s": 977, "text": "<input type=”radio”>" }, { "code": null, "e": 1098, "s": 998, "text": "Example: This example explains the HTML input type as radio button by specifying its value as true." }, { "code": null, "e": 1103, "s": 1098, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML input type radio </title> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1> GeeksforGeeks </h1> <h2> HTML <Input type= \"radio\"> </h2> Radio Button: <input type=\"radio\" checked=true id=\"radioID\" value=\"Geeks_radio\" name=\"Geek_radio\"> </body> </html>", "e": 1549, "s": 1103, "text": null }, { "code": null, "e": 1557, "s": 1549, "text": "Output:" }, { "code": null, "e": 1578, "s": 1557, "text": "<input type=”radio”>" }, { "code": null, "e": 1599, "s": 1578, "text": "Supported Browsers: " }, { "code": null, "e": 1613, "s": 1599, "text": "Google Chrome" }, { "code": null, "e": 1631, "s": 1613, "text": "Internet Explorer" }, { "code": null, "e": 1639, "s": 1631, "text": "Firefox" }, { "code": null, "e": 1646, "s": 1639, "text": "Safari" }, { "code": null, "e": 1652, "s": 1646, "text": "Opera" }, { "code": null, "e": 1680, "s": 1652, "text": "Microsoft Edge 12 and above" }, { "code": null, "e": 1694, "s": 1680, "text": "shubhamyadav4" }, { "code": null, "e": 1715, "s": 1694, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 1731, "s": 1715, "text": "HTML-Attributes" }, { "code": null, "e": 1736, "s": 1731, "text": "HTML" }, { "code": null, "e": 1753, "s": 1736, "text": "Web Technologies" }, { "code": null, "e": 1758, "s": 1753, "text": "HTML" }, { "code": null, "e": 1856, "s": 1758, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1904, "s": 1856, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 1928, "s": 1904, "text": "REST API (Introduction)" }, { "code": null, "e": 1978, "s": 1928, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 2017, "s": 1978, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 2054, "s": 2017, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 2087, "s": 2054, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2148, "s": 2087, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2191, "s": 2148, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 2263, "s": 2191, "text": "Differences between Functional Components and Class Components in React" } ]
QuickSort on Singly Linked List
24 Jun, 2022 QuickSort on Doubly Linked List is discussed here. QuickSort on Singly linked list was given as an exercise. Following is C++ implementation for same. The important things about implementation are, it changes pointers rather swapping data and time complexity is same as the implementation for Doubly Linked List. In partition(), we consider last element as pivot. We traverse through the current list and if a node has value greater than pivot, we move it after tail. If the node has smaller value, we keep it at its current position. In QuickSortRecur(), we first call partition() which places pivot at correct position and returns pivot. After pivot is placed at correct position, we find tail node of left side (list before pivot) and recur for left list. Finally, we recur for right list. Implementation”: C++ Java Python3 C# Javascript C // C++ program for Quick Sort on Singly Linked List#include <cstdio>#include <iostream>using namespace std; /* a node of the singly linked list */struct Node { int data; struct Node* next;}; /* A utility function to insert a node at the beginning of * linked list */void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = new Node; /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* A utility function to print linked list */void printList(struct Node* node){ while (node != NULL) { printf("%d ", node->data); node = node->next; } printf("\n");} // Returns the last node of the liststruct Node* getTail(struct Node* cur){ while (cur != NULL && cur->next != NULL) cur = cur->next; return cur;} // Partitions the list taking the last element as the pivotstruct Node* partition(struct Node* head, struct Node* end, struct Node** newHead, struct Node** newEnd){ struct Node* pivot = end; struct Node *prev = NULL, *cur = head, *tail = pivot; // During partition, both the head and end of the list // might change which is updated in the newHead and // newEnd variables while (cur != pivot) { if (cur->data < pivot->data) { // First node that has a value less than the // pivot - becomes the new head if ((*newHead) == NULL) (*newHead) = cur; prev = cur; cur = cur->next; } else // If cur node is greater than pivot { // Move cur node to next of tail, and change // tail if (prev) prev->next = cur->next; struct Node* tmp = cur->next; cur->next = NULL; tail->next = cur; tail = cur; cur = tmp; } } // If the pivot data is the smallest element in the // current list, pivot becomes the head if ((*newHead) == NULL) (*newHead) = pivot; // Update newEnd to the current last node (*newEnd) = tail; // Return the pivot node return pivot;} // here the sorting happens exclusive of the end nodestruct Node* quickSortRecur(struct Node* head, struct Node* end){ // base condition if (!head || head == end) return head; Node *newHead = NULL, *newEnd = NULL; // Partition the list, newHead and newEnd will be // updated by the partition function struct Node* pivot = partition(head, end, &newHead, &newEnd); // If pivot is the smallest element - no need to recur // for the left part. if (newHead != pivot) { // Set the node before the pivot node as NULL struct Node* tmp = newHead; while (tmp->next != pivot) tmp = tmp->next; tmp->next = NULL; // Recur for the list before pivot newHead = quickSortRecur(newHead, tmp); // Change next of last node of the left half to // pivot tmp = getTail(newHead); tmp->next = pivot; } // Recur for the list after the pivot element pivot->next = quickSortRecur(pivot->next, newEnd); return newHead;} // The main function for quick sort. This is a wrapper over// recursive function quickSortRecur()void quickSort(struct Node** headRef){ (*headRef) = quickSortRecur(*headRef, getTail(*headRef)); return;} // Driver codeint main(){ struct Node* a = NULL; push(&a, 5); push(&a, 20); push(&a, 4); push(&a, 3); push(&a, 30); cout << "Linked List before sorting \n"; printList(a); quickSort(&a); cout << "Linked List after sorting \n"; printList(a); return 0;} // Java program for Quick Sort on Singly Linked List /*sort a linked list using quick sort*/publicclass QuickSortLinkedList { static class Node { int data; Node next; Node(int d) { this.data = d; this.next = null; } } Node head; void addNode(int data) { if (head == null) { head = new Node(data); return; } Node curr = head; while (curr.next != null) curr = curr.next; Node newNode = new Node(data); curr.next = newNode; } void printList(Node n) { while (n != null) { System.out.print(n.data); System.out.print(" "); n = n.next; } } // takes first and last node, // but do not break any links in // the whole linked list Node paritionLast(Node start, Node end) { if (start == end || start == null || end == null) return start; Node pivot_prev = start; Node curr = start; int pivot = end.data; // iterate till one before the end, // no need to iterate till the end // because end is pivot while (start != end) { if (start.data < pivot) { // keep tracks of last modified item pivot_prev = curr; int temp = curr.data; curr.data = start.data; start.data = temp; curr = curr.next; } start = start.next; } // swap the position of curr i.e. // next suitable index and pivot int temp = curr.data; curr.data = pivot; end.data = temp; // return one previous to current // because current is now pointing to pivot return pivot_prev; } void sort(Node start, Node end) { if(start == null || start == end|| start == end.next ) return; // split list and partition recurse Node pivot_prev = paritionLast(start, end); sort(start, pivot_prev); // if pivot is picked and moved to the start, // that means start and pivot is same // so pick from next of pivot if (pivot_prev != null && pivot_prev == start) sort(pivot_prev.next, end); // if pivot is in between of the list, // start from next of pivot, // since we have pivot_prev, so we move two nodes else if (pivot_prev != null && pivot_prev.next != null) sort(pivot_prev.next.next, end); } // Driver Codepublic static void main(String[] args) { QuickSortLinkedList list = new QuickSortLinkedList(); list.addNode(30); list.addNode(3); list.addNode(4); list.addNode(20); list.addNode(5); Node n = list.head; while (n.next != null) n = n.next; System.out.println("Linked List before sorting"); list.printList(list.head); list.sort(list.head, n); System.out.println("\nLinked List after sorting"); list.printList(list.head); }} // This code is contributed by trinadumca ''' sort a linked list using quick sort ''' class Node: def __init__(self, val): self.data = val self.next = None class QuickSortLinkedList: def __init__(self): self.head=None def addNode(self,data): if (self.head == None): self.head = Node(data) return curr = self.head while (curr.next != None): curr = curr.next newNode = Node(data) curr.next = newNode def printList(self,n): while (n != None): print(n.data, end=" ") n = n.next ''' takes first and last node,but do not break any links in the whole linked list''' def paritionLast(self,start, end): if (start == end or start == None or end == None): return start pivot_prev = start curr = start pivot = end.data '''iterate till one before the end, no need to iterate till the end because end is pivot''' while (start != end): if (start.data < pivot): # keep tracks of last modified item pivot_prev = curr temp = curr.data curr.data = start.data start.data = temp curr = curr.next start = start.next '''swap the position of curr i.e. next suitable index and pivot''' temp = curr.data curr.data = pivot end.data = temp ''' return one previous to current because current is now pointing to pivot ''' return pivot_prev def sort(self, start, end): if(start == None or start == end or start == end.next): return # split list and partition recurse pivot_prev = self.paritionLast(start, end) self.sort(start, pivot_prev) ''' if pivot is picked and moved to the start, that means start and pivot is same so pick from next of pivot ''' if(pivot_prev != None and pivot_prev == start): self.sort(pivot_prev.next, end) # if pivot is in between of the list,start from next of pivot, # since we have pivot_prev, so we move two nodes elif (pivot_prev != None and pivot_prev.next != None): self.sort(pivot_prev.next.next, end) if __name__ == "__main__": ll = QuickSortLinkedList() ll.addNode(30) ll.addNode(3) ll.addNode(4) ll.addNode(20) ll.addNode(5) n = ll.head while (n.next != None): n = n.next print("\nLinked List before sorting") ll.printList(ll.head) ll.sort(ll.head, n) print("\nLinked List after sorting"); ll.printList(ll.head) # This code is contributed by humpheykibet. // C# program for Quick Sort on// Singly Linked Listusing System; /*sort a linked list using quick sort*/class GFG { public class Node { public int data; public Node next; public Node(int d) { this.data = d; this.next = null; } } Node head; void addNode(int data) { if (head == null) { head = new Node(data); return; } Node curr = head; while (curr.next != null) curr = curr.next; Node newNode = new Node(data); curr.next = newNode; } void printList(Node n) { while (n != null) { Console.Write(n.data); Console.Write(" "); n = n.next; } } // takes first and last node, // but do not break any links in // the whole linked list Node paritionLast(Node start, Node end) { if (start == end || start == null || end == null) return start; Node pivot_prev = start; Node curr = start; int pivot = end.data; // iterate till one before the end, // no need to iterate till the end // because end is pivot int temp; while (start != end) { if (start.data < pivot) { // keep tracks of last modified item pivot_prev = curr; temp = curr.data; curr.data = start.data; start.data = temp; curr = curr.next; } start = start.next; } // swap the position of curr i.e. // next suitable index and pivot temp = curr.data; curr.data = pivot; end.data = temp; // return one previous to current // because current is now pointing to pivot return pivot_prev; } void sort(Node start, Node end) { if (start == end) return; // split list and partition recurse Node pivot_prev = paritionLast(start, end); sort(start, pivot_prev); // if pivot is picked and moved to the start, // that means start and pivot is same // so pick from next of pivot if (pivot_prev != null && pivot_prev == start) sort(pivot_prev.next, end); // if pivot is in between of the list, // start from next of pivot, // since we have pivot_prev, so we move two nodes else if (pivot_prev != null && pivot_prev.next != null) sort(pivot_prev.next.next, end); } // Driver Code public static void Main(String[] args) { GFG list = new GFG(); list.addNode(30); list.addNode(3); list.addNode(4); list.addNode(20); list.addNode(5); Node n = list.head; while (n.next != null) n = n.next; Console.WriteLine("Linked List before sorting"); list.printList(list.head); list.sort(list.head, n); Console.WriteLine("\nLinked List after sorting"); list.printList(list.head); }} // This code is contributed by 29AjayKumar <script>// javascript program for Quick Sort on Singly Linked List /*sort a linked list using quick sort*/ class Node { constructor(val) { this.data = val; this.next = null; } } var head; function addNode(data) { if (head == null) { head = new Node(data); return; } var curr = head; while (curr.next != null) curr = curr.next; var newNode = new Node(data); curr.next = newNode; } function printList( n) { while (n != null) { document.write(n.data); document.write(" "); n = n.next; } } // takes first and last node, // but do not break any links in // the whole linked list function paritionLast( start, end) { if (start == end || start == null || end == null) return start; var pivot_prev = start; var curr = start; var pivot = end.data; // iterate till one before the end, // no need to iterate till the end // because end is pivot while (start != end) { if (start.data < pivot) { // keep tracks of last modified item pivot_prev = curr; var temp = curr.data; curr.data = start.data; start.data = temp; curr = curr.next; } start = start.next; } // swap the position of curr i.e. // next suitable index and pivot var temp = curr.data; curr.data = pivot; end.data = temp; // return one previous to current // because current is now pointing to pivot return pivot_prev; } function sort( start, end) { if (start == null || start == end || start == end.next) return; // split list and partition recurse var pivot_prev = paritionLast(start, end); sort(start, pivot_prev); // if pivot is picked and moved to the start, // that means start and pivot is same // so pick from next of pivot if (pivot_prev != null && pivot_prev == start) sort(pivot_prev.next, end); // if pivot is in between of the list, // start from next of pivot, // since we have pivot_prev, so we move two nodes else if (pivot_prev != null && pivot_prev.next != null) sort(pivot_prev.next.next, end); } // Driver Code addNode(30); addNode(3); addNode(4); addNode(20); addNode(5); var n = head; while (n.next != null) n = n.next; document.write("Linked List before sorting<br/>"); printList(head); sort(head, n); document.write("<br/>Linked List after sorting<br/>"); printList(head); // This code contributed by umadevi9616 </script> #include <stdio.h>#include <stdlib.h> //Creating structurestruct Node{ int data; struct Node *next;};//Add new node at end of linked list void insert(struct Node **head, int value){ //Create dynamic node struct Node *node = (struct Node *) malloc(sizeof(struct Node)); if (node == NULL) { //checking memory overflow printf("Memory overflow\n"); } else { node->data = value; node->next = NULL; if ( *head == NULL) { *head = node; } else { struct Node *temp = *head; //finding last node while (temp->next != NULL) { temp = temp->next; } //adding node at last possition temp->next = node; } }}//Displaying linked list elementvoid display(struct Node *head){ if (head == NULL) { printf("Empty linked list"); return; } struct Node *temp = head; printf("\n Linked List :"); while (temp != NULL) { printf(" %d", temp->data); temp = temp->next; }}//Finding last node of linked liststruct Node *last_node(struct Node *head){ struct Node *temp = head; while (temp != NULL && temp->next != NULL) { temp = temp->next; } return temp;}//We are Setting the given last node position to its proper positionstruct Node *parition(struct Node *first, struct Node *last){ //Get first node of given linked list struct Node *pivot = first; struct Node *front = first; int temp = 0; while (front != NULL && front != last) { if (front->data < last->data) { pivot = first; //Swapping node values temp = first->data; first->data = front->data; front->data = temp; //Visiting the next node first = first->next; } //Visiting the next node front = front->next; } //Change last node value to current node temp = first->data; first->data = last->data; last->data = temp; return pivot;}//Performing quick sort in the given linked listvoid quick_sort(struct Node *first, struct Node *last){ if (first == last) { return; } struct Node *pivot = parition(first, last); if (pivot != NULL && pivot->next != NULL) { quick_sort(pivot->next, last); } if (pivot != NULL && first != pivot) { quick_sort(first, pivot); }}int main(){ struct Node *head = NULL; //Create linked list insert( &head, 41); insert( &head, 5); insert( &head, 7); insert( &head, 22); insert( &head, 28); insert( &head, 63); insert( &head, 4); insert( &head, 8); insert( &head, 2); insert( &head, 11); printf("\n Before Sort "); display(head); quick_sort(head, last_node(head)); printf("\n After Sort "); display(head); return 0;} Linked List before sorting 30 3 4 20 5 Linked List after sorting 3 4 5 20 30 Time Complexity: O(nlogn) It takes O(n^2) in worst case and O(nlogn) in average or best case. Auxiliary Space: O(n) As extra space is used in recursion call stack. TrinaD 29AjayKumar sudoaccessdenied umadevi9616 humphreykibet anikaseth98 kashishsoda simranarora5sos sayanc170 abhijeet19403 hardikkoriintern Linked-List-Sorting Quick Sort Linked List Sorting Linked List Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures What is Data Structure: Types, Classifications and Applications Linked List vs Array Implementing a Linked List in Java using Class Find Length of a Linked List (Iterative and Recursive) Merge Sort Bubble Sort Algorithm QuickSort Insertion Sort Selection Sort Algorithm
[ { "code": null, "e": 52, "s": 24, "text": "\n24 Jun, 2022" }, { "code": null, "e": 366, "s": 52, "text": "QuickSort on Doubly Linked List is discussed here. QuickSort on Singly linked list was given as an exercise. Following is C++ implementation for same. The important things about implementation are, it changes pointers rather swapping data and time complexity is same as the implementation for Doubly Linked List. " }, { "code": null, "e": 589, "s": 366, "text": "In partition(), we consider last element as pivot. We traverse through the current list and if a node has value greater than pivot, we move it after tail. If the node has smaller value, we keep it at its current position. " }, { "code": null, "e": 847, "s": 589, "text": "In QuickSortRecur(), we first call partition() which places pivot at correct position and returns pivot. After pivot is placed at correct position, we find tail node of left side (list before pivot) and recur for left list. Finally, we recur for right list." }, { "code": null, "e": 864, "s": 847, "text": "Implementation”:" }, { "code": null, "e": 868, "s": 864, "text": "C++" }, { "code": null, "e": 873, "s": 868, "text": "Java" }, { "code": null, "e": 881, "s": 873, "text": "Python3" }, { "code": null, "e": 884, "s": 881, "text": "C#" }, { "code": null, "e": 895, "s": 884, "text": "Javascript" }, { "code": null, "e": 897, "s": 895, "text": "C" }, { "code": "// C++ program for Quick Sort on Singly Linked List#include <cstdio>#include <iostream>using namespace std; /* a node of the singly linked list */struct Node { int data; struct Node* next;}; /* A utility function to insert a node at the beginning of * linked list */void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = new Node; /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* A utility function to print linked list */void printList(struct Node* node){ while (node != NULL) { printf(\"%d \", node->data); node = node->next; } printf(\"\\n\");} // Returns the last node of the liststruct Node* getTail(struct Node* cur){ while (cur != NULL && cur->next != NULL) cur = cur->next; return cur;} // Partitions the list taking the last element as the pivotstruct Node* partition(struct Node* head, struct Node* end, struct Node** newHead, struct Node** newEnd){ struct Node* pivot = end; struct Node *prev = NULL, *cur = head, *tail = pivot; // During partition, both the head and end of the list // might change which is updated in the newHead and // newEnd variables while (cur != pivot) { if (cur->data < pivot->data) { // First node that has a value less than the // pivot - becomes the new head if ((*newHead) == NULL) (*newHead) = cur; prev = cur; cur = cur->next; } else // If cur node is greater than pivot { // Move cur node to next of tail, and change // tail if (prev) prev->next = cur->next; struct Node* tmp = cur->next; cur->next = NULL; tail->next = cur; tail = cur; cur = tmp; } } // If the pivot data is the smallest element in the // current list, pivot becomes the head if ((*newHead) == NULL) (*newHead) = pivot; // Update newEnd to the current last node (*newEnd) = tail; // Return the pivot node return pivot;} // here the sorting happens exclusive of the end nodestruct Node* quickSortRecur(struct Node* head, struct Node* end){ // base condition if (!head || head == end) return head; Node *newHead = NULL, *newEnd = NULL; // Partition the list, newHead and newEnd will be // updated by the partition function struct Node* pivot = partition(head, end, &newHead, &newEnd); // If pivot is the smallest element - no need to recur // for the left part. if (newHead != pivot) { // Set the node before the pivot node as NULL struct Node* tmp = newHead; while (tmp->next != pivot) tmp = tmp->next; tmp->next = NULL; // Recur for the list before pivot newHead = quickSortRecur(newHead, tmp); // Change next of last node of the left half to // pivot tmp = getTail(newHead); tmp->next = pivot; } // Recur for the list after the pivot element pivot->next = quickSortRecur(pivot->next, newEnd); return newHead;} // The main function for quick sort. This is a wrapper over// recursive function quickSortRecur()void quickSort(struct Node** headRef){ (*headRef) = quickSortRecur(*headRef, getTail(*headRef)); return;} // Driver codeint main(){ struct Node* a = NULL; push(&a, 5); push(&a, 20); push(&a, 4); push(&a, 3); push(&a, 30); cout << \"Linked List before sorting \\n\"; printList(a); quickSort(&a); cout << \"Linked List after sorting \\n\"; printList(a); return 0;}", "e": 4773, "s": 897, "text": null }, { "code": "// Java program for Quick Sort on Singly Linked List /*sort a linked list using quick sort*/publicclass QuickSortLinkedList { static class Node { int data; Node next; Node(int d) { this.data = d; this.next = null; } } Node head; void addNode(int data) { if (head == null) { head = new Node(data); return; } Node curr = head; while (curr.next != null) curr = curr.next; Node newNode = new Node(data); curr.next = newNode; } void printList(Node n) { while (n != null) { System.out.print(n.data); System.out.print(\" \"); n = n.next; } } // takes first and last node, // but do not break any links in // the whole linked list Node paritionLast(Node start, Node end) { if (start == end || start == null || end == null) return start; Node pivot_prev = start; Node curr = start; int pivot = end.data; // iterate till one before the end, // no need to iterate till the end // because end is pivot while (start != end) { if (start.data < pivot) { // keep tracks of last modified item pivot_prev = curr; int temp = curr.data; curr.data = start.data; start.data = temp; curr = curr.next; } start = start.next; } // swap the position of curr i.e. // next suitable index and pivot int temp = curr.data; curr.data = pivot; end.data = temp; // return one previous to current // because current is now pointing to pivot return pivot_prev; } void sort(Node start, Node end) { if(start == null || start == end|| start == end.next ) return; // split list and partition recurse Node pivot_prev = paritionLast(start, end); sort(start, pivot_prev); // if pivot is picked and moved to the start, // that means start and pivot is same // so pick from next of pivot if (pivot_prev != null && pivot_prev == start) sort(pivot_prev.next, end); // if pivot is in between of the list, // start from next of pivot, // since we have pivot_prev, so we move two nodes else if (pivot_prev != null && pivot_prev.next != null) sort(pivot_prev.next.next, end); } // Driver Codepublic static void main(String[] args) { QuickSortLinkedList list = new QuickSortLinkedList(); list.addNode(30); list.addNode(3); list.addNode(4); list.addNode(20); list.addNode(5); Node n = list.head; while (n.next != null) n = n.next; System.out.println(\"Linked List before sorting\"); list.printList(list.head); list.sort(list.head, n); System.out.println(\"\\nLinked List after sorting\"); list.printList(list.head); }} // This code is contributed by trinadumca", "e": 7959, "s": 4773, "text": null }, { "code": "''' sort a linked list using quick sort ''' class Node: def __init__(self, val): self.data = val self.next = None class QuickSortLinkedList: def __init__(self): self.head=None def addNode(self,data): if (self.head == None): self.head = Node(data) return curr = self.head while (curr.next != None): curr = curr.next newNode = Node(data) curr.next = newNode def printList(self,n): while (n != None): print(n.data, end=\" \") n = n.next ''' takes first and last node,but do not break any links in the whole linked list''' def paritionLast(self,start, end): if (start == end or start == None or end == None): return start pivot_prev = start curr = start pivot = end.data '''iterate till one before the end, no need to iterate till the end because end is pivot''' while (start != end): if (start.data < pivot): # keep tracks of last modified item pivot_prev = curr temp = curr.data curr.data = start.data start.data = temp curr = curr.next start = start.next '''swap the position of curr i.e. next suitable index and pivot''' temp = curr.data curr.data = pivot end.data = temp ''' return one previous to current because current is now pointing to pivot ''' return pivot_prev def sort(self, start, end): if(start == None or start == end or start == end.next): return # split list and partition recurse pivot_prev = self.paritionLast(start, end) self.sort(start, pivot_prev) ''' if pivot is picked and moved to the start, that means start and pivot is same so pick from next of pivot ''' if(pivot_prev != None and pivot_prev == start): self.sort(pivot_prev.next, end) # if pivot is in between of the list,start from next of pivot, # since we have pivot_prev, so we move two nodes elif (pivot_prev != None and pivot_prev.next != None): self.sort(pivot_prev.next.next, end) if __name__ == \"__main__\": ll = QuickSortLinkedList() ll.addNode(30) ll.addNode(3) ll.addNode(4) ll.addNode(20) ll.addNode(5) n = ll.head while (n.next != None): n = n.next print(\"\\nLinked List before sorting\") ll.printList(ll.head) ll.sort(ll.head, n) print(\"\\nLinked List after sorting\"); ll.printList(ll.head) # This code is contributed by humpheykibet.", "e": 10696, "s": 7959, "text": null }, { "code": "// C# program for Quick Sort on// Singly Linked Listusing System; /*sort a linked list using quick sort*/class GFG { public class Node { public int data; public Node next; public Node(int d) { this.data = d; this.next = null; } } Node head; void addNode(int data) { if (head == null) { head = new Node(data); return; } Node curr = head; while (curr.next != null) curr = curr.next; Node newNode = new Node(data); curr.next = newNode; } void printList(Node n) { while (n != null) { Console.Write(n.data); Console.Write(\" \"); n = n.next; } } // takes first and last node, // but do not break any links in // the whole linked list Node paritionLast(Node start, Node end) { if (start == end || start == null || end == null) return start; Node pivot_prev = start; Node curr = start; int pivot = end.data; // iterate till one before the end, // no need to iterate till the end // because end is pivot int temp; while (start != end) { if (start.data < pivot) { // keep tracks of last modified item pivot_prev = curr; temp = curr.data; curr.data = start.data; start.data = temp; curr = curr.next; } start = start.next; } // swap the position of curr i.e. // next suitable index and pivot temp = curr.data; curr.data = pivot; end.data = temp; // return one previous to current // because current is now pointing to pivot return pivot_prev; } void sort(Node start, Node end) { if (start == end) return; // split list and partition recurse Node pivot_prev = paritionLast(start, end); sort(start, pivot_prev); // if pivot is picked and moved to the start, // that means start and pivot is same // so pick from next of pivot if (pivot_prev != null && pivot_prev == start) sort(pivot_prev.next, end); // if pivot is in between of the list, // start from next of pivot, // since we have pivot_prev, so we move two nodes else if (pivot_prev != null && pivot_prev.next != null) sort(pivot_prev.next.next, end); } // Driver Code public static void Main(String[] args) { GFG list = new GFG(); list.addNode(30); list.addNode(3); list.addNode(4); list.addNode(20); list.addNode(5); Node n = list.head; while (n.next != null) n = n.next; Console.WriteLine(\"Linked List before sorting\"); list.printList(list.head); list.sort(list.head, n); Console.WriteLine(\"\\nLinked List after sorting\"); list.printList(list.head); }} // This code is contributed by 29AjayKumar", "e": 13819, "s": 10696, "text": null }, { "code": "<script>// javascript program for Quick Sort on Singly Linked List /*sort a linked list using quick sort*/ class Node { constructor(val) { this.data = val; this.next = null; } } var head; function addNode(data) { if (head == null) { head = new Node(data); return; } var curr = head; while (curr.next != null) curr = curr.next; var newNode = new Node(data); curr.next = newNode; } function printList( n) { while (n != null) { document.write(n.data); document.write(\" \"); n = n.next; } } // takes first and last node, // but do not break any links in // the whole linked list function paritionLast( start, end) { if (start == end || start == null || end == null) return start; var pivot_prev = start; var curr = start; var pivot = end.data; // iterate till one before the end, // no need to iterate till the end // because end is pivot while (start != end) { if (start.data < pivot) { // keep tracks of last modified item pivot_prev = curr; var temp = curr.data; curr.data = start.data; start.data = temp; curr = curr.next; } start = start.next; } // swap the position of curr i.e. // next suitable index and pivot var temp = curr.data; curr.data = pivot; end.data = temp; // return one previous to current // because current is now pointing to pivot return pivot_prev; } function sort( start, end) { if (start == null || start == end || start == end.next) return; // split list and partition recurse var pivot_prev = paritionLast(start, end); sort(start, pivot_prev); // if pivot is picked and moved to the start, // that means start and pivot is same // so pick from next of pivot if (pivot_prev != null && pivot_prev == start) sort(pivot_prev.next, end); // if pivot is in between of the list, // start from next of pivot, // since we have pivot_prev, so we move two nodes else if (pivot_prev != null && pivot_prev.next != null) sort(pivot_prev.next.next, end); } // Driver Code addNode(30); addNode(3); addNode(4); addNode(20); addNode(5); var n = head; while (n.next != null) n = n.next; document.write(\"Linked List before sorting<br/>\"); printList(head); sort(head, n); document.write(\"<br/>Linked List after sorting<br/>\"); printList(head); // This code contributed by umadevi9616 </script>", "e": 16734, "s": 13819, "text": null }, { "code": "#include <stdio.h>#include <stdlib.h> //Creating structurestruct Node{ int data; struct Node *next;};//Add new node at end of linked list void insert(struct Node **head, int value){ //Create dynamic node struct Node *node = (struct Node *) malloc(sizeof(struct Node)); if (node == NULL) { //checking memory overflow printf(\"Memory overflow\\n\"); } else { node->data = value; node->next = NULL; if ( *head == NULL) { *head = node; } else { struct Node *temp = *head; //finding last node while (temp->next != NULL) { temp = temp->next; } //adding node at last possition temp->next = node; } }}//Displaying linked list elementvoid display(struct Node *head){ if (head == NULL) { printf(\"Empty linked list\"); return; } struct Node *temp = head; printf(\"\\n Linked List :\"); while (temp != NULL) { printf(\" %d\", temp->data); temp = temp->next; }}//Finding last node of linked liststruct Node *last_node(struct Node *head){ struct Node *temp = head; while (temp != NULL && temp->next != NULL) { temp = temp->next; } return temp;}//We are Setting the given last node position to its proper positionstruct Node *parition(struct Node *first, struct Node *last){ //Get first node of given linked list struct Node *pivot = first; struct Node *front = first; int temp = 0; while (front != NULL && front != last) { if (front->data < last->data) { pivot = first; //Swapping node values temp = first->data; first->data = front->data; front->data = temp; //Visiting the next node first = first->next; } //Visiting the next node front = front->next; } //Change last node value to current node temp = first->data; first->data = last->data; last->data = temp; return pivot;}//Performing quick sort in the given linked listvoid quick_sort(struct Node *first, struct Node *last){ if (first == last) { return; } struct Node *pivot = parition(first, last); if (pivot != NULL && pivot->next != NULL) { quick_sort(pivot->next, last); } if (pivot != NULL && first != pivot) { quick_sort(first, pivot); }}int main(){ struct Node *head = NULL; //Create linked list insert( &head, 41); insert( &head, 5); insert( &head, 7); insert( &head, 22); insert( &head, 28); insert( &head, 63); insert( &head, 4); insert( &head, 8); insert( &head, 2); insert( &head, 11); printf(\"\\n Before Sort \"); display(head); quick_sort(head, last_node(head)); printf(\"\\n After Sort \"); display(head); return 0;}", "e": 19626, "s": 16734, "text": null }, { "code": null, "e": 19707, "s": 19626, "text": "Linked List before sorting \n30 3 4 20 5 \nLinked List after sorting \n3 4 5 20 30 " }, { "code": null, "e": 19735, "s": 19707, "text": "Time Complexity: O(nlogn) " }, { "code": null, "e": 19803, "s": 19735, "text": "It takes O(n^2) in worst case and O(nlogn) in average or best case." }, { "code": null, "e": 19825, "s": 19803, "text": "Auxiliary Space: O(n)" }, { "code": null, "e": 19873, "s": 19825, "text": "As extra space is used in recursion call stack." }, { "code": null, "e": 19880, "s": 19873, "text": "TrinaD" }, { "code": null, "e": 19892, "s": 19880, "text": "29AjayKumar" }, { "code": null, "e": 19909, "s": 19892, "text": "sudoaccessdenied" }, { "code": null, "e": 19921, "s": 19909, "text": "umadevi9616" }, { "code": null, "e": 19935, "s": 19921, "text": "humphreykibet" }, { "code": null, "e": 19947, "s": 19935, "text": "anikaseth98" }, { "code": null, "e": 19959, "s": 19947, "text": "kashishsoda" }, { "code": null, "e": 19975, "s": 19959, "text": "simranarora5sos" }, { "code": null, "e": 19985, "s": 19975, "text": "sayanc170" }, { "code": null, "e": 19999, "s": 19985, "text": "abhijeet19403" }, { "code": null, "e": 20016, "s": 19999, "text": "hardikkoriintern" }, { "code": null, "e": 20036, "s": 20016, "text": "Linked-List-Sorting" }, { "code": null, "e": 20047, "s": 20036, "text": "Quick Sort" }, { "code": null, "e": 20059, "s": 20047, "text": "Linked List" }, { "code": null, "e": 20067, "s": 20059, "text": "Sorting" }, { "code": null, "e": 20079, "s": 20067, "text": "Linked List" }, { "code": null, "e": 20087, "s": 20079, "text": "Sorting" }, { "code": null, "e": 20185, "s": 20087, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 20217, "s": 20185, "text": "Introduction to Data Structures" }, { "code": null, "e": 20281, "s": 20217, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 20302, "s": 20281, "text": "Linked List vs Array" }, { "code": null, "e": 20349, "s": 20302, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 20404, "s": 20349, "text": "Find Length of a Linked List (Iterative and Recursive)" }, { "code": null, "e": 20415, "s": 20404, "text": "Merge Sort" }, { "code": null, "e": 20437, "s": 20415, "text": "Bubble Sort Algorithm" }, { "code": null, "e": 20447, "s": 20437, "text": "QuickSort" }, { "code": null, "e": 20462, "s": 20447, "text": "Insertion Sort" } ]
Beautifulsoup – Kinds of objects
01 Jun, 2021 Prerequisites: BeautifulSoup In this article, we will discuss different types of objects in Beautifullsoup. When the string or HTML document is given in the constructor of BeautifulSoup, this constructor converts this document to different python objects. The four major and important objects are : BeautifulSoupTagNavigableStringComments BeautifulSoup Tag NavigableString Comments 1. BeautifulSoup Object: The BeautifulSoup object represents the parsed document as a whole. So, it is the complete document which we are trying to scrape. For most purposes, you can treat it as a Tag object. Python3 # importing the modulefrom bs4 import BeautifulSoup # parsing the documentsoup = BeautifulSoup('''<h1>Geeks for Geeks</h1>''', "html.parser") print(type(soup)) Output: <class 'bs4.BeautifulSoup'> 2. Tag Object: Tag object corresponds to an XML or HTML tag in the original document. Further, this object is usually used to extract a tag from the whole HTML document. Further, Beautiful Soup is not an HTTP client which means to scrap online websites you first have to download them using the requests module and then serve them to Beautiful Soup for scraping. Additionally, this object returns the first found tag if your document has multiple tags with the same name. Python3 # Import Beautiful Soupfrom bs4 import BeautifulSoup # Initialize the object with an HTML pagesoup = BeautifulSoup(''' <html> <b>Geeks for Geeks</b> </html> ''', "html.parser") # Get the tagtag = soup.b # Print the outputprint(type(tag)) Output: <class 'bs4.element.Tag'> The tag contains many methods and attributes. And two important features of a tag are its name and attributes. Name Attributes # Name : The name of the tag can be accessed through ‘.name’ as suffix. Syntax: tag.name Return: the type of tag it is. We can also change the name of the tag. Python3 # Import Beautiful Soupfrom bs4 import BeautifulSoup # Initialize the object with an HTML pagesoup = BeautifulSoup(''' <html> <b>Geeks for Geeks</b> </html> ''', "html.parser") # Get the tagtag = soup.b # Print the outputprint(tag.name) # changing the tagtag.name = "Strong"print(tag) Output: b <Strong>Geeks for Geeks</Strong> # Attributes : Example 1: Anything that is NOT tag, is basically an attribute and must contain a value. A tag object can have many attributes and can be accessed either through accessing the keys or directly accessing through value. We can also modify the attributes and their value. Python3 # Import Beautiful Soupfrom bs4 import BeautifulSoup # Initialize the object with an HTML pagesoup = BeautifulSoup(''' <html> <b class="gfg">Geeks for Geeks</b> </html> ''', "html.parser") # Get the tagtag = soup.b print(tag["class"]) # modifying classtag["class"] = "geeks"print(tag) # delete the class attributesdel tag["class"]print(tag) Output: ['gfg'] <b class="geeks">Geeks for Geeks</b> <b>Geeks for Geeks</b> Example 2: A document may contain multi-valued attributes and can be accessed using key-value pair. Python3 # Import Beautiful Soupfrom bs4 import BeautifulSoup # Initialize the object with an HTML page# soup for multi_valued attributessoup = BeautifulSoup(''' <html> <b class="gfg geeks">Geeks for Geeks</b> </html> ''', "html.parser") # Get the tagtag = soup.b print(tag["class"]) Output: ['gfg', 'geeks'] 3. NavigableString Object: A string corresponds to a bit of text within a tag. Beautiful Soup uses the NavigableString class to contain these bits of text. Syntax: <tag> String here </tag> Python3 # Import Beautiful Soupfrom bs4 import BeautifulSoup # Initialize the object with an HTML pagesoup = BeautifulSoup(''' <html> <b>Geeks for Geeks</b> </html> ''', "html.parser") # Get the tagtag = soup.b # Get the string inside the tagstring = tag.string # Print the outputprint(type(string)) Output: <class 'bs4.element.NavigableString'> 4. Comment Object: The Comment object is just a special type of NavigableString and is used to make the codebase more readable. Python3 # Import Beautiful Soupfrom bs4 import BeautifulSoup # Create the documentmarkup = "<b><!-- COMMENT --></b>" # Initialize the object with the documentsoup = BeautifulSoup(markup, "html.parser") # Get the whole comment inside b tagcomment = soup.b.string # Print the type of the commentprint(type(comment)) Output: <class 'bs4.element.Comment'> sweetyty Picked Python BeautifulSoup Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Jun, 2021" }, { "code": null, "e": 57, "s": 28, "text": "Prerequisites: BeautifulSoup" }, { "code": null, "e": 285, "s": 57, "text": "In this article, we will discuss different types of objects in Beautifullsoup. When the string or HTML document is given in the constructor of BeautifulSoup, this constructor converts this document to different python objects. " }, { "code": null, "e": 329, "s": 285, "text": "The four major and important objects are : " }, { "code": null, "e": 369, "s": 329, "text": "BeautifulSoupTagNavigableStringComments" }, { "code": null, "e": 383, "s": 369, "text": "BeautifulSoup" }, { "code": null, "e": 387, "s": 383, "text": "Tag" }, { "code": null, "e": 403, "s": 387, "text": "NavigableString" }, { "code": null, "e": 412, "s": 403, "text": "Comments" }, { "code": null, "e": 622, "s": 412, "text": "1. BeautifulSoup Object: The BeautifulSoup object represents the parsed document as a whole. So, it is the complete document which we are trying to scrape. For most purposes, you can treat it as a Tag object." }, { "code": null, "e": 630, "s": 622, "text": "Python3" }, { "code": "# importing the modulefrom bs4 import BeautifulSoup # parsing the documentsoup = BeautifulSoup('''<h1>Geeks for Geeks</h1>''', \"html.parser\") print(type(soup))", "e": 810, "s": 630, "text": null }, { "code": null, "e": 822, "s": 814, "text": "Output:" }, { "code": null, "e": 852, "s": 824, "text": "<class 'bs4.BeautifulSoup'>" }, { "code": null, "e": 1326, "s": 854, "text": "2. Tag Object: Tag object corresponds to an XML or HTML tag in the original document. Further, this object is usually used to extract a tag from the whole HTML document. Further, Beautiful Soup is not an HTTP client which means to scrap online websites you first have to download them using the requests module and then serve them to Beautiful Soup for scraping. Additionally, this object returns the first found tag if your document has multiple tags with the same name." }, { "code": null, "e": 1336, "s": 1328, "text": "Python3" }, { "code": "# Import Beautiful Soupfrom bs4 import BeautifulSoup # Initialize the object with an HTML pagesoup = BeautifulSoup(''' <html> <b>Geeks for Geeks</b> </html> ''', \"html.parser\") # Get the tagtag = soup.b # Print the outputprint(type(tag))", "e": 1596, "s": 1336, "text": null }, { "code": null, "e": 1608, "s": 1600, "text": "Output:" }, { "code": null, "e": 1636, "s": 1610, "text": "<class 'bs4.element.Tag'>" }, { "code": null, "e": 1749, "s": 1638, "text": "The tag contains many methods and attributes. And two important features of a tag are its name and attributes." }, { "code": null, "e": 1756, "s": 1751, "text": "Name" }, { "code": null, "e": 1767, "s": 1756, "text": "Attributes" }, { "code": null, "e": 1778, "s": 1769, "text": "# Name :" }, { "code": null, "e": 1843, "s": 1780, "text": "The name of the tag can be accessed through ‘.name’ as suffix." }, { "code": null, "e": 1862, "s": 1845, "text": "Syntax: tag.name" }, { "code": null, "e": 1893, "s": 1862, "text": "Return: the type of tag it is." }, { "code": null, "e": 1935, "s": 1895, "text": "We can also change the name of the tag." }, { "code": null, "e": 1945, "s": 1937, "text": "Python3" }, { "code": "# Import Beautiful Soupfrom bs4 import BeautifulSoup # Initialize the object with an HTML pagesoup = BeautifulSoup(''' <html> <b>Geeks for Geeks</b> </html> ''', \"html.parser\") # Get the tagtag = soup.b # Print the outputprint(tag.name) # changing the tagtag.name = \"Strong\"print(tag)", "e": 2252, "s": 1945, "text": null }, { "code": null, "e": 2264, "s": 2256, "text": "Output:" }, { "code": null, "e": 2301, "s": 2266, "text": "b\n<Strong>Geeks for Geeks</Strong>" }, { "code": null, "e": 2319, "s": 2303, "text": " # Attributes :" }, { "code": null, "e": 2590, "s": 2321, "text": "Example 1: Anything that is NOT tag, is basically an attribute and must contain a value. A tag object can have many attributes and can be accessed either through accessing the keys or directly accessing through value. We can also modify the attributes and their value." }, { "code": null, "e": 2600, "s": 2592, "text": "Python3" }, { "code": "# Import Beautiful Soupfrom bs4 import BeautifulSoup # Initialize the object with an HTML pagesoup = BeautifulSoup(''' <html> <b class=\"gfg\">Geeks for Geeks</b> </html> ''', \"html.parser\") # Get the tagtag = soup.b print(tag[\"class\"]) # modifying classtag[\"class\"] = \"geeks\"print(tag) # delete the class attributesdel tag[\"class\"]print(tag)", "e": 2961, "s": 2600, "text": null }, { "code": null, "e": 2973, "s": 2965, "text": "Output:" }, { "code": null, "e": 3043, "s": 2975, "text": "['gfg']\n<b class=\"geeks\">Geeks for Geeks</b>\n<b>Geeks for Geeks</b>" }, { "code": null, "e": 3145, "s": 3045, "text": "Example 2: A document may contain multi-valued attributes and can be accessed using key-value pair." }, { "code": null, "e": 3155, "s": 3147, "text": "Python3" }, { "code": "# Import Beautiful Soupfrom bs4 import BeautifulSoup # Initialize the object with an HTML page# soup for multi_valued attributessoup = BeautifulSoup(''' <html> <b class=\"gfg geeks\">Geeks for Geeks</b> </html> ''', \"html.parser\") # Get the tagtag = soup.b print(tag[\"class\"])", "e": 3446, "s": 3155, "text": null }, { "code": null, "e": 3454, "s": 3446, "text": "Output:" }, { "code": null, "e": 3471, "s": 3454, "text": "['gfg', 'geeks']" }, { "code": null, "e": 3627, "s": 3471, "text": "3. NavigableString Object: A string corresponds to a bit of text within a tag. Beautiful Soup uses the NavigableString class to contain these bits of text." }, { "code": null, "e": 3661, "s": 3627, "text": "Syntax: <tag> String here </tag>" }, { "code": null, "e": 3669, "s": 3661, "text": "Python3" }, { "code": "# Import Beautiful Soupfrom bs4 import BeautifulSoup # Initialize the object with an HTML pagesoup = BeautifulSoup(''' <html> <b>Geeks for Geeks</b> </html> ''', \"html.parser\") # Get the tagtag = soup.b # Get the string inside the tagstring = tag.string # Print the outputprint(type(string))", "e": 3983, "s": 3669, "text": null }, { "code": null, "e": 3995, "s": 3987, "text": "Output:" }, { "code": null, "e": 4035, "s": 3997, "text": "<class 'bs4.element.NavigableString'>" }, { "code": null, "e": 4165, "s": 4037, "text": "4. Comment Object: The Comment object is just a special type of NavigableString and is used to make the codebase more readable." }, { "code": null, "e": 4175, "s": 4167, "text": "Python3" }, { "code": "# Import Beautiful Soupfrom bs4 import BeautifulSoup # Create the documentmarkup = \"<b><!-- COMMENT --></b>\" # Initialize the object with the documentsoup = BeautifulSoup(markup, \"html.parser\") # Get the whole comment inside b tagcomment = soup.b.string # Print the type of the commentprint(type(comment))", "e": 4489, "s": 4175, "text": null }, { "code": null, "e": 4501, "s": 4493, "text": "Output:" }, { "code": null, "e": 4533, "s": 4503, "text": "<class 'bs4.element.Comment'>" }, { "code": null, "e": 4544, "s": 4535, "text": "sweetyty" }, { "code": null, "e": 4551, "s": 4544, "text": "Picked" }, { "code": null, "e": 4572, "s": 4551, "text": "Python BeautifulSoup" }, { "code": null, "e": 4579, "s": 4572, "text": "Python" }, { "code": null, "e": 4677, "s": 4579, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4709, "s": 4677, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4736, "s": 4709, "text": "Python Classes and Objects" }, { "code": null, "e": 4757, "s": 4736, "text": "Python OOPs Concepts" }, { "code": null, "e": 4780, "s": 4757, "text": "Introduction To PYTHON" }, { "code": null, "e": 4811, "s": 4780, "text": "Python | os.path.join() method" }, { "code": null, "e": 4867, "s": 4811, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 4909, "s": 4867, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 4951, "s": 4909, "text": "Check if element exists in list in Python" }, { "code": null, "e": 4990, "s": 4951, "text": "Python | Get unique values from a list" } ]
MySQL query to convert a single digit number to two-digit
For this, you can use LPAD() and pad a value on the left. Let us first create a table − mysql> create table DemoTable767 (Value varchar(100)); Query OK, 0 rows affected (1.40 sec) Insert some records in the table using insert command − mysql> insert into DemoTable767 values('4'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable767 values('5'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable767 values('6'); Query OK, 1 row affected (0.39 sec) mysql> insert into DemoTable767 values('1'); Query OK, 1 row affected (0.10 sec) Display all records from the table using select statement − mysql> select *from DemoTable767; This will produce the following output - +-------+ | Value | +-------+ | 4 | | 5 | | 6 | | 1 | +-------+ 4 rows in set (0.00 sec) Following is the query to convert a single digit number to two-digit by padding values − mysql> select lpad(Value,2,'0') from DemoTable767; This will produce the following output - +-------------------+ | lpad(Value,2,'0') | +-------------------+ | 04 | | 05 | | 06 | | 01 | +-------------------+ 4 rows in set (0.00 sec)
[ { "code": null, "e": 1245, "s": 1187, "text": "For this, you can use LPAD() and pad a value on the left." }, { "code": null, "e": 1275, "s": 1245, "text": "Let us first create a table −" }, { "code": null, "e": 1367, "s": 1275, "text": "mysql> create table DemoTable767 (Value varchar(100));\nQuery OK, 0 rows affected (1.40 sec)" }, { "code": null, "e": 1423, "s": 1367, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1747, "s": 1423, "text": "mysql> insert into DemoTable767 values('4');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable767 values('5');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable767 values('6');\nQuery OK, 1 row affected (0.39 sec)\nmysql> insert into DemoTable767 values('1');\nQuery OK, 1 row affected (0.10 sec)" }, { "code": null, "e": 1807, "s": 1747, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1841, "s": 1807, "text": "mysql> select *from DemoTable767;" }, { "code": null, "e": 1882, "s": 1841, "text": "This will produce the following output -" }, { "code": null, "e": 1987, "s": 1882, "text": "+-------+\n| Value |\n+-------+\n| 4 |\n| 5 |\n| 6 |\n| 1 |\n+-------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2076, "s": 1987, "text": "Following is the query to convert a single digit number to two-digit by padding values −" }, { "code": null, "e": 2127, "s": 2076, "text": "mysql> select lpad(Value,2,'0') from DemoTable767;" }, { "code": null, "e": 2168, "s": 2127, "text": "This will produce the following output -" }, { "code": null, "e": 2369, "s": 2168, "text": "+-------------------+\n| lpad(Value,2,'0') |\n+-------------------+\n| 04 |\n| 05 |\n| 06 |\n| 01 |\n+-------------------+\n4 rows in set (0.00 sec)" } ]
PyQt5 – How to add image in window ?
03 Aug, 2021 In this article, we will see how to add image to a window. The basic idea of doing this is first of all loading the image using QPixmap and adding the loaded image to the Label then resizing the label according to the dimensions of the image, although the resizing part is optional. In order to use Qpixmap and other stuff we have to import following libraries: from PyQt5.QtWidgets import * from PyQt5.QtGui import QPixmap import sys For loading image : Syntax : pixmap = QPixmap('image.png') Argument : Image name if image is in same folder else file path. For adding image to label : Syntax : label.setPixmap(pixmap) Argument : It takes QPixmap object as argument. Code : Python3 # importing the required libraries from PyQt5.QtWidgets import *from PyQt5.QtGui import QPixmapimport sys class Window(QMainWindow): def __init__(self): super().__init__() self.acceptDrops() # set the title self.setWindowTitle("Image") # setting the geometry of window self.setGeometry(0, 0, 400, 300) # creating label self.label = QLabel(self) # loading image self.pixmap = QPixmap('image.png') # adding image to label self.label.setPixmap(self.pixmap) # Optional, resize label to image size self.label.resize(self.pixmap.width(), self.pixmap.height()) # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : arorakashish0911 Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Aug, 2021" }, { "code": null, "e": 311, "s": 28, "text": "In this article, we will see how to add image to a window. The basic idea of doing this is first of all loading the image using QPixmap and adding the loaded image to the Label then resizing the label according to the dimensions of the image, although the resizing part is optional." }, { "code": null, "e": 391, "s": 311, "text": "In order to use Qpixmap and other stuff we have to import following libraries: " }, { "code": null, "e": 464, "s": 391, "text": "from PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import QPixmap\nimport sys" }, { "code": null, "e": 494, "s": 464, "text": "For loading image : Syntax : " }, { "code": null, "e": 524, "s": 494, "text": "pixmap = QPixmap('image.png')" }, { "code": null, "e": 629, "s": 524, "text": "Argument : Image name if image is in same folder else file path. For adding image to label : Syntax : " }, { "code": null, "e": 653, "s": 629, "text": "label.setPixmap(pixmap)" }, { "code": null, "e": 701, "s": 653, "text": "Argument : It takes QPixmap object as argument." }, { "code": null, "e": 710, "s": 701, "text": "Code : " }, { "code": null, "e": 718, "s": 710, "text": "Python3" }, { "code": "# importing the required libraries from PyQt5.QtWidgets import *from PyQt5.QtGui import QPixmapimport sys class Window(QMainWindow): def __init__(self): super().__init__() self.acceptDrops() # set the title self.setWindowTitle(\"Image\") # setting the geometry of window self.setGeometry(0, 0, 400, 300) # creating label self.label = QLabel(self) # loading image self.pixmap = QPixmap('image.png') # adding image to label self.label.setPixmap(self.pixmap) # Optional, resize label to image size self.label.resize(self.pixmap.width(), self.pixmap.height()) # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 1600, "s": 718, "text": null }, { "code": null, "e": 1610, "s": 1600, "text": "Output : " }, { "code": null, "e": 1629, "s": 1612, "text": "arorakashish0911" }, { "code": null, "e": 1640, "s": 1629, "text": "Python-gui" }, { "code": null, "e": 1652, "s": 1640, "text": "Python-PyQt" }, { "code": null, "e": 1659, "s": 1652, "text": "Python" } ]
Limitation of Distributed System
31 Jan, 2020 Distributed System is a collection of self-governing computer systems efficient of transmission and cooperation among each other by the means of interconnections between their hardware and software. It is a collection of loosely coupled processor that appears to its users a single systematic system. Distributed systems has various limitations such as in distributed system there is not any presence of a global state. This differentiates distributed system computing from databases in which a steady global state is maintained. Distributed system limitations has the impact on both design and implementation of distributed systems. There are mainly two limitations of the distributed system which are as following: 1. Absence of a Global Clock 2. Absence of Shared Memory The above two limitations of the distributed system are explained as following below: 1. Absence of a Global Clock:In a distributed system there are a lot of systems and each system has its own clock. Each clock on each system is running at a different rate or granularity leading to them asynchronous. In starting the clocks are regulated to keep them consistent, but only after one local clock cycle they are out of the synchronization and no clock has the exact time.Time is known for a certain precision because it is used for the following in distributed system: Temporal ordering of events Collecting up-to-date information on the state of the integrated system Scheduling of processes There are restrictions on the precision of time by which processes in a distributed system can synchronize their clocks due to asynchronous message passing. Every clock in distributed system is synchronize with a more reliable clock, but due to transmission and execution time lapses the clocks becomes different. Absence of global clock make more difficult the algorithm for designing and debugging of distributed system. 2. Absence of Shared Memory:Distributed systems have not any physically shared memory, all computers in the distributed system have their own specific physical memory. As computer in the distributed system do not share the common memory, it is impossible for any one system to know the global state of the full distributed system. Process in the distributed system obtains coherent view of the system but in actual that view is partial view of the system.As in distributed system there is an absence of a global state, it is challenging to recognize any global property of the system. The global state in distributed system is divided by many number of computers into smaller entities. Distributed System Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Differences between TCP and UDP Types of Network Topology RSA Algorithm in Cryptography TCP Server-Client implementation in C Socket Programming in Python Differences between IPv4 and IPv6 GSM in Wireless Communication Wireless Application Protocol Secure Socket Layer (SSL) Mobile Internet Protocol (or Mobile IP)
[ { "code": null, "e": 52, "s": 24, "text": "\n31 Jan, 2020" }, { "code": null, "e": 582, "s": 52, "text": "Distributed System is a collection of self-governing computer systems efficient of transmission and cooperation among each other by the means of interconnections between their hardware and software. It is a collection of loosely coupled processor that appears to its users a single systematic system. Distributed systems has various limitations such as in distributed system there is not any presence of a global state. This differentiates distributed system computing from databases in which a steady global state is maintained." }, { "code": null, "e": 769, "s": 582, "text": "Distributed system limitations has the impact on both design and implementation of distributed systems. There are mainly two limitations of the distributed system which are as following:" }, { "code": null, "e": 826, "s": 769, "text": "1. Absence of a Global Clock\n2. Absence of Shared Memory" }, { "code": null, "e": 912, "s": 826, "text": "The above two limitations of the distributed system are explained as following below:" }, { "code": null, "e": 1394, "s": 912, "text": "1. Absence of a Global Clock:In a distributed system there are a lot of systems and each system has its own clock. Each clock on each system is running at a different rate or granularity leading to them asynchronous. In starting the clocks are regulated to keep them consistent, but only after one local clock cycle they are out of the synchronization and no clock has the exact time.Time is known for a certain precision because it is used for the following in distributed system:" }, { "code": null, "e": 1422, "s": 1394, "text": "Temporal ordering of events" }, { "code": null, "e": 1494, "s": 1422, "text": "Collecting up-to-date information on the state of the integrated system" }, { "code": null, "e": 1518, "s": 1494, "text": "Scheduling of processes" }, { "code": null, "e": 1941, "s": 1518, "text": "There are restrictions on the precision of time by which processes in a distributed system can synchronize their clocks due to asynchronous message passing. Every clock in distributed system is synchronize with a more reliable clock, but due to transmission and execution time lapses the clocks becomes different. Absence of global clock make more difficult the algorithm for designing and debugging of distributed system." }, { "code": null, "e": 2627, "s": 1941, "text": "2. Absence of Shared Memory:Distributed systems have not any physically shared memory, all computers in the distributed system have their own specific physical memory. As computer in the distributed system do not share the common memory, it is impossible for any one system to know the global state of the full distributed system. Process in the distributed system obtains coherent view of the system but in actual that view is partial view of the system.As in distributed system there is an absence of a global state, it is challenging to recognize any global property of the system. The global state in distributed system is divided by many number of computers into smaller entities." }, { "code": null, "e": 2646, "s": 2627, "text": "Distributed System" }, { "code": null, "e": 2664, "s": 2646, "text": "Computer Networks" }, { "code": null, "e": 2682, "s": 2664, "text": "Computer Networks" }, { "code": null, "e": 2780, "s": 2682, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2812, "s": 2780, "text": "Differences between TCP and UDP" }, { "code": null, "e": 2838, "s": 2812, "text": "Types of Network Topology" }, { "code": null, "e": 2868, "s": 2838, "text": "RSA Algorithm in Cryptography" }, { "code": null, "e": 2906, "s": 2868, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 2935, "s": 2906, "text": "Socket Programming in Python" }, { "code": null, "e": 2969, "s": 2935, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 2999, "s": 2969, "text": "GSM in Wireless Communication" }, { "code": null, "e": 3029, "s": 2999, "text": "Wireless Application Protocol" }, { "code": null, "e": 3055, "s": 3029, "text": "Secure Socket Layer (SSL)" } ]
GUI to Shutdown, Restart and Logout from the PC using Python
21 Oct, 2021 In this article, we are going to write a python script to shut down or Restart or Logout your system and bind it with GUI Application. The OS module in Python provides functions for interacting with the operating system. OS is an inbuilt library python. Syntax : For shutdown your system : os.system(“shutdown /s /t 1”) For restart your system : os.system(“shutdown /r /t 1”) For Logout your system : os.system(“shutdown -l”) Implementation GUI Application using Tkinter: Python3 # import modulesfrom tkinter import *import os # user define functiondef shutdown(): return os.system("shutdown /s /t 1") def restart(): return os.system("shutdown /r /t 1") def logout(): return os.system("shutdown -l") # tkinter objectmaster = Tk() # background set to greymaster.configure(bg='light grey') # creating a button using the widget# Buttons that will call the submit functionButton(master, text="Shutdown", command=shutdown).grid(row=0)Button(master, text="Restart", command=restart).grid(row=1)Button(master, text="Log out", command=logout).grid(row=2) mainloop() Output: Note: Please ensure that you save and close all the programs before running this code on the IDLE, as this program will immediately shutdown and restart your computer. saurabh1990aror Python Tkinter-exercises Python-tkinter python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Python OOPs Concepts How to drop one or multiple columns in Pandas Dataframe Introduction To PYTHON How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 54, "s": 26, "text": "\n21 Oct, 2021" }, { "code": null, "e": 190, "s": 54, "text": "In this article, we are going to write a python script to shut down or Restart or Logout your system and bind it with GUI Application. " }, { "code": null, "e": 309, "s": 190, "text": "The OS module in Python provides functions for interacting with the operating system. OS is an inbuilt library python." }, { "code": null, "e": 318, "s": 309, "text": "Syntax :" }, { "code": null, "e": 375, "s": 318, "text": "For shutdown your system : os.system(“shutdown /s /t 1”)" }, { "code": null, "e": 431, "s": 375, "text": "For restart your system : os.system(“shutdown /r /t 1”)" }, { "code": null, "e": 481, "s": 431, "text": "For Logout your system : os.system(“shutdown -l”)" }, { "code": null, "e": 527, "s": 481, "text": "Implementation GUI Application using Tkinter:" }, { "code": null, "e": 535, "s": 527, "text": "Python3" }, { "code": "# import modulesfrom tkinter import *import os # user define functiondef shutdown(): return os.system(\"shutdown /s /t 1\") def restart(): return os.system(\"shutdown /r /t 1\") def logout(): return os.system(\"shutdown -l\") # tkinter objectmaster = Tk() # background set to greymaster.configure(bg='light grey') # creating a button using the widget# Buttons that will call the submit functionButton(master, text=\"Shutdown\", command=shutdown).grid(row=0)Button(master, text=\"Restart\", command=restart).grid(row=1)Button(master, text=\"Log out\", command=logout).grid(row=2) mainloop()", "e": 1124, "s": 535, "text": null }, { "code": null, "e": 1132, "s": 1124, "text": "Output:" }, { "code": null, "e": 1300, "s": 1132, "text": "Note: Please ensure that you save and close all the programs before running this code on the IDLE, as this program will immediately shutdown and restart your computer." }, { "code": null, "e": 1316, "s": 1300, "text": "saurabh1990aror" }, { "code": null, "e": 1341, "s": 1316, "text": "Python Tkinter-exercises" }, { "code": null, "e": 1356, "s": 1341, "text": "Python-tkinter" }, { "code": null, "e": 1371, "s": 1356, "text": "python-utility" }, { "code": null, "e": 1378, "s": 1371, "text": "Python" }, { "code": null, "e": 1476, "s": 1378, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1508, "s": 1476, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1535, "s": 1508, "text": "Python Classes and Objects" }, { "code": null, "e": 1566, "s": 1535, "text": "Python | os.path.join() method" }, { "code": null, "e": 1587, "s": 1566, "text": "Python OOPs Concepts" }, { "code": null, "e": 1643, "s": 1587, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1666, "s": 1643, "text": "Introduction To PYTHON" }, { "code": null, "e": 1708, "s": 1666, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1750, "s": 1708, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1789, "s": 1750, "text": "Python | datetime.timedelta() function" } ]
SQL - CHECK Constraint
The CHECK Constraint enables a condition to check the value being entered into a record. If the condition evaluates to false, the record violates the constraint and isn't entered the table. For example, the following program creates a new table called CUSTOMERS and adds five columns. Here, we add a CHECK with AGE column, so that you cannot have any CUSTOMER who is below 18 years. CREATE TABLE CUSTOMERS( ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT NOT NULL CHECK (AGE >= 18), ADDRESS CHAR (25) , SALARY DECIMAL (18, 2), PRIMARY KEY (ID) ); If the CUSTOMERS table has already been created, then to add a CHECK constraint to AGE column, you would write a statement like the one given below. ALTER TABLE CUSTOMERS MODIFY AGE INT NOT NULL CHECK (AGE >= 18 ); You can also use the following syntax, which supports naming the constraint in multiple columns as well − ALTER TABLE CUSTOMERS ADD CONSTRAINT myCheckConstraint CHECK(AGE >= 18); To drop a CHECK constraint, use the following SQL syntax. This syntax does not work with MySQL. ALTER TABLE CUSTOMERS DROP CONSTRAINT myCheckConstraint;
[ { "code": null, "e": 2777, "s": 2587, "text": "The CHECK Constraint enables a condition to check the value being entered into a record. If the condition evaluates to false, the record violates the constraint and isn't entered the table." }, { "code": null, "e": 2970, "s": 2777, "text": "For example, the following program creates a new table called CUSTOMERS and adds five columns. Here, we add a CHECK with AGE column, so that you cannot have any CUSTOMER who is below 18 years." }, { "code": null, "e": 3200, "s": 2970, "text": "CREATE TABLE CUSTOMERS(\n ID INT NOT NULL,\n NAME VARCHAR (20) NOT NULL,\n AGE INT NOT NULL CHECK (AGE >= 18),\n ADDRESS CHAR (25) ,\n SALARY DECIMAL (18, 2), \n PRIMARY KEY (ID)\n);" }, { "code": null, "e": 3349, "s": 3200, "text": "If the CUSTOMERS table has already been created, then to add a CHECK constraint to AGE column, you would write a statement like the one given below." }, { "code": null, "e": 3418, "s": 3349, "text": "ALTER TABLE CUSTOMERS\n MODIFY AGE INT NOT NULL CHECK (AGE >= 18 );" }, { "code": null, "e": 3524, "s": 3418, "text": "You can also use the following syntax, which supports naming the constraint in multiple columns as well −" }, { "code": null, "e": 3600, "s": 3524, "text": "ALTER TABLE CUSTOMERS\n ADD CONSTRAINT myCheckConstraint CHECK(AGE >= 18);" }, { "code": null, "e": 3696, "s": 3600, "text": "To drop a CHECK constraint, use the following SQL syntax. This syntax does not work with MySQL." } ]
How to Group Pandas DataFrame By Date and Time ?
08 May, 2021 In this article, we will discuss how to group by a dataframe on the basis of date and time in Pandas. We will see the way to group a timeseries dataframe by Year, Month, days, etc. Additionally, we’ll also see the way to groupby time objects like minutes. Pandas GroupBy allows us to specify a groupby instruction for an object. This specified instruction will select a column via the key parameter of the grouper function along with the level and/or axis parameters if given, a level of the index of the target object/column. Syntax: pandas.Grouper(key=None, level=None, freq=None, axis=0, sort=False) Below are some examples that depict how to group by a dataframe on the basis of date and time using pandas Grouper class. Example 1: Group by month Python3 # importing modulesimport pandas as pd # creating a dataframe dfdf = pd.DataFrame( { "Date": [ pd.Timestamp("2000-11-02"), pd.Timestamp("2000-01-02"), pd.Timestamp("2000-01-09"), pd.Timestamp("2000-03-11"), pd.Timestamp("2000-01-26"), pd.Timestamp("2000-02-16") ], "ID": [1, 2, 3, 4, 5, 6], "Price": [140, 120, 230, 40, 100, 450] }) # show dfdisplay(df) # applying the groupby function on dfdf.groupby(pd.Grouper(key='Date', axis=0, freq='M')).sum() Output: In the above example, the dataframe is groupby by the Date column. As we have provided freq = ‘M’ which means month, so the data is grouped month-wise till the last date of every month and provided sum of price column. We have not provided value for all months, then also groupby function displayed data for all months and assigned value 0 for other months. Example 2: Group by days Python3 # importing modulesimport pandas as pd # creating a dataframe dfdf = pd.DataFrame( { "Date": [ pd.Timestamp("2000-11-02"), pd.Timestamp("2000-01-02"), pd.Timestamp("2000-01-09"), pd.Timestamp("2000-03-11"), pd.Timestamp("2000-01-26"), pd.Timestamp("2000-02-16") ], "ID": [1, 2, 3, 4, 5, 6], "Price": [140, 120, 230, 40, 100, 450] }) # display dataframedisplay(df) # applying groupbydf.groupby(pd.Grouper(key='Date', axis=0, freq='2D', sort=True)).sum() Output: In the above example, the dataframe is groupby by the Date column. As we have provided freq = ‘5D’ which means five days, so the data grouped by interval 5 days of every month till the last date given in the date column. Example 3: Group by year Python3 # importing moduleimport pandas as pd # creating dataframe with datetimedf = pd.DataFrame( { "Date": [ # here the date contains # different years pd.Timestamp("2010-11-02"), pd.Timestamp("2011-01-02"), pd.Timestamp("2013-01-09"), pd.Timestamp("2014-03-11"), pd.Timestamp("2015-01-26"), pd.Timestamp("2012-02-16") ], "ID": [1, 2, 3, 4, 5, 6], "Price": [140, 120, 230, 40, 100, 450] })# show dfdisplay(df) # applying groupby functiondf.groupby(pd.Grouper(key='Date', freq='2Y')).sum() Output: In the above example, the dataframe is groupby by the Date column. As we have provided freq = ‘2Y’ which means 2 years, so the data is grouped in the interval of 2 years. Example 4: Group by minutes Python3 # importing moduleimport pandas as pd # create an array of 5 dates starting # at '2015-02-24', one per minutedates = pd.date_range('2015-02-24', periods=10, freq='T') # creating dataframe with above array # of datesdf = pd.DataFrame({"Date": dates, "ID": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], "Price": [140, 120, 230, 40, 100, 450, 234, 785, 12, 42]}) # display dataframedisplay(df) # applied groupby functiondf.groupby(pd.Grouper(key='Date', freq='2min')).sum() Output: In the above example, the data is grouped in intervals of every 2 minutes. Picked Python pandas-groupby Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 May, 2021" }, { "code": null, "e": 284, "s": 28, "text": "In this article, we will discuss how to group by a dataframe on the basis of date and time in Pandas. We will see the way to group a timeseries dataframe by Year, Month, days, etc. Additionally, we’ll also see the way to groupby time objects like minutes." }, { "code": null, "e": 555, "s": 284, "text": "Pandas GroupBy allows us to specify a groupby instruction for an object. This specified instruction will select a column via the key parameter of the grouper function along with the level and/or axis parameters if given, a level of the index of the target object/column." }, { "code": null, "e": 631, "s": 555, "text": "Syntax: pandas.Grouper(key=None, level=None, freq=None, axis=0, sort=False)" }, { "code": null, "e": 753, "s": 631, "text": "Below are some examples that depict how to group by a dataframe on the basis of date and time using pandas Grouper class." }, { "code": null, "e": 779, "s": 753, "text": "Example 1: Group by month" }, { "code": null, "e": 787, "s": 779, "text": "Python3" }, { "code": "# importing modulesimport pandas as pd # creating a dataframe dfdf = pd.DataFrame( { \"Date\": [ pd.Timestamp(\"2000-11-02\"), pd.Timestamp(\"2000-01-02\"), pd.Timestamp(\"2000-01-09\"), pd.Timestamp(\"2000-03-11\"), pd.Timestamp(\"2000-01-26\"), pd.Timestamp(\"2000-02-16\") ], \"ID\": [1, 2, 3, 4, 5, 6], \"Price\": [140, 120, 230, 40, 100, 450] }) # show dfdisplay(df) # applying the groupby function on dfdf.groupby(pd.Grouper(key='Date', axis=0, freq='M')).sum()", "e": 1362, "s": 787, "text": null }, { "code": null, "e": 1370, "s": 1362, "text": "Output:" }, { "code": null, "e": 1728, "s": 1370, "text": "In the above example, the dataframe is groupby by the Date column. As we have provided freq = ‘M’ which means month, so the data is grouped month-wise till the last date of every month and provided sum of price column. We have not provided value for all months, then also groupby function displayed data for all months and assigned value 0 for other months." }, { "code": null, "e": 1753, "s": 1728, "text": "Example 2: Group by days" }, { "code": null, "e": 1761, "s": 1753, "text": "Python3" }, { "code": "# importing modulesimport pandas as pd # creating a dataframe dfdf = pd.DataFrame( { \"Date\": [ pd.Timestamp(\"2000-11-02\"), pd.Timestamp(\"2000-01-02\"), pd.Timestamp(\"2000-01-09\"), pd.Timestamp(\"2000-03-11\"), pd.Timestamp(\"2000-01-26\"), pd.Timestamp(\"2000-02-16\") ], \"ID\": [1, 2, 3, 4, 5, 6], \"Price\": [140, 120, 230, 40, 100, 450] }) # display dataframedisplay(df) # applying groupbydf.groupby(pd.Grouper(key='Date', axis=0, freq='2D', sort=True)).sum()", "e": 2339, "s": 1761, "text": null }, { "code": null, "e": 2347, "s": 2339, "text": "Output:" }, { "code": null, "e": 2568, "s": 2347, "text": "In the above example, the dataframe is groupby by the Date column. As we have provided freq = ‘5D’ which means five days, so the data grouped by interval 5 days of every month till the last date given in the date column." }, { "code": null, "e": 2593, "s": 2568, "text": "Example 3: Group by year" }, { "code": null, "e": 2601, "s": 2593, "text": "Python3" }, { "code": "# importing moduleimport pandas as pd # creating dataframe with datetimedf = pd.DataFrame( { \"Date\": [ # here the date contains # different years pd.Timestamp(\"2010-11-02\"), pd.Timestamp(\"2011-01-02\"), pd.Timestamp(\"2013-01-09\"), pd.Timestamp(\"2014-03-11\"), pd.Timestamp(\"2015-01-26\"), pd.Timestamp(\"2012-02-16\") ], \"ID\": [1, 2, 3, 4, 5, 6], \"Price\": [140, 120, 230, 40, 100, 450] })# show dfdisplay(df) # applying groupby functiondf.groupby(pd.Grouper(key='Date', freq='2Y')).sum()", "e": 3210, "s": 2601, "text": null }, { "code": null, "e": 3218, "s": 3210, "text": "Output:" }, { "code": null, "e": 3389, "s": 3218, "text": "In the above example, the dataframe is groupby by the Date column. As we have provided freq = ‘2Y’ which means 2 years, so the data is grouped in the interval of 2 years." }, { "code": null, "e": 3417, "s": 3389, "text": "Example 4: Group by minutes" }, { "code": null, "e": 3425, "s": 3417, "text": "Python3" }, { "code": "# importing moduleimport pandas as pd # create an array of 5 dates starting # at '2015-02-24', one per minutedates = pd.date_range('2015-02-24', periods=10, freq='T') # creating dataframe with above array # of datesdf = pd.DataFrame({\"Date\": dates, \"ID\": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], \"Price\": [140, 120, 230, 40, 100, 450, 234, 785, 12, 42]}) # display dataframedisplay(df) # applied groupby functiondf.groupby(pd.Grouper(key='Date', freq='2min')).sum()", "e": 3905, "s": 3425, "text": null }, { "code": null, "e": 3913, "s": 3905, "text": "Output:" }, { "code": null, "e": 3988, "s": 3913, "text": "In the above example, the data is grouped in intervals of every 2 minutes." }, { "code": null, "e": 3995, "s": 3988, "text": "Picked" }, { "code": null, "e": 4017, "s": 3995, "text": "Python pandas-groupby" }, { "code": null, "e": 4031, "s": 4017, "text": "Python-pandas" }, { "code": null, "e": 4038, "s": 4031, "text": "Python" } ]
Python | time.clock_gettime_ns() method
17 Sep, 2019 Time module in Python provides various time-related functions. This module comes under Python’s standard utility modules. time.clock_gettime_ns() method of Time module is used to get the time (in nanoseconds) of the specified clock clk_id. Basically, clk_id is a integer value which represents the id of the clock. Following are the constants available on UNIX platforms that can be used as value of clk_id parameter: Syntax: time.clock_gettime(clk_id) Parameter:clk_id: A clk_id constant or an integer value representing clk_id of the clock. Return type: This method returns a float value which represents the time in nanoseconds of the specified clock clk_id. Code #1: Use of time.clock_gettime_ns() method # Python program to explain time.clock_gettime_ns() method # importing time moduleimport time # clk_id for System-wide real-time clockclk_id1 = time.CLOCK_REALTIME # clk_id for monotonic clockclk_id2 = time.CLOCK_MONOTONIC # clk_id for monotonic (Raw hardware# based time) clockclk_id3 = time.CLOCK_MONOTONIC # clk_id for Thread-specific CPU-time clockclk_id4 = time.CLOCK_THREAD_CPUTIME_ID # clk_id for High-resolution# per-process timer from the CPUclk_id5 = time.CLOCK_PROCESS_CPUTIME_ID # Get the time (in nanoseconds) of the above # specified clock clk_ids# using time.clock_gettime_ns() methodt1 = time.clock_gettime_ns(clk_id1)t2 = time.clock_gettime_ns(clk_id2)t3 = time.clock_gettime_ns(clk_id3)t4 = time.clock_gettime_ns(clk_id4)t5 = time.clock_gettime_ns(clk_id5) # Print the time (in nanoseconds) of # different clock clk_idsprint("System-wide real-time clock time: % d nanoseconds" % t1)print("Monotonic clock time: % d nanoseconds" % t2)print("Monotonic (raw-hardware based) clock time: % d nanoseconds" % t3)print("Thread-specific CPU time clock: % d nanoseconds" % t4)print("Per-process timer from the CPU: % d nanoseconds" % t5) System-wide real-time clock time: 1568588052857445167 nanoseconds Monotonic clock time: 13129927039288 nanoseconds Monotonic (raw-hardware based) clock time: 13129927039811 nanoseconds Thread-specific CPU time clock: 27169892 nanoseconds Per-process timer from the CPU: 27171779 nanoseconds Code #2: Using an integer value as parameter of time.clock_gettime_ns() method # Python program to explain time.clock_gettime_ns() method # importing time moduleimport time # value of clk_id for time.CLOCK_REALTIME# clock id constant which represents# System-wide real-time clock is 0clk_id1 = 0 # value of clk_id for time.CLOCK_MONOTONIC# clock id constant which represents# a monotonic clock is 2clk_id2 = 2 # Get the time in nanoseconds)# for the specified clock clk_ids# using time.clock_gettime_ns() methodt1 = time.clock_gettime_ns(clk_id1)t2 = time.clock_gettime_ns(clk_id2) # Print the time in nanosecondsprint("System-wide real-time clock time: % d nanoseconds" % t1)print("Monotonic clock time: % d nanoseconds" % t2) System-wide real-time clock time: 1568588180971305067 nanoseconds Monotonic clock time: 13258040899143 nanoseconds Reference: https://docs.python.org/3/library/time.html#time.clock_gettime python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Sep, 2019" }, { "code": null, "e": 150, "s": 28, "text": "Time module in Python provides various time-related functions. This module comes under Python’s standard utility modules." }, { "code": null, "e": 343, "s": 150, "text": "time.clock_gettime_ns() method of Time module is used to get the time (in nanoseconds) of the specified clock clk_id. Basically, clk_id is a integer value which represents the id of the clock." }, { "code": null, "e": 446, "s": 343, "text": "Following are the constants available on UNIX platforms that can be used as value of clk_id parameter:" }, { "code": null, "e": 481, "s": 446, "text": "Syntax: time.clock_gettime(clk_id)" }, { "code": null, "e": 571, "s": 481, "text": "Parameter:clk_id: A clk_id constant or an integer value representing clk_id of the clock." }, { "code": null, "e": 690, "s": 571, "text": "Return type: This method returns a float value which represents the time in nanoseconds of the specified clock clk_id." }, { "code": null, "e": 737, "s": 690, "text": "Code #1: Use of time.clock_gettime_ns() method" }, { "code": "# Python program to explain time.clock_gettime_ns() method # importing time moduleimport time # clk_id for System-wide real-time clockclk_id1 = time.CLOCK_REALTIME # clk_id for monotonic clockclk_id2 = time.CLOCK_MONOTONIC # clk_id for monotonic (Raw hardware# based time) clockclk_id3 = time.CLOCK_MONOTONIC # clk_id for Thread-specific CPU-time clockclk_id4 = time.CLOCK_THREAD_CPUTIME_ID # clk_id for High-resolution# per-process timer from the CPUclk_id5 = time.CLOCK_PROCESS_CPUTIME_ID # Get the time (in nanoseconds) of the above # specified clock clk_ids# using time.clock_gettime_ns() methodt1 = time.clock_gettime_ns(clk_id1)t2 = time.clock_gettime_ns(clk_id2)t3 = time.clock_gettime_ns(clk_id3)t4 = time.clock_gettime_ns(clk_id4)t5 = time.clock_gettime_ns(clk_id5) # Print the time (in nanoseconds) of # different clock clk_idsprint(\"System-wide real-time clock time: % d nanoseconds\" % t1)print(\"Monotonic clock time: % d nanoseconds\" % t2)print(\"Monotonic (raw-hardware based) clock time: % d nanoseconds\" % t3)print(\"Thread-specific CPU time clock: % d nanoseconds\" % t4)print(\"Per-process timer from the CPU: % d nanoseconds\" % t5) ", "e": 1899, "s": 737, "text": null }, { "code": null, "e": 2191, "s": 1899, "text": "System-wide real-time clock time: 1568588052857445167 nanoseconds\nMonotonic clock time: 13129927039288 nanoseconds\nMonotonic (raw-hardware based) clock time: 13129927039811 nanoseconds\nThread-specific CPU time clock: 27169892 nanoseconds\nPer-process timer from the CPU: 27171779 nanoseconds\n" }, { "code": null, "e": 2270, "s": 2191, "text": "Code #2: Using an integer value as parameter of time.clock_gettime_ns() method" }, { "code": "# Python program to explain time.clock_gettime_ns() method # importing time moduleimport time # value of clk_id for time.CLOCK_REALTIME# clock id constant which represents# System-wide real-time clock is 0clk_id1 = 0 # value of clk_id for time.CLOCK_MONOTONIC# clock id constant which represents# a monotonic clock is 2clk_id2 = 2 # Get the time in nanoseconds)# for the specified clock clk_ids# using time.clock_gettime_ns() methodt1 = time.clock_gettime_ns(clk_id1)t2 = time.clock_gettime_ns(clk_id2) # Print the time in nanosecondsprint(\"System-wide real-time clock time: % d nanoseconds\" % t1)print(\"Monotonic clock time: % d nanoseconds\" % t2)", "e": 2928, "s": 2270, "text": null }, { "code": null, "e": 3044, "s": 2928, "text": "System-wide real-time clock time: 1568588180971305067 nanoseconds\nMonotonic clock time: 13258040899143 nanoseconds\n" }, { "code": null, "e": 3118, "s": 3044, "text": "Reference: https://docs.python.org/3/library/time.html#time.clock_gettime" }, { "code": null, "e": 3133, "s": 3118, "text": "python-utility" }, { "code": null, "e": 3140, "s": 3133, "text": "Python" } ]
Intersection of two Sorted Linked Lists
01 Jul, 2022 Given two lists sorted in increasing order, create and return a new list representing the intersection of the two lists. The new list should be made with its own memory — the original lists should not be changed. Example: Input: First linked list: 1->2->3->4->6 Second linked list be 2->4->6->8, Output: 2->4->6. The elements 2, 4, 6 are common in both the list so they appear in the intersection list. Input: First linked list: 1->2->3->4->5 Second linked list be 2->3->4, Output: 2->3->4 The elements 2, 3, 4 are common in both the list so they appear in the intersection list. Method 1: Using Dummy Node. Approach: The idea is to use a temporary dummy node at the start of the result list. The pointer tail always points to the last node in the result list, so new nodes can be added easily. The dummy node initially gives the tail a memory space to point to. This dummy node is efficient, since it is only temporary, and it is allocated in the stack. The loop proceeds, removing one node from either ‘a’ or ‘b’ and adding it to the tail. When the given lists are traversed the result is in dummy. next, as the values are allocated from next node of the dummy. If both the elements are equal then remove both and insert the element to the tail. Else remove the smaller element among both the lists. Below is the implementation of the above approach: C++ C Java Python3 C# Javascript #include<bits/stdc++.h>using namespace std; /* Link list node */struct Node { int data; Node* next;}; void push(Node** head_ref, int new_data); /*This solution uses the temporary dummy to build up the result list */Node* sortedIntersect(Node* a, Node* b){ Node dummy; Node* tail = &dummy; dummy.next = NULL; /* Once one or the other list runs out -- we're done */ while (a != NULL && b != NULL) { if (a->data == b->data) { push((&tail->next), a->data); tail = tail->next; a = a->next; b = b->next; } /* advance the smaller list */ else if (a->data < b->data) a = a->next; else b = b->next; } return (dummy.next);} /* UTILITY FUNCTIONS *//* Function to insert a node atthe beginning of the linked list */void push(Node** head_ref, int new_data){ /* allocate node */ Node* new_node = (Node*)malloc( sizeof(Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print nodes in a given linked list */void printList(Node* node){ while (node != NULL) { cout << node->data <<" "; node = node->next; }} /* Driver program to test above functions*/int main(){ /* Start with the empty lists */ Node* a = NULL; Node* b = NULL; Node* intersect = NULL; /* Let us create the first sorted linked list to test the functions Created linked list will be 1->2->3->4->5->6 */ push(&a, 6); push(&a, 5); push(&a, 4); push(&a, 3); push(&a, 2); push(&a, 1); /* Let us create the second sorted linked list Created linked list will be 2->4->6->8 */ push(&b, 8); push(&b, 6); push(&b, 4); push(&b, 2); /* Find the intersection two linked lists */ intersect = sortedIntersect(a, b); cout<<"Linked list containing common items of a & b \n"; printList(intersect);} #include <stdio.h>#include <stdlib.h> /* Link list node */struct Node { int data; struct Node* next;}; void push(struct Node** head_ref, int new_data); /*This solution uses the temporary dummy to build up the result list */struct Node* sortedIntersect( struct Node* a, struct Node* b){ struct Node dummy; struct Node* tail = &dummy; dummy.next = NULL; /* Once one or the other list runs out -- we're done */ while (a != NULL && b != NULL) { if (a->data == b->data) { push((&tail->next), a->data); tail = tail->next; a = a->next; b = b->next; } /* advance the smaller list */ else if (a->data < b->data) a = a->next; else b = b->next; } return (dummy.next);} /* UTILITY FUNCTIONS *//* Function to insert a node atthe beginning of the linked list */void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*)malloc( sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print nodes in a given linked list */void printList(struct Node* node){ while (node != NULL) { printf("%d ", node->data); node = node->next; }} /* Driver program to test above functions*/int main(){ /* Start with the empty lists */ struct Node* a = NULL; struct Node* b = NULL; struct Node* intersect = NULL; /* Let us create the first sorted linked list to test the functions Created linked list will be 1->2->3->4->5->6 */ push(&a, 6); push(&a, 5); push(&a, 4); push(&a, 3); push(&a, 2); push(&a, 1); /* Let us create the second sorted linked list Created linked list will be 2->4->6->8 */ push(&b, 8); push(&b, 6); push(&b, 4); push(&b, 2); /* Find the intersection two linked lists */ intersect = sortedIntersect(a, b); printf("\n Linked list containing common items of a & b \n "); printList(intersect); getchar();} class GFG{ // head nodes for pointing to 1st and 2nd linked lists static Node a = null, b = null; // dummy node for storing intersection static Node dummy = null; // tail node for keeping track of // last node so that it makes easy for insertion static Node tail = null; // class - Node static class Node { int data; Node next; Node(int data) { this.data = data; next = null; } } // function for printing the list void printList(Node start) { Node p = start; while (p != null) { System.out.print(p.data + " "); p = p.next; } System.out.println(); } // inserting elements into list void push(int data) { Node temp = new Node(data); if(dummy == null) { dummy = temp; tail = temp; } else { tail.next = temp; tail = temp; } } // function for finding intersection and adding it to dummy list void sortedIntersect() { // pointers for iterating Node p = a,q = b; while(p != null && q != null) { if(p.data == q.data) { // add to dummy list push(p.data); p = p.next; q = q.next; } else if(p.data < q.data) p = p.next; else q= q.next; } } // Driver code public static void main(String args[]) { GFG list = new GFG(); // creating first linked list list.a = new Node(1); list.a.next = new Node(2); list.a.next.next = new Node(3); list.a.next.next.next = new Node(4); list.a.next.next.next.next = new Node(6); // creating second linked list list.b = new Node(2); list.b.next = new Node(4); list.b.next.next = new Node(6); list.b.next.next.next = new Node(8); // function call for intersection list.sortedIntersect(); // print required intersection System.out.println("Linked list containing common items of a & b"); list.printList(dummy); }} // This code is contributed by Likhita AVL ''' Link list node '''class Node: def __init__(self): self.data = 0 self.next = None '''This solution uses the temporary dummy to build up the result list '''def sortedIntersect(a, b): dummy = Node() tail = dummy; dummy.next = None; ''' Once one or the other list runs out -- we're done ''' while (a != None and b != None): if (a.data == b.data): tail.next = push((tail.next), a.data); tail = tail.next; a = a.next; b = b.next; # advance the smaller list elif(a.data < b.data): a = a.next; else: b = b.next; return (dummy.next); ''' UTILITY FUNCTIONS '''''' Function to insert a node atthe beginning of the linked list '''def push(head_ref, new_data): ''' allocate node ''' new_node = Node() ''' put in the data ''' new_node.data = new_data; ''' link the old list off the new node ''' new_node.next = (head_ref); ''' move the head to point to the new node ''' (head_ref) = new_node; return head_ref ''' Function to print nodes in a given linked list '''def printList(node): while (node != None): print(node.data, end=' ') node = node.next; ''' Driver code'''if __name__=='__main__': ''' Start with the empty lists ''' a = None; b = None; intersect = None; ''' Let us create the first sorted linked list to test the functions Created linked list will be 1.2.3.4.5.6 ''' a = push(a, 6); a = push(a, 5); a = push(a, 4); a = push(a, 3); a = push(a, 2); a = push(a, 1); ''' Let us create the second sorted linked list Created linked list will be 2.4.6.8 ''' b = push(b, 8); b = push(b, 6); b = push(b, 4); b = push(b, 2); ''' Find the intersection two linked lists ''' intersect = sortedIntersect(a, b); print("Linked list containing common items of a & b "); printList(intersect); # This code is contributed by rutvik_56. using System; public class GFG{ // dummy node for storing intersection static Node dummy = null; // tail node for keeping track of // last node so that it makes easy for insertion static Node tail = null; // class - Node public class Node { public int data; public Node next; public Node(int data) { this.data = data; next = null; } } // head nodes for pointing to 1st and 2nd linked lists Node a = null, b = null; // function for printing the list void printList(Node start) { Node p = start; while (p != null) { Console.Write(p.data + " "); p = p.next; } Console.WriteLine(); } // inserting elements into list void push(int data) { Node temp = new Node(data); if(dummy == null) { dummy = temp; tail = temp; } else { tail.next = temp; tail = temp; } } // function for finding intersection and adding it to dummy list void sortedIntersect() { // pointers for iterating Node p = a,q = b; while(p != null && q != null) { if(p.data == q.data) { // add to dummy list push(p.data); p = p.next; q = q.next; } else if(p.data < q.data) p = p.next; else q= q.next; } } // Driver code public static void Main(String []args) { GFG list = new GFG(); // creating first linked list list.a = new Node(1); list.a.next = new Node(2); list.a.next.next = new Node(3); list.a.next.next.next = new Node(4); list.a.next.next.next.next = new Node(6); // creating second linked list list.b = new Node(2); list.b.next = new Node(4); list.b.next.next = new Node(6); list.b.next.next.next = new Node(8); // function call for intersection list.sortedIntersect(); // print required intersection Console.WriteLine("Linked list containing common items of a & b"); list.printList(dummy); }} // This code is contributed by aashish1995 <script> // head nodes for pointing to // 1st and 2nd linked lists var a = null, b = null; // dummy node for storing intersection var dummy = null; // tail node for keeping track of // last node so that it makes easy for insertion var tail = null; // class - Node class Node { constructor(val) { this.data = val; this.next = null; } } // function for printing the list function printList(start) {var p = start; while (p != null) { document.write(p.data + " "); p = p.next; } document.write(); } // inserting elements into list function push(data) {var temp = new Node(data); if (dummy == null) { dummy = temp; tail = temp; } else { tail.next = temp; tail = temp; } } // function for finding intersection and // adding it to dummy list function sortedIntersect() { // pointers for iteratingvar p = a, q = b; while (p != null && q != null) { if (p.data == q.data) { // add to dummy list push(p.data); p = p.next; q = q.next; } else if (p.data < q.data) p = p.next; else q = q.next; } } // Driver code // creating first linked list a = new Node(1); a.next = new Node(2); a.next.next = new Node(3); a.next.next.next = new Node(4); a.next.next.next.next = new Node(6); // creating second linked list b = new Node(2); b.next = new Node(4); b.next.next = new Node(6); b.next.next.next = new Node(8); // function call for intersection sortedIntersect(); // print required intersection document.write( "Linked list containing common items of a & b<br/>" ); printList(dummy); // This code is contributed by todaysgaurav </script> Linked list containing common items of a & b 2 4 6 Output: Linked list containing common items of a & b 2 4 6 Complexity Analysis: Time Complexity: O(m+n) where m and n are number of nodes in first and second linked lists respectively. Only one traversal of the lists are needed. Auxiliary Space: O(min(m, n)). The output list can store at most min(m,n) nodes . Method 2: Using Local References. Approach: This solution is structurally very similar to the above, but it avoids using a dummy node Instead, it maintains a struct node** pointer, lastPtrRef, that always points to the last pointer of the result list. This solves the same case that the dummy node did — dealing with the result list when it is empty. If the list is built at its tail, either the dummy node or the struct node** “reference” strategy can be used. Below is the implementation of the above approach: C #include <stdio.h>#include <stdlib.h> /* Link list node */struct Node { int data; struct Node* next;}; void push(struct Node** head_ref, int new_data); /* This solution uses the local reference */struct Node* sortedIntersect( struct Node* a, struct Node* b){ struct Node* result = NULL; struct Node** lastPtrRef = &result; /* Advance comparing the first nodes in both lists. When one or the other list runs out, we're done. */ while (a != NULL && b != NULL) { if (a->data == b->data) { /* found a node for the intersection */ push(lastPtrRef, a->data); lastPtrRef = &((*lastPtrRef)->next); a = a->next; b = b->next; } else if (a->data < b->data) a = a->next; /* advance the smaller list */ else b = b->next; } return (result);} /* UTILITY FUNCTIONS *//* Function to insert a node at the beginning of the linked list */void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*)malloc( sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print nodes in a given linked list */void printList(struct Node* node){ while (node != NULL) { printf("%d ", node->data); node = node->next; }} /* Driver program to test above functions*/int main(){ /* Start with the empty lists */ struct Node* a = NULL; struct Node* b = NULL; struct Node* intersect = NULL; /* Let us create the first sorted linked list to test the functions Created linked list will be 1->2->3->4->5->6 */ push(&a, 6); push(&a, 5); push(&a, 4); push(&a, 3); push(&a, 2); push(&a, 1); /* Let us create the second sorted linked list Created linked list will be 2->4->6->8 */ push(&b, 8); push(&b, 6); push(&b, 4); push(&b, 2); /* Find the intersection two linked lists */ intersect = sortedIntersect(a, b); printf("\n Linked list containing common items of a & b \n "); printList(intersect); getchar();} Linked list containing common items of a & b 2 4 6 Output: Linked list containing common items of a & b 2 4 6 Complexity Analysis: Time Complexity: O(m+n) where m and n are number of nodes in first and second linked lists respectively. Only one traversal of the lists are needed. Auxiliary Space: O(max(m, n)). The output list can store at most m+n nodes. Method 3: Recursive Solution. Approach: The recursive approach is very similar to the above two approaches. Build a recursive function that takes two nodes and returns a linked list node. Compare the first element of both the lists. If they are similar then call the recursive function with the next node of both the lists. Create a node with the data of the current node and put the returned node from the recursive function to the next pointer of the node created. Return the node created. If the values are not equal then remove the smaller node of both the lists and call the recursive function. Below is the implementation of the above approach: C++ C Java Python3 C# Javascript #include <bits/stdc++.h>using namespace std; // Link list nodestruct Node{ int data; struct Node* next;}; struct Node* sortedIntersect(struct Node* a, struct Node* b){ // base case if (a == NULL || b == NULL) return NULL; /* If both lists are non-empty */ /* Advance the smaller list and call recursively */ if (a->data < b->data) return sortedIntersect(a->next, b); if (a->data > b->data) return sortedIntersect(a, b->next); // Below lines are executed only // when a->data == b->data struct Node* temp = (struct Node*)malloc( sizeof(struct Node)); temp->data = a->data; // Advance both lists and call recursively temp->next = sortedIntersect(a->next, b->next); return temp;} /* UTILITY FUNCTIONS *//* Function to insert a node atthe beginning of the linked list */void push(struct Node** head_ref, int new_data){ /* Allocate node */ struct Node* new_node = (struct Node*)malloc( sizeof(struct Node)); /* Put in the data */ new_node->data = new_data; /* Link the old list off the new node */ new_node->next = (*head_ref); /* Move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print nodes in a given linked list */void printList(struct Node* node){ while (node != NULL) { cout << " " << node->data; node = node->next; }} // Driver codeint main(){ /* Start with the empty lists */ struct Node* a = NULL; struct Node* b = NULL; struct Node* intersect = NULL; /* Let us create the first sorted linked list to test the functions Created linked list will be 1->2->3->4->5->6 */ push(&a, 6); push(&a, 5); push(&a, 4); push(&a, 3); push(&a, 2); push(&a, 1); /* Let us create the second sorted linked list Created linked list will be 2->4->6->8 */ push(&b, 8); push(&b, 6); push(&b, 4); push(&b, 2); /* Find the intersection two linked lists */ intersect = sortedIntersect(a, b); cout << "\n Linked list containing " << "common items of a & b \n "; printList(intersect); return 0;} // This code is contributed by shivanisinghss2110 #include <stdio.h>#include <stdlib.h> /* Link list node */struct Node { int data; struct Node* next;}; struct Node* sortedIntersect( struct Node* a, struct Node* b){ /* base case */ if (a == NULL || b == NULL) return NULL; /* If both lists are non-empty */ /* advance the smaller list and call recursively */ if (a->data < b->data) return sortedIntersect(a->next, b); if (a->data > b->data) return sortedIntersect(a, b->next); // Below lines are executed only // when a->data == b->data struct Node* temp = (struct Node*)malloc( sizeof(struct Node)); temp->data = a->data; /* advance both lists and call recursively */ temp->next = sortedIntersect(a->next, b->next); return temp;} /* UTILITY FUNCTIONS *//* Function to insert a node atthe beginning of the linked list */void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*)malloc( sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print nodes in a given linked list */void printList(struct Node* node){ while (node != NULL) { printf("%d ", node->data); node = node->next; }} /* Driver program to test above functions*/int main(){ /* Start with the empty lists */ struct Node* a = NULL; struct Node* b = NULL; struct Node* intersect = NULL; /* Let us create the first sorted linked list to test the functions Created linked list will be 1->2->3->4->5->6 */ push(&a, 6); push(&a, 5); push(&a, 4); push(&a, 3); push(&a, 2); push(&a, 1); /* Let us create the second sorted linked list Created linked list will be 2->4->6->8 */ push(&b, 8); push(&b, 6); push(&b, 4); push(&b, 2); /* Find the intersection two linked lists */ intersect = sortedIntersect(a, b); printf("\n Linked list containing common items of a & b \n "); printList(intersect); return 0;} import java.util.*; class GFG{ // Link list nodestatic class Node{ int data; Node next;}; static Node sortedIntersect(Node a, Node b){ // base case if (a == null || b == null) return null; /* If both lists are non-empty */ /* Advance the smaller list and call recursively */ if (a.data < b.data) return sortedIntersect(a.next, b); if (a.data > b.data) return sortedIntersect(a, b.next); // Below lines are executed only // when a.data == b.data Node temp = new Node(); temp.data = a.data; // Advance both lists and call recursively temp.next = sortedIntersect(a.next, b.next); return temp;} /* UTILITY FUNCTIONS *//* Function to insert a node atthe beginning of the linked list */static Node push(Node head_ref, int new_data){ /* Allocate node */ Node new_node = new Node(); /* Put in the data */ new_node.data = new_data; /* Link the old list off the new node */ new_node.next = head_ref; /* Move the head to point to the new node */ head_ref = new_node; return head_ref;} /* Function to print nodes in a given linked list */static void printList(Node node){ while (node != null) { System.out.print(" " + node.data); node = node.next; }} // Driver codepublic static void main(String[] args){ /* Start with the empty lists */ Node a = null; Node b = null; Node intersect = null; /* Let us create the first sorted linked list to test the functions Created linked list will be 1.2.3.4.5.6 */ a = push(a, 6); a = push(a, 5); a = push(a, 4); a = push(a, 3); a = push(a, 2); a = push(a, 1); /* Let us create the second sorted linked list Created linked list will be 2.4.6.8 */ b = push(b, 8); b = push(b, 6); b = push(b, 4); b = push(b, 2); /* Find the intersection two linked lists */ intersect = sortedIntersect(a, b); System.out.print("\n Linked list containing " + "common items of a & b \n "); printList(intersect); }} // This code is contributed by umadevi9616 # Link list nodeclass Node: def __init__(self): self.data = 0 self.next = None def sortedIntersect(a, b): # base case if (a == None or b == None): return None # If both lists are non-empty # Advance the smaller list and call recursively if (a.data < b.data): return sortedIntersect(a.next, b); if (a.data > b.data): return sortedIntersect(a, b.next); # Below lines are executed only # when a.data == b.data temp = Node(); temp.data = a.data; # Advance both lists and call recursively temp.next = sortedIntersect(a.next, b.next); return temp; # UTILITY FUNCTIONS # Function to insert a node at the beginning of the linked list def push(head_ref, new_data): # Allocate node new_node = Node() # Put in the data new_node.data = new_data; # Link the old list off the new node new_node.next = head_ref; # Move the head to point to the new node head_ref = new_node; return head_ref; # Function to print nodes in a given linked list def printList(node): while (node != None): print(node.data, end=" ") node = node.next; # Driver code # Start with the empty listsa = Noneb = Noneintersect = None # Let us create the first sorted linked list to test the functions Created# linked list will be 1.2.3.4.5.6 a = push(a, 6)a = push(a, 5)a = push(a, 4)a = push(a, 3)a = push(a, 2)a = push(a, 1) # Let us create the second sorted linked list Created linked list will be# 2.4.6.8 b = push(b, 8)b = push(b, 6)b = push(b, 4)b = push(b, 2) # Find the intersection two linked listsintersect = sortedIntersect(a, b) print("\n Linked list containing " + "common items of a & b");printList(intersect) # This code is contributed by Saurabh Jaiswal using System; public class GFG { // Link list node public class Node { public int data; public Node next; }; static Node sortedIntersect(Node a, Node b) { // base case if (a == null || b == null) return null; /* If both lists are non-empty */ /* * Advance the smaller list and call recursively */ if (a.data < b.data) return sortedIntersect(a.next, b); if (a.data > b.data) return sortedIntersect(a, b.next); // Below lines are executed only // when a.data == b.data Node temp = new Node(); temp.data = a.data; // Advance both lists and call recursively temp.next = sortedIntersect(a.next, b.next); return temp; } /* UTILITY FUNCTIONS */ /* * Function to insert a node at the beginning of the linked list */ static Node push(Node head_ref, int new_data) { /* Allocate node */ Node new_node = new Node(); /* Put in the data */ new_node.data = new_data; /* Link the old list off the new node */ new_node.next = head_ref; /* Move the head to point to the new node */ head_ref = new_node; return head_ref; } /* * Function to print nodes in a given linked list */ static void printList(Node node) { while (node != null) { Console.Write(" " + node.data); node = node.next; } } // Driver code public static void Main(String[] args) { /* Start with the empty lists */ Node a = null; Node b = null; Node intersect = null; /* * Let us create the first sorted linked list to test the functions Created * linked list will be 1.2.3.4.5.6 */ a = push(a, 6); a = push(a, 5); a = push(a, 4); a = push(a, 3); a = push(a, 2); a = push(a, 1); /* * Let us create the second sorted linked list Created linked list will be * 2.4.6.8 */ b = push(b, 8); b = push(b, 6); b = push(b, 4); b = push(b, 2); /* Find the intersection two linked lists */ intersect = sortedIntersect(a, b); Console.Write("\n Linked list containing " + "common items of a & b \n "); printList(intersect); }} // This code is contributed by umadevi9616 <script> // Link list node class Node { constructor(){ this.data = 0; this.next = null;} } function sortedIntersect(a, b) { // base case if (a == null || b == null) return null; /* If both lists are non-empty */ /* * Advance the smaller list and call recursively */ if (a.data < b.data) return sortedIntersect(a.next, b); if (a.data > b.data) return sortedIntersect(a, b.next); // Below lines are executed only // when a.data == b.datavar temp = new Node(); temp.data = a.data; // Advance both lists and call recursively temp.next = sortedIntersect(a.next, b.next); return temp; } /* UTILITY FUNCTIONS */ /* * Function to insert a node at the beginning of the linked list */ function push(head_ref , new_data) { /* Allocate node */var new_node = new Node(); /* Put in the data */ new_node.data = new_data; /* Link the old list off the new node */ new_node.next = head_ref; /* Move the head to point to the new node */ head_ref = new_node; return head_ref; } /* * Function to print nodes in a given linked list */ function printList(node) { while (node != null) { document.write(" " + node.data); node = node.next; } } // Driver code /* Start with the empty lists */var a = null;var b = null;var intersect = null; /* * Let us create the first sorted linked list to test the functions Created * linked list will be 1.2.3.4.5.6 */ a = push(a, 6); a = push(a, 5); a = push(a, 4); a = push(a, 3); a = push(a, 2); a = push(a, 1); /* * Let us create the second sorted linked list Created linked list will be * 2.4.6.8 */ b = push(b, 8); b = push(b, 6); b = push(b, 4); b = push(b, 2); /* Find the intersection two linked lists */ intersect = sortedIntersect(a, b); document.write("\n Linked list containing " + "common items of a & b <br/> "); printList(intersect); // This code is contributed by Rajput-Ji</script> Linked list containing common items of a & b 2 4 6 Complexity Analysis: Time Complexity: O(m+n) where m and n are number of nodes in first and second linked lists respectively. Only one traversal of the lists are needed. Auxiliary Space: O(max(m, n)). The output list can store at most m+n nodes. Method 4: Use Hashing Java C# import java.util.*; // This code is contributed by ayyuce demirbaspublic class LinkedList { Node head; static class Node { int data; Node next; Node(int d) { data = d; next=null; } } public void printList() { Node n= head; while(n!=null) { System.out.println(n.data+ " "); n=n.next; } } public void append(int d) { Node n= new Node(d); if(head== null) { head= new Node(d); return; } n.next=null; Node last= head; while(last.next !=null) { last=last.next; } last.next=n; return; } static int[] intersection(Node tmp1, Node tmp2, int k) { int[] res = new int[k]; HashSet<Integer> set = new HashSet<Integer>(); while(tmp1 != null) { set.add(tmp1.data); tmp1=tmp1.next; } int cnt=0; while(tmp2 != null) { if(set.contains(tmp2.data)) { res[cnt]=tmp2.data; cnt++; } tmp2=tmp2.next; } return res; } public static void main(String[] args) { LinkedList ll = new LinkedList(); LinkedList ll1 = new LinkedList(); ll.append(0); ll.append(1); ll.append(2); ll.append(3); ll.append(4); ll.append(5); ll.append(6); ll.append(7); ll1.append(9); ll1.append(0); ll1.append(12); ll1.append(3); ll1.append(4); ll1.append(5); ll1.append(6); ll1.append(7); int[] arr= intersection(ll.head, ll1.head,6); for(int i : arr) { System.out.println(i); } } } using System;using System.Collections.Generic; // This code is contributed by ayyuce demirbaspublic class List { Node head; public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } public void printList() { Node n = head; while (n != null) { Console.WriteLine(n.data + " "); n = n.next; } } public void append(int d) { Node n = new Node(d); if (head == null) { head = new Node(d); return; } n.next = null; Node last = head; while (last.next != null) { last = last.next; } last.next = n; return; } static int[] intersection(Node tmp1, Node tmp2, int k) { int[] res = new int[k]; HashSet<int> set = new HashSet<int>(); while (tmp1 != null) { set.Add(tmp1.data); tmp1 = tmp1.next; } int cnt = 0; while (tmp2 != null) { if (set.Contains(tmp2.data)) { res[cnt] = tmp2.data; cnt++; } tmp2 = tmp2.next; } return res; } public static void Main(String[] args) { List ll = new List(); List ll1 = new List(); ll.append(0); ll.append(1); ll.append(2); ll.append(3); ll.append(4); ll.append(5); ll.append(6); ll.append(7); ll1.append(9); ll1.append(0); ll1.append(12); ll1.append(3); ll1.append(4); ll1.append(5); ll1.append(6); ll1.append(7); int[] arr = intersection(ll.head, ll1.head, 6); foreach(int i in arr) { Console.WriteLine(i); } }} // This code is contributed by umadevi9616 0 3 4 5 6 7 Complexity Analysis: Time Complexity: O(n) Please write comments if you find the above codes/algorithms incorrect, or find better ways to solve the same problem.References: cslibrary.stanford.edu/105/LinkedListProblems.pdf andrew1234 Akanksha_Rai mukul garg 1 rutvik_56 pratham76 avllikhita todaysgaurav aashish1995 khushboogoyal499 shivanisinghss2110 simranarora5sos ayyuce umadevi9616 Rajput-Ji sweetyty sagartomar9927 _saurabh_jaiswal simmytarika5 Amazon D-E-Shaw Microsoft Zopper Linked List Sorting Amazon Microsoft D-E-Shaw Zopper Linked List Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stack Data Structure (Introduction and Program) LinkedList in Java Introduction to Data Structures What is Data Structure: Types, Classifications and Applications Implementing a Linked List in Java using Class Merge Sort Bubble Sort Algorithm QuickSort Insertion Sort Selection Sort Algorithm
[ { "code": null, "e": 54, "s": 26, "text": "\n01 Jul, 2022" }, { "code": null, "e": 268, "s": 54, "text": "Given two lists sorted in increasing order, create and return a new list representing the intersection of the two lists. The new list should be made with its own memory — the original lists should not be changed. " }, { "code": null, "e": 278, "s": 268, "text": "Example: " }, { "code": null, "e": 646, "s": 278, "text": "Input: \nFirst linked list: 1->2->3->4->6\nSecond linked list be 2->4->6->8, \nOutput: 2->4->6.\nThe elements 2, 4, 6 are common in \nboth the list so they appear in the \nintersection list. \n\nInput: \nFirst linked list: 1->2->3->4->5\nSecond linked list be 2->3->4, \nOutput: 2->3->4\nThe elements 2, 3, 4 are common in \nboth the list so they appear in the \nintersection list." }, { "code": null, "e": 1369, "s": 646, "text": "Method 1: Using Dummy Node. Approach: The idea is to use a temporary dummy node at the start of the result list. The pointer tail always points to the last node in the result list, so new nodes can be added easily. The dummy node initially gives the tail a memory space to point to. This dummy node is efficient, since it is only temporary, and it is allocated in the stack. The loop proceeds, removing one node from either ‘a’ or ‘b’ and adding it to the tail. When the given lists are traversed the result is in dummy. next, as the values are allocated from next node of the dummy. If both the elements are equal then remove both and insert the element to the tail. Else remove the smaller element among both the lists. " }, { "code": null, "e": 1420, "s": 1369, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1424, "s": 1420, "text": "C++" }, { "code": null, "e": 1426, "s": 1424, "text": "C" }, { "code": null, "e": 1431, "s": 1426, "text": "Java" }, { "code": null, "e": 1439, "s": 1431, "text": "Python3" }, { "code": null, "e": 1442, "s": 1439, "text": "C#" }, { "code": null, "e": 1453, "s": 1442, "text": "Javascript" }, { "code": "#include<bits/stdc++.h>using namespace std; /* Link list node */struct Node { int data; Node* next;}; void push(Node** head_ref, int new_data); /*This solution uses the temporary dummy to build up the result list */Node* sortedIntersect(Node* a, Node* b){ Node dummy; Node* tail = &dummy; dummy.next = NULL; /* Once one or the other list runs out -- we're done */ while (a != NULL && b != NULL) { if (a->data == b->data) { push((&tail->next), a->data); tail = tail->next; a = a->next; b = b->next; } /* advance the smaller list */ else if (a->data < b->data) a = a->next; else b = b->next; } return (dummy.next);} /* UTILITY FUNCTIONS *//* Function to insert a node atthe beginning of the linked list */void push(Node** head_ref, int new_data){ /* allocate node */ Node* new_node = (Node*)malloc( sizeof(Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print nodes in a given linked list */void printList(Node* node){ while (node != NULL) { cout << node->data <<\" \"; node = node->next; }} /* Driver program to test above functions*/int main(){ /* Start with the empty lists */ Node* a = NULL; Node* b = NULL; Node* intersect = NULL; /* Let us create the first sorted linked list to test the functions Created linked list will be 1->2->3->4->5->6 */ push(&a, 6); push(&a, 5); push(&a, 4); push(&a, 3); push(&a, 2); push(&a, 1); /* Let us create the second sorted linked list Created linked list will be 2->4->6->8 */ push(&b, 8); push(&b, 6); push(&b, 4); push(&b, 2); /* Find the intersection two linked lists */ intersect = sortedIntersect(a, b); cout<<\"Linked list containing common items of a & b \\n\"; printList(intersect);}", "e": 3512, "s": 1453, "text": null }, { "code": "#include <stdio.h>#include <stdlib.h> /* Link list node */struct Node { int data; struct Node* next;}; void push(struct Node** head_ref, int new_data); /*This solution uses the temporary dummy to build up the result list */struct Node* sortedIntersect( struct Node* a, struct Node* b){ struct Node dummy; struct Node* tail = &dummy; dummy.next = NULL; /* Once one or the other list runs out -- we're done */ while (a != NULL && b != NULL) { if (a->data == b->data) { push((&tail->next), a->data); tail = tail->next; a = a->next; b = b->next; } /* advance the smaller list */ else if (a->data < b->data) a = a->next; else b = b->next; } return (dummy.next);} /* UTILITY FUNCTIONS *//* Function to insert a node atthe beginning of the linked list */void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*)malloc( sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print nodes in a given linked list */void printList(struct Node* node){ while (node != NULL) { printf(\"%d \", node->data); node = node->next; }} /* Driver program to test above functions*/int main(){ /* Start with the empty lists */ struct Node* a = NULL; struct Node* b = NULL; struct Node* intersect = NULL; /* Let us create the first sorted linked list to test the functions Created linked list will be 1->2->3->4->5->6 */ push(&a, 6); push(&a, 5); push(&a, 4); push(&a, 3); push(&a, 2); push(&a, 1); /* Let us create the second sorted linked list Created linked list will be 2->4->6->8 */ push(&b, 8); push(&b, 6); push(&b, 4); push(&b, 2); /* Find the intersection two linked lists */ intersect = sortedIntersect(a, b); printf(\"\\n Linked list containing common items of a & b \\n \"); printList(intersect); getchar();}", "e": 5699, "s": 3512, "text": null }, { "code": "class GFG{ // head nodes for pointing to 1st and 2nd linked lists static Node a = null, b = null; // dummy node for storing intersection static Node dummy = null; // tail node for keeping track of // last node so that it makes easy for insertion static Node tail = null; // class - Node static class Node { int data; Node next; Node(int data) { this.data = data; next = null; } } // function for printing the list void printList(Node start) { Node p = start; while (p != null) { System.out.print(p.data + \" \"); p = p.next; } System.out.println(); } // inserting elements into list void push(int data) { Node temp = new Node(data); if(dummy == null) { dummy = temp; tail = temp; } else { tail.next = temp; tail = temp; } } // function for finding intersection and adding it to dummy list void sortedIntersect() { // pointers for iterating Node p = a,q = b; while(p != null && q != null) { if(p.data == q.data) { // add to dummy list push(p.data); p = p.next; q = q.next; } else if(p.data < q.data) p = p.next; else q= q.next; } } // Driver code public static void main(String args[]) { GFG list = new GFG(); // creating first linked list list.a = new Node(1); list.a.next = new Node(2); list.a.next.next = new Node(3); list.a.next.next.next = new Node(4); list.a.next.next.next.next = new Node(6); // creating second linked list list.b = new Node(2); list.b.next = new Node(4); list.b.next.next = new Node(6); list.b.next.next.next = new Node(8); // function call for intersection list.sortedIntersect(); // print required intersection System.out.println(\"Linked list containing common items of a & b\"); list.printList(dummy); }} // This code is contributed by Likhita AVL", "e": 7987, "s": 5699, "text": null }, { "code": "''' Link list node '''class Node: def __init__(self): self.data = 0 self.next = None '''This solution uses the temporary dummy to build up the result list '''def sortedIntersect(a, b): dummy = Node() tail = dummy; dummy.next = None; ''' Once one or the other list runs out -- we're done ''' while (a != None and b != None): if (a.data == b.data): tail.next = push((tail.next), a.data); tail = tail.next; a = a.next; b = b.next; # advance the smaller list elif(a.data < b.data): a = a.next; else: b = b.next; return (dummy.next); ''' UTILITY FUNCTIONS '''''' Function to insert a node atthe beginning of the linked list '''def push(head_ref, new_data): ''' allocate node ''' new_node = Node() ''' put in the data ''' new_node.data = new_data; ''' link the old list off the new node ''' new_node.next = (head_ref); ''' move the head to point to the new node ''' (head_ref) = new_node; return head_ref ''' Function to print nodes in a given linked list '''def printList(node): while (node != None): print(node.data, end=' ') node = node.next; ''' Driver code'''if __name__=='__main__': ''' Start with the empty lists ''' a = None; b = None; intersect = None; ''' Let us create the first sorted linked list to test the functions Created linked list will be 1.2.3.4.5.6 ''' a = push(a, 6); a = push(a, 5); a = push(a, 4); a = push(a, 3); a = push(a, 2); a = push(a, 1); ''' Let us create the second sorted linked list Created linked list will be 2.4.6.8 ''' b = push(b, 8); b = push(b, 6); b = push(b, 4); b = push(b, 2); ''' Find the intersection two linked lists ''' intersect = sortedIntersect(a, b); print(\"Linked list containing common items of a & b \"); printList(intersect); # This code is contributed by rutvik_56.", "e": 10006, "s": 7987, "text": null }, { "code": "using System; public class GFG{ // dummy node for storing intersection static Node dummy = null; // tail node for keeping track of // last node so that it makes easy for insertion static Node tail = null; // class - Node public class Node { public int data; public Node next; public Node(int data) { this.data = data; next = null; } } // head nodes for pointing to 1st and 2nd linked lists Node a = null, b = null; // function for printing the list void printList(Node start) { Node p = start; while (p != null) { Console.Write(p.data + \" \"); p = p.next; } Console.WriteLine(); } // inserting elements into list void push(int data) { Node temp = new Node(data); if(dummy == null) { dummy = temp; tail = temp; } else { tail.next = temp; tail = temp; } } // function for finding intersection and adding it to dummy list void sortedIntersect() { // pointers for iterating Node p = a,q = b; while(p != null && q != null) { if(p.data == q.data) { // add to dummy list push(p.data); p = p.next; q = q.next; } else if(p.data < q.data) p = p.next; else q= q.next; } } // Driver code public static void Main(String []args) { GFG list = new GFG(); // creating first linked list list.a = new Node(1); list.a.next = new Node(2); list.a.next.next = new Node(3); list.a.next.next.next = new Node(4); list.a.next.next.next.next = new Node(6); // creating second linked list list.b = new Node(2); list.b.next = new Node(4); list.b.next.next = new Node(6); list.b.next.next.next = new Node(8); // function call for intersection list.sortedIntersect(); // print required intersection Console.WriteLine(\"Linked list containing common items of a & b\"); list.printList(dummy); }} // This code is contributed by aashish1995", "e": 12357, "s": 10006, "text": null }, { "code": "<script> // head nodes for pointing to // 1st and 2nd linked lists var a = null, b = null; // dummy node for storing intersection var dummy = null; // tail node for keeping track of // last node so that it makes easy for insertion var tail = null; // class - Node class Node { constructor(val) { this.data = val; this.next = null; } } // function for printing the list function printList(start) {var p = start; while (p != null) { document.write(p.data + \" \"); p = p.next; } document.write(); } // inserting elements into list function push(data) {var temp = new Node(data); if (dummy == null) { dummy = temp; tail = temp; } else { tail.next = temp; tail = temp; } } // function for finding intersection and // adding it to dummy list function sortedIntersect() { // pointers for iteratingvar p = a, q = b; while (p != null && q != null) { if (p.data == q.data) { // add to dummy list push(p.data); p = p.next; q = q.next; } else if (p.data < q.data) p = p.next; else q = q.next; } } // Driver code // creating first linked list a = new Node(1); a.next = new Node(2); a.next.next = new Node(3); a.next.next.next = new Node(4); a.next.next.next.next = new Node(6); // creating second linked list b = new Node(2); b.next = new Node(4); b.next.next = new Node(6); b.next.next.next = new Node(8); // function call for intersection sortedIntersect(); // print required intersection document.write( \"Linked list containing common items of a & b<br/>\" ); printList(dummy); // This code is contributed by todaysgaurav </script>", "e": 14402, "s": 12357, "text": null }, { "code": null, "e": 14455, "s": 14402, "text": "Linked list containing common items of a & b \n2 4 6 " }, { "code": null, "e": 14464, "s": 14455, "text": "Output: " }, { "code": null, "e": 14517, "s": 14464, "text": "Linked list containing common items of a & b \n 2 4 6" }, { "code": null, "e": 14539, "s": 14517, "text": "Complexity Analysis: " }, { "code": null, "e": 14688, "s": 14539, "text": "Time Complexity: O(m+n) where m and n are number of nodes in first and second linked lists respectively. Only one traversal of the lists are needed." }, { "code": null, "e": 14770, "s": 14688, "text": "Auxiliary Space: O(min(m, n)). The output list can store at most min(m,n) nodes ." }, { "code": null, "e": 15233, "s": 14770, "text": "Method 2: Using Local References. Approach: This solution is structurally very similar to the above, but it avoids using a dummy node Instead, it maintains a struct node** pointer, lastPtrRef, that always points to the last pointer of the result list. This solves the same case that the dummy node did — dealing with the result list when it is empty. If the list is built at its tail, either the dummy node or the struct node** “reference” strategy can be used. " }, { "code": null, "e": 15284, "s": 15233, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 15286, "s": 15284, "text": "C" }, { "code": "#include <stdio.h>#include <stdlib.h> /* Link list node */struct Node { int data; struct Node* next;}; void push(struct Node** head_ref, int new_data); /* This solution uses the local reference */struct Node* sortedIntersect( struct Node* a, struct Node* b){ struct Node* result = NULL; struct Node** lastPtrRef = &result; /* Advance comparing the first nodes in both lists. When one or the other list runs out, we're done. */ while (a != NULL && b != NULL) { if (a->data == b->data) { /* found a node for the intersection */ push(lastPtrRef, a->data); lastPtrRef = &((*lastPtrRef)->next); a = a->next; b = b->next; } else if (a->data < b->data) a = a->next; /* advance the smaller list */ else b = b->next; } return (result);} /* UTILITY FUNCTIONS *//* Function to insert a node at the beginning of the linked list */void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*)malloc( sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print nodes in a given linked list */void printList(struct Node* node){ while (node != NULL) { printf(\"%d \", node->data); node = node->next; }} /* Driver program to test above functions*/int main(){ /* Start with the empty lists */ struct Node* a = NULL; struct Node* b = NULL; struct Node* intersect = NULL; /* Let us create the first sorted linked list to test the functions Created linked list will be 1->2->3->4->5->6 */ push(&a, 6); push(&a, 5); push(&a, 4); push(&a, 3); push(&a, 2); push(&a, 1); /* Let us create the second sorted linked list Created linked list will be 2->4->6->8 */ push(&b, 8); push(&b, 6); push(&b, 4); push(&b, 2); /* Find the intersection two linked lists */ intersect = sortedIntersect(a, b); printf(\"\\n Linked list containing common items of a & b \\n \"); printList(intersect); getchar();}", "e": 17567, "s": 15286, "text": null }, { "code": null, "e": 17622, "s": 17567, "text": " Linked list containing common items of a & b \n 2 4 6 " }, { "code": null, "e": 17631, "s": 17622, "text": "Output: " }, { "code": null, "e": 17684, "s": 17631, "text": "Linked list containing common items of a & b \n 2 4 6" }, { "code": null, "e": 17706, "s": 17684, "text": "Complexity Analysis: " }, { "code": null, "e": 17855, "s": 17706, "text": "Time Complexity: O(m+n) where m and n are number of nodes in first and second linked lists respectively. Only one traversal of the lists are needed." }, { "code": null, "e": 17931, "s": 17855, "text": "Auxiliary Space: O(max(m, n)). The output list can store at most m+n nodes." }, { "code": null, "e": 18165, "s": 17931, "text": "Method 3: Recursive Solution. Approach: The recursive approach is very similar to the above two approaches. Build a recursive function that takes two nodes and returns a linked list node. Compare the first element of both the lists. " }, { "code": null, "e": 18424, "s": 18165, "text": "If they are similar then call the recursive function with the next node of both the lists. Create a node with the data of the current node and put the returned node from the recursive function to the next pointer of the node created. Return the node created." }, { "code": null, "e": 18532, "s": 18424, "text": "If the values are not equal then remove the smaller node of both the lists and call the recursive function." }, { "code": null, "e": 18583, "s": 18532, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 18587, "s": 18583, "text": "C++" }, { "code": null, "e": 18589, "s": 18587, "text": "C" }, { "code": null, "e": 18594, "s": 18589, "text": "Java" }, { "code": null, "e": 18602, "s": 18594, "text": "Python3" }, { "code": null, "e": 18605, "s": 18602, "text": "C#" }, { "code": null, "e": 18616, "s": 18605, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; // Link list nodestruct Node{ int data; struct Node* next;}; struct Node* sortedIntersect(struct Node* a, struct Node* b){ // base case if (a == NULL || b == NULL) return NULL; /* If both lists are non-empty */ /* Advance the smaller list and call recursively */ if (a->data < b->data) return sortedIntersect(a->next, b); if (a->data > b->data) return sortedIntersect(a, b->next); // Below lines are executed only // when a->data == b->data struct Node* temp = (struct Node*)malloc( sizeof(struct Node)); temp->data = a->data; // Advance both lists and call recursively temp->next = sortedIntersect(a->next, b->next); return temp;} /* UTILITY FUNCTIONS *//* Function to insert a node atthe beginning of the linked list */void push(struct Node** head_ref, int new_data){ /* Allocate node */ struct Node* new_node = (struct Node*)malloc( sizeof(struct Node)); /* Put in the data */ new_node->data = new_data; /* Link the old list off the new node */ new_node->next = (*head_ref); /* Move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print nodes in a given linked list */void printList(struct Node* node){ while (node != NULL) { cout << \" \" << node->data; node = node->next; }} // Driver codeint main(){ /* Start with the empty lists */ struct Node* a = NULL; struct Node* b = NULL; struct Node* intersect = NULL; /* Let us create the first sorted linked list to test the functions Created linked list will be 1->2->3->4->5->6 */ push(&a, 6); push(&a, 5); push(&a, 4); push(&a, 3); push(&a, 2); push(&a, 1); /* Let us create the second sorted linked list Created linked list will be 2->4->6->8 */ push(&b, 8); push(&b, 6); push(&b, 4); push(&b, 2); /* Find the intersection two linked lists */ intersect = sortedIntersect(a, b); cout << \"\\n Linked list containing \" << \"common items of a & b \\n \"; printList(intersect); return 0;} // This code is contributed by shivanisinghss2110", "e": 20908, "s": 18616, "text": null }, { "code": "#include <stdio.h>#include <stdlib.h> /* Link list node */struct Node { int data; struct Node* next;}; struct Node* sortedIntersect( struct Node* a, struct Node* b){ /* base case */ if (a == NULL || b == NULL) return NULL; /* If both lists are non-empty */ /* advance the smaller list and call recursively */ if (a->data < b->data) return sortedIntersect(a->next, b); if (a->data > b->data) return sortedIntersect(a, b->next); // Below lines are executed only // when a->data == b->data struct Node* temp = (struct Node*)malloc( sizeof(struct Node)); temp->data = a->data; /* advance both lists and call recursively */ temp->next = sortedIntersect(a->next, b->next); return temp;} /* UTILITY FUNCTIONS *//* Function to insert a node atthe beginning of the linked list */void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*)malloc( sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print nodes in a given linked list */void printList(struct Node* node){ while (node != NULL) { printf(\"%d \", node->data); node = node->next; }} /* Driver program to test above functions*/int main(){ /* Start with the empty lists */ struct Node* a = NULL; struct Node* b = NULL; struct Node* intersect = NULL; /* Let us create the first sorted linked list to test the functions Created linked list will be 1->2->3->4->5->6 */ push(&a, 6); push(&a, 5); push(&a, 4); push(&a, 3); push(&a, 2); push(&a, 1); /* Let us create the second sorted linked list Created linked list will be 2->4->6->8 */ push(&b, 8); push(&b, 6); push(&b, 4); push(&b, 2); /* Find the intersection two linked lists */ intersect = sortedIntersect(a, b); printf(\"\\n Linked list containing common items of a & b \\n \"); printList(intersect); return 0;}", "e": 23087, "s": 20908, "text": null }, { "code": "import java.util.*; class GFG{ // Link list nodestatic class Node{ int data; Node next;}; static Node sortedIntersect(Node a, Node b){ // base case if (a == null || b == null) return null; /* If both lists are non-empty */ /* Advance the smaller list and call recursively */ if (a.data < b.data) return sortedIntersect(a.next, b); if (a.data > b.data) return sortedIntersect(a, b.next); // Below lines are executed only // when a.data == b.data Node temp = new Node(); temp.data = a.data; // Advance both lists and call recursively temp.next = sortedIntersect(a.next, b.next); return temp;} /* UTILITY FUNCTIONS *//* Function to insert a node atthe beginning of the linked list */static Node push(Node head_ref, int new_data){ /* Allocate node */ Node new_node = new Node(); /* Put in the data */ new_node.data = new_data; /* Link the old list off the new node */ new_node.next = head_ref; /* Move the head to point to the new node */ head_ref = new_node; return head_ref;} /* Function to print nodes in a given linked list */static void printList(Node node){ while (node != null) { System.out.print(\" \" + node.data); node = node.next; }} // Driver codepublic static void main(String[] args){ /* Start with the empty lists */ Node a = null; Node b = null; Node intersect = null; /* Let us create the first sorted linked list to test the functions Created linked list will be 1.2.3.4.5.6 */ a = push(a, 6); a = push(a, 5); a = push(a, 4); a = push(a, 3); a = push(a, 2); a = push(a, 1); /* Let us create the second sorted linked list Created linked list will be 2.4.6.8 */ b = push(b, 8); b = push(b, 6); b = push(b, 4); b = push(b, 2); /* Find the intersection two linked lists */ intersect = sortedIntersect(a, b); System.out.print(\"\\n Linked list containing \" + \"common items of a & b \\n \"); printList(intersect); }} // This code is contributed by umadevi9616", "e": 25247, "s": 23087, "text": null }, { "code": "# Link list nodeclass Node: def __init__(self): self.data = 0 self.next = None def sortedIntersect(a, b): # base case if (a == None or b == None): return None # If both lists are non-empty # Advance the smaller list and call recursively if (a.data < b.data): return sortedIntersect(a.next, b); if (a.data > b.data): return sortedIntersect(a, b.next); # Below lines are executed only # when a.data == b.data temp = Node(); temp.data = a.data; # Advance both lists and call recursively temp.next = sortedIntersect(a.next, b.next); return temp; # UTILITY FUNCTIONS # Function to insert a node at the beginning of the linked list def push(head_ref, new_data): # Allocate node new_node = Node() # Put in the data new_node.data = new_data; # Link the old list off the new node new_node.next = head_ref; # Move the head to point to the new node head_ref = new_node; return head_ref; # Function to print nodes in a given linked list def printList(node): while (node != None): print(node.data, end=\" \") node = node.next; # Driver code # Start with the empty listsa = Noneb = Noneintersect = None # Let us create the first sorted linked list to test the functions Created# linked list will be 1.2.3.4.5.6 a = push(a, 6)a = push(a, 5)a = push(a, 4)a = push(a, 3)a = push(a, 2)a = push(a, 1) # Let us create the second sorted linked list Created linked list will be# 2.4.6.8 b = push(b, 8)b = push(b, 6)b = push(b, 4)b = push(b, 2) # Find the intersection two linked listsintersect = sortedIntersect(a, b) print(\"\\n Linked list containing \" + \"common items of a & b\");printList(intersect) # This code is contributed by Saurabh Jaiswal", "e": 27061, "s": 25247, "text": null }, { "code": "using System; public class GFG { // Link list node public class Node { public int data; public Node next; }; static Node sortedIntersect(Node a, Node b) { // base case if (a == null || b == null) return null; /* If both lists are non-empty */ /* * Advance the smaller list and call recursively */ if (a.data < b.data) return sortedIntersect(a.next, b); if (a.data > b.data) return sortedIntersect(a, b.next); // Below lines are executed only // when a.data == b.data Node temp = new Node(); temp.data = a.data; // Advance both lists and call recursively temp.next = sortedIntersect(a.next, b.next); return temp; } /* UTILITY FUNCTIONS */ /* * Function to insert a node at the beginning of the linked list */ static Node push(Node head_ref, int new_data) { /* Allocate node */ Node new_node = new Node(); /* Put in the data */ new_node.data = new_data; /* Link the old list off the new node */ new_node.next = head_ref; /* Move the head to point to the new node */ head_ref = new_node; return head_ref; } /* * Function to print nodes in a given linked list */ static void printList(Node node) { while (node != null) { Console.Write(\" \" + node.data); node = node.next; } } // Driver code public static void Main(String[] args) { /* Start with the empty lists */ Node a = null; Node b = null; Node intersect = null; /* * Let us create the first sorted linked list to test the functions Created * linked list will be 1.2.3.4.5.6 */ a = push(a, 6); a = push(a, 5); a = push(a, 4); a = push(a, 3); a = push(a, 2); a = push(a, 1); /* * Let us create the second sorted linked list Created linked list will be * 2.4.6.8 */ b = push(b, 8); b = push(b, 6); b = push(b, 4); b = push(b, 2); /* Find the intersection two linked lists */ intersect = sortedIntersect(a, b); Console.Write(\"\\n Linked list containing \" + \"common items of a & b \\n \"); printList(intersect); }} // This code is contributed by umadevi9616", "e": 29250, "s": 27061, "text": null }, { "code": "<script> // Link list node class Node { constructor(){ this.data = 0; this.next = null;} } function sortedIntersect(a, b) { // base case if (a == null || b == null) return null; /* If both lists are non-empty */ /* * Advance the smaller list and call recursively */ if (a.data < b.data) return sortedIntersect(a.next, b); if (a.data > b.data) return sortedIntersect(a, b.next); // Below lines are executed only // when a.data == b.datavar temp = new Node(); temp.data = a.data; // Advance both lists and call recursively temp.next = sortedIntersect(a.next, b.next); return temp; } /* UTILITY FUNCTIONS */ /* * Function to insert a node at the beginning of the linked list */ function push(head_ref , new_data) { /* Allocate node */var new_node = new Node(); /* Put in the data */ new_node.data = new_data; /* Link the old list off the new node */ new_node.next = head_ref; /* Move the head to point to the new node */ head_ref = new_node; return head_ref; } /* * Function to print nodes in a given linked list */ function printList(node) { while (node != null) { document.write(\" \" + node.data); node = node.next; } } // Driver code /* Start with the empty lists */var a = null;var b = null;var intersect = null; /* * Let us create the first sorted linked list to test the functions Created * linked list will be 1.2.3.4.5.6 */ a = push(a, 6); a = push(a, 5); a = push(a, 4); a = push(a, 3); a = push(a, 2); a = push(a, 1); /* * Let us create the second sorted linked list Created linked list will be * 2.4.6.8 */ b = push(b, 8); b = push(b, 6); b = push(b, 4); b = push(b, 2); /* Find the intersection two linked lists */ intersect = sortedIntersect(a, b); document.write(\"\\n Linked list containing \" + \"common items of a & b <br/> \"); printList(intersect); // This code is contributed by Rajput-Ji</script>", "e": 31561, "s": 29250, "text": null }, { "code": null, "e": 31616, "s": 31561, "text": " Linked list containing common items of a & b \n 2 4 6" }, { "code": null, "e": 31638, "s": 31616, "text": "Complexity Analysis: " }, { "code": null, "e": 31787, "s": 31638, "text": "Time Complexity: O(m+n) where m and n are number of nodes in first and second linked lists respectively. Only one traversal of the lists are needed." }, { "code": null, "e": 31863, "s": 31787, "text": "Auxiliary Space: O(max(m, n)). The output list can store at most m+n nodes." }, { "code": null, "e": 31885, "s": 31863, "text": "Method 4: Use Hashing" }, { "code": null, "e": 31890, "s": 31885, "text": "Java" }, { "code": null, "e": 31893, "s": 31890, "text": "C#" }, { "code": "import java.util.*; // This code is contributed by ayyuce demirbaspublic class LinkedList { Node head; static class Node { int data; Node next; Node(int d) { data = d; next=null; } } public void printList() { Node n= head; while(n!=null) { System.out.println(n.data+ \" \"); n=n.next; } } public void append(int d) { Node n= new Node(d); if(head== null) { head= new Node(d); return; } n.next=null; Node last= head; while(last.next !=null) { last=last.next; } last.next=n; return; } static int[] intersection(Node tmp1, Node tmp2, int k) { int[] res = new int[k]; HashSet<Integer> set = new HashSet<Integer>(); while(tmp1 != null) { set.add(tmp1.data); tmp1=tmp1.next; } int cnt=0; while(tmp2 != null) { if(set.contains(tmp2.data)) { res[cnt]=tmp2.data; cnt++; } tmp2=tmp2.next; } return res; } public static void main(String[] args) { LinkedList ll = new LinkedList(); LinkedList ll1 = new LinkedList(); ll.append(0); ll.append(1); ll.append(2); ll.append(3); ll.append(4); ll.append(5); ll.append(6); ll.append(7); ll1.append(9); ll1.append(0); ll1.append(12); ll1.append(3); ll1.append(4); ll1.append(5); ll1.append(6); ll1.append(7); int[] arr= intersection(ll.head, ll1.head,6); for(int i : arr) { System.out.println(i); } } }", "e": 34208, "s": 31893, "text": null }, { "code": "using System;using System.Collections.Generic; // This code is contributed by ayyuce demirbaspublic class List { Node head; public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } public void printList() { Node n = head; while (n != null) { Console.WriteLine(n.data + \" \"); n = n.next; } } public void append(int d) { Node n = new Node(d); if (head == null) { head = new Node(d); return; } n.next = null; Node last = head; while (last.next != null) { last = last.next; } last.next = n; return; } static int[] intersection(Node tmp1, Node tmp2, int k) { int[] res = new int[k]; HashSet<int> set = new HashSet<int>(); while (tmp1 != null) { set.Add(tmp1.data); tmp1 = tmp1.next; } int cnt = 0; while (tmp2 != null) { if (set.Contains(tmp2.data)) { res[cnt] = tmp2.data; cnt++; } tmp2 = tmp2.next; } return res; } public static void Main(String[] args) { List ll = new List(); List ll1 = new List(); ll.append(0); ll.append(1); ll.append(2); ll.append(3); ll.append(4); ll.append(5); ll.append(6); ll.append(7); ll1.append(9); ll1.append(0); ll1.append(12); ll1.append(3); ll1.append(4); ll1.append(5); ll1.append(6); ll1.append(7); int[] arr = intersection(ll.head, ll1.head, 6); foreach(int i in arr) { Console.WriteLine(i); } }} // This code is contributed by umadevi9616", "e": 35769, "s": 34208, "text": null }, { "code": null, "e": 35781, "s": 35769, "text": "0\n3\n4\n5\n6\n7" }, { "code": null, "e": 35802, "s": 35781, "text": "Complexity Analysis:" }, { "code": null, "e": 35824, "s": 35802, "text": "Time Complexity: O(n)" }, { "code": null, "e": 36004, "s": 35824, "text": "Please write comments if you find the above codes/algorithms incorrect, or find better ways to solve the same problem.References: cslibrary.stanford.edu/105/LinkedListProblems.pdf" }, { "code": null, "e": 36015, "s": 36004, "text": "andrew1234" }, { "code": null, "e": 36028, "s": 36015, "text": "Akanksha_Rai" }, { "code": null, "e": 36041, "s": 36028, "text": "mukul garg 1" }, { "code": null, "e": 36051, "s": 36041, "text": "rutvik_56" }, { "code": null, "e": 36061, "s": 36051, "text": "pratham76" }, { "code": null, "e": 36072, "s": 36061, "text": "avllikhita" }, { "code": null, "e": 36085, "s": 36072, "text": "todaysgaurav" }, { "code": null, "e": 36097, "s": 36085, "text": "aashish1995" }, { "code": null, "e": 36114, "s": 36097, "text": "khushboogoyal499" }, { "code": null, "e": 36133, "s": 36114, "text": "shivanisinghss2110" }, { "code": null, "e": 36149, "s": 36133, "text": "simranarora5sos" }, { "code": null, "e": 36156, "s": 36149, "text": "ayyuce" }, { "code": null, "e": 36168, "s": 36156, "text": "umadevi9616" }, { "code": null, "e": 36178, "s": 36168, "text": "Rajput-Ji" }, { "code": null, "e": 36187, "s": 36178, "text": "sweetyty" }, { "code": null, "e": 36202, "s": 36187, "text": "sagartomar9927" }, { "code": null, "e": 36219, "s": 36202, "text": "_saurabh_jaiswal" }, { "code": null, "e": 36232, "s": 36219, "text": "simmytarika5" }, { "code": null, "e": 36239, "s": 36232, "text": "Amazon" }, { "code": null, "e": 36248, "s": 36239, "text": "D-E-Shaw" }, { "code": null, "e": 36258, "s": 36248, "text": "Microsoft" }, { "code": null, "e": 36265, "s": 36258, "text": "Zopper" }, { "code": null, "e": 36277, "s": 36265, "text": "Linked List" }, { "code": null, "e": 36285, "s": 36277, "text": "Sorting" }, { "code": null, "e": 36292, "s": 36285, "text": "Amazon" }, { "code": null, "e": 36302, "s": 36292, "text": "Microsoft" }, { "code": null, "e": 36311, "s": 36302, "text": "D-E-Shaw" }, { "code": null, "e": 36318, "s": 36311, "text": "Zopper" }, { "code": null, "e": 36330, "s": 36318, "text": "Linked List" }, { "code": null, "e": 36338, "s": 36330, "text": "Sorting" }, { "code": null, "e": 36436, "s": 36338, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36484, "s": 36436, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 36503, "s": 36484, "text": "LinkedList in Java" }, { "code": null, "e": 36535, "s": 36503, "text": "Introduction to Data Structures" }, { "code": null, "e": 36599, "s": 36535, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 36646, "s": 36599, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 36657, "s": 36646, "text": "Merge Sort" }, { "code": null, "e": 36679, "s": 36657, "text": "Bubble Sort Algorithm" }, { "code": null, "e": 36689, "s": 36679, "text": "QuickSort" }, { "code": null, "e": 36704, "s": 36689, "text": "Insertion Sort" } ]
Count of distinct XORs formed by rearranging two Binary strings
06 Jun, 2022 Given two binary strings A and B of equal length N, the task is to find the number of distinct XORs possible by arbitrarily reordering the two binary strings. Since the number can be large enough, find the number modulo 109 + 7 Examples: Input: A = “00”, B = “01” Output: 2 Explanation: There are two possible results by rearranging the digits of the string B. They are: “10” and “01” Input: A = “010”, B = “100” Output: 4 Explanation: There are four possible results possible by rearranging the digits of both the strings. They are: “000”, “110”, “011”, “101” Approach: Since we know that 0 XOR 0 = 0 0 XOR 1 = 1 1 XOR 0 = 1 1 XOR 1 = 0 Therefore, to get an XOR value as ‘1’ at any index of the result string, the input strings must have odd number of 1s at that index. Now, we will try to rearrange the Binary strings in a way, that maximum number of indices have an odd number of 1s at them. This can be visualized by the following example: Therefore, from the above observation, the idea is to find the minimum and the maximum number of 1’s possible by reordering the strings. To find the Maximum ‘1’s: The maximum ‘1’s in the result would occur when maximum {0, 1} and {1, 0} pairs are formed. Therefore, To find the Maximum ‘1’s: The maximum ‘1’s in the result would occur when maximum {0, 1} and {1, 0} pairs are formed. Therefore, Maximum number of {0, 1} pairs = minimum(count of ‘0’ in A, count of ‘1’ in B) Maximum number of {1, 0} pairs = minimum(count of ‘1’ in A, count of ‘0’ in B)Therefore, Maximum number of ‘1’s in the XOR = Maximum number of {0, 1} pairs + Maximum number of {1, 0} pairs To find the Minimum ‘1’s: This case can be seen as the converse of the maximum number of ‘0’s in the result. Similarly, the maximum ‘0’s in the result would occur when maximum {0, 0} and {1, 1} pairs are formed. Therefore, Maximum number of {0, 0} pairs = minimum(count of ‘0’ in A, count of ‘0’ in B) Maximum number of {1, 1} pairs = minimum(count of ‘1’ in A, count of ‘1’ in B) Maximum number of ‘0’s in the XOR = Maximum number of {0, 0} pairs + Maximum number of {1, 1} pairsTherefore, Minimum number of ‘1’s in the XOR = N – Maximum number of ‘0’s in the XOR All the combinations of 1’s can be formed in between these two numbers (minimum and maximum) with the difference of 2. Finally, the total number of possible ways to get the result can be calculated by the number of combinations from the minimum number of 1’s and the maximum number of 1’s with a step of 2. Below is the implementation of the above approach: C++14 Java Python3 C# Javascript // C++ program to find the number of// distinct XORs formed by rearranging// two binary strings#include <bits/stdc++.h> using namespace std; // function to compute modulo powerlong long power(long long a, long long b, long long mod){ long long aa = 1; while(b) { if(b&1) { aa = aa * a; aa %= mod; } a = a * a; a %= mod; b /= 2; } return aa;} // Function to calculate nCr % p// over a rangelong long nCrRangeSum(long long n, long long r1, long long r2, long long p){ // Initialize the numerator // and denominator long long num = 1, den = 1; // Initialize the sum long long sum = 0; // nC0 is 1 if (r1 == 0) sum += 1; // Traversing till the range for (int i = 0; i < r2; i++) { // Computing the numerator num = (num * (n - i)) % p; // Computing the denominator den = (den * (i + 1)) % p; // If 'i' lies between the given range // and is at an even long long interval from // the starting range because // the combinations at a step of 2 // is required if(i - r1 >= -1 and (i - r1 + 1) % 2 == 0) { // Computing nCr and adding the value // sum sum += (num * power(den, p - 2, p)) % p; sum %= p; } } return sum;} // Function to find the number of// distinct XORs formed by// rearranging two binary stringsint compute(string A, string B, int N){ // Initializing the count variable // to 0 int c0A = 0, c1A = 0, c0B = 0, c1B = 0; // Iterating through A for (char c:A) { // Increment the c1A variable // if the current element is 1 if (c == '1') c1A += 1; // Increment the c0A variable // if the current element is 0 else if (c == '0') c0A += 1; } // Iterating through B for (char c:B){ // Increment the c1B variable // if the current element is 1 if (c == '1') c1B += 1; // Increment the c0A variable // if the current element is 0 else if (c == '0') c0B += 1; } // Finding the minimum number of '1's in the XOR // and the maximum number of '1's in the XOR int max1xor = min(c0A, c1B) + min(c1A, c0B); int min1xor = N - min(c0B, c0A) - min(c1A, c1B); // Compute the number of combinations between // the minimum number of 1's and the maximum // number of 1's and perform % with 10^9 + 7 int ans = nCrRangeSum(N, min1xor, max1xor, 1000000000 + 7); // Return the answer return ans;} // Driver codeint main(){ long long N = 3; string A = "010"; string B = "100"; cout << compute(A, B,N); return 0;} // This code is contributed by mohit kumar 29 // JAVA program to find the number of// distinct Bitwise XORs formed by rearranging// two binary strings class GFG{ // function to compute modular exponentiation // i.e. to find (a^b) % mod static long mod_power(long a, long b, long mod) { long result = 1l; while(b > 0) { if((b&1) == 0) // b is even { result = a * a; a %= mod; b /= 2; } else // b is odd { result = result * a; result %= mod; } } return result; } // method to evaluate nCr modulo p // over an interval static long nCr_RangeSum(long n, long r1, long r2, long p) { // initializing numerator // and denominator long num = 1, den = 1; // initialize the sum long sum = 0l; // nC0 is 1 if(r1 == 0) sum += 1l; // Iterating through the range for(int i = 0; i < r2; i++) { // computing the numerator num = (num * (n - i)) % p; // computing the denominator den = (den * (i + 1)) % p; // If 'i' lies between the given range // and is at an even interval from // the starting range because // the combinations at a step of 2 // is required if(i - r1 >= -1 && (i - r1 + 1) % 2 == 0) { // Computing nCr and adding the value // to the sum sum += (num * mod_power(den, p - 2, p)) % p; sum %= p; } } return sum; } // method to find the number of // distinct XORs formed by // rearrangement of two binary strings static long compute(String A, String B, int N) { // Initializing the counter variables // to 0 int c0A = 0, c1A = 0, c0B = 0, c1B = 0; // Iterating through A's characters for (char c : A.toCharArray()) { // Increment the c1A variable // if the current element is 1 if (c == '1') c1A += 1; // Increment the c0A variable // if the current element is 0 else if (c == '0') c0A += 1; } // Iterating through B's characters for (char c : B.toCharArray()) { // Increment the c1B variable // if the current element is 1 if (c == '1') c1B += 1; // Increment the c0A variable // if the current element is 0 else if (c == '0') c0B += 1; } // Finding the minimum number of '1's in the XOR // and the maximum number of '1's in the XOR int max1xor = Math.min(c0A, c1B) + Math.min(c1A, c0B); int min1xor = N - Math.min(c0B, c0A) - Math.min(c1A, c1B); // Compute the number of combinations between // the minimum number of 1's and the maximum // number of 1's and perform modulo with 10^9 + 7 long ans = nCr_RangeSum(N, min1xor, max1xor, 1000000000 + 7); // Return the answer return ans; } // Driver code public static void main(String[] args) { int N = 3; // length of each string String A = "010"; String B = "100"; System.out.print(compute(A, B, N)); }} // This Code is contributed by Soumitri Chattopadhyay. # Python3 program to find the number of# distinct XORs formed by rearranging# two binary strings # Function to calculate nCr % p# over a rangedef nCrRangeSum(n, r1, r2, p): # Initialize the numerator # and denominator num = den = 1 # Initialize the sum sum = 0 # nC0 is 1 if r1 == 0: sum += 1 # Traversing till the range for i in range(r2): # Computing the numerator num = (num * (n - i)) % p # Computing the denominator den = (den * (i + 1)) % p # If 'i' lies between the given range # and is at an even interval from # the starting range because # the combinations at a step of 2 # is required if(i - r1 >= -1 and (i - r1 + 1) % 2 == 0): # Computing nCr and adding the value # sum sum += (num * pow(den, p - 2, p)) % p sum %= p return sum # Function to find the number of# distinct XORs formed by# rearranging two binary stringsdef compute(A, B): # Initializing the count variable # to 0 c0A = c1A = c0B = c1B = 0 # Iterating through A for c in A: # Increment the c1A variable # if the current element is 1 if c == '1': c1A += 1 # Increment the c0A variable # if the current element is 0 elif c == '0': c0A += 1 # Iterating through B for c in B: # Increment the c1B variable # if the current element is 1 if c == '1': c1B += 1 # Increment the c0A variable # if the current element is 0 elif c == '0': c0B += 1 # Finding the minimum number of '1's in the XOR # and the maximum number of '1's in the XOR max1xor = min(c0A, c1B) + min(c1A, c0B) min1xor = N - min(c0B, c0A) - min(c1A, c1B) # Compute the number of combinations between # the minimum number of 1's and the maximum # number of 1's and perform % with 10^9 + 7 ans = nCrRangeSum(N, min1xor, max1xor, 10**9 + 7) # Return the answer return ans # Driver codeif __name__ == "__main__": N = 3 A = "010" B = "100" print(compute(A, B)) // C# program to find the number of // distinct Bitwise XORs formed by// rearranging two binary stringsusing System; class GFG{ // Function to compute modular exponentiation// i.e. to find (a^b) % mod static long mod_power(long a, long b, long mod){ long result = 1; while (b > 0) { if ((b & 1) == 0) // b is even { result = a * a; a %= mod; b /= 2; } else // b is odd { result = result * a; result %= mod; } } return result;} // Function to evaluate nCr modulo p// over an intervalstatic long nCr_RangeSum(long n, long r1, long r2, long p){ // Initializing numerator // and denominator long num = 1, den = 1; // Initialize the sum long sum = 0; // nC0 is 1 if (r1 == 0) sum += 1; // Iterating through the range for(int i = 0; i < r2; i++) { // Computing the numerator num = (num * (n - i)) % p; // Computing the denominator den = (den * (i + 1)) % p; // If 'i' lies between the given range // and is at an even interval from // the starting range because // the combinations at a step of 2 // is required if (i - r1 >= -1 && (i - r1 + 1) % 2 == 0) { // Computing nCr and adding the value // to the sum sum += (num * mod_power( den, p - 2, p)) % p; sum %= p; } } return sum;} // Function to find the number of distinct// XORs formed by rearrangement of two// binary stringsstatic long compute(string A, string B, int N){ // Initializing the counter variables // to 0 int c0A = 0, c1A = 0, c0B = 0, c1B = 0; // Iterating through A's characters foreach(char c in A) { // Increment the c1A variable // if the current element is 1 if (c == '1') c1A += 1; // Increment the c0A variable // if the current element is 0 else if (c == '0') c0A += 1; } // Iterating through B's characters foreach(char c in B) { // Increment the c1B variable // if the current element is 1 if (c == '1') c1B += 1; // Increment the c0A variable // if the current element is 0 else if (c == '0') c0B += 1; } // Finding the minimum number of // '1's in the XOR and the maximum // number of '1's in the XOR int max1xor = Math.Min(c0A, c1B) + Math.Min(c1A, c0B); int min1xor = N - Math.Min(c0B, c0A) - Math.Min(c1A, c1B); // Compute the number of combinations // between the minimum number of 1's // and the maximum number of 1's and // perform modulo with 10^9 + 7 long ans = nCr_RangeSum(N, min1xor, max1xor, 1000000000 + 7); // Return the answer return ans; } // Driver codestatic public void Main(){ // Length of each string int N = 3; string A = "010"; string B = "100"; Console.WriteLine(compute(A, B, N));}} // This code is contributed by offbeat // JavaScript program to find the number of// distinct XORs formed by rearranging// two binary strings // function to compute modulo powerfunction power(a, b, mod){ var aa = 1n; while (b) { if (BigInt(b) & 1n) { aa = aa * a; aa %= mod; } a = a * a; a %= mod; b = Math.floor(Number(BigInt(b) / 2n)); } return aa;} // Function to calculate nCr % p// over a rangefunction nCrRangeSum(n, r1, r2, p){ // Initialize the numerator // and denominator var num = 1n; var den = 1n; // Initialize the sum var sum = 0n; // nC0 is 1 if (r1 == 0) sum += 1n; // Traversing till the range for (var i = 0; i < r2; i++) { // Computing the numerator num = (num * (BigInt(n) - BigInt(i))) % p; // Computing the denominator den = BigInt(den * (BigInt(i) + 1n)) % p; // If 'i' lies between the given range // and is at an even long long interval from // the starting range because // the combinations at a step of 2 // is required if (i - r1 >= -1 && (i - r1 + 1) % 2 == 0) { // Computing nCr and adding the value // sum sum += BigInt(num * power(den, p - 2n, p)) % p; sum %= p; } } return Number(sum);} // Function to find the number of// distinct XORs formed by// rearranging two binary stringsfunction compute(A, B, N){ // Initializing the count variable // to 0 var c0A = 0; var c1A = 0; var c0B = 0; var c1B = 0; // Iterating through A for (var c of A) { // Increment the c1A variable // if the current element is 1 if (c == '1') c1A += 1; // Increment the c0A variable // if the current element is 0 else if (c == '0') c0A += 1; } // Iterating through B for (var c of B) { // Increment the c1B variable // if the current element is 1 if (c == '1') c1B += 1; // Increment the c0A variable // if the current element is 0 else if (c == '0') c0B += 1; } // Finding the minimum number of '1's in the XOR // and the maximum number of '1's in the XOR var max1xor = Math.min(c0A, c1B) + Math.min(c1A, c0B); var min1xor = N - Math.min(c0B, c0A) - Math.min(c1A, c1B); // Compute the number of combinations between // the minimum number of 1's and the maximum // number of 1's and perform % with 10^9 + 7 var ans = nCrRangeSum(N, min1xor, max1xor, BigInt(1000000000 + 7)); // Return the answer return ans;} // Driver codevar N = 3;var A = "010";var B = "100"; // Function callconsole.log(compute(A, B, N)); // This code is contributed by phasing17 4 mohit kumar 29 chatterjee0soumitri offbeat phasing17 array-rearrange binary-string Bitwise-XOR Permutation and Combination Arrays Bit Magic Combinatorial Mathematical Strings Write From Home Arrays Strings Mathematical Bit Magic Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Linear Search Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Bitwise Operators in C/C++ Left Shift and Right Shift Operators in C/C++ Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Count set bits in an integer How to swap two numbers without using a temporary variable?
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jun, 2022" }, { "code": null, "e": 280, "s": 52, "text": "Given two binary strings A and B of equal length N, the task is to find the number of distinct XORs possible by arbitrarily reordering the two binary strings. Since the number can be large enough, find the number modulo 109 + 7" }, { "code": null, "e": 291, "s": 280, "text": "Examples: " }, { "code": null, "e": 438, "s": 291, "text": "Input: A = “00”, B = “01” Output: 2 Explanation: There are two possible results by rearranging the digits of the string B. They are: “10” and “01”" }, { "code": null, "e": 615, "s": 438, "text": "Input: A = “010”, B = “100” Output: 4 Explanation: There are four possible results possible by rearranging the digits of both the strings. They are: “000”, “110”, “011”, “101” " }, { "code": null, "e": 627, "s": 615, "text": "Approach: " }, { "code": null, "e": 646, "s": 627, "text": "Since we know that" }, { "code": null, "e": 694, "s": 646, "text": "0 XOR 0 = 0\n0 XOR 1 = 1\n1 XOR 0 = 1\n1 XOR 1 = 0" }, { "code": null, "e": 827, "s": 694, "text": "Therefore, to get an XOR value as ‘1’ at any index of the result string, the input strings must have odd number of 1s at that index." }, { "code": null, "e": 1000, "s": 827, "text": "Now, we will try to rearrange the Binary strings in a way, that maximum number of indices have an odd number of 1s at them. This can be visualized by the following example:" }, { "code": null, "e": 1266, "s": 1000, "text": "Therefore, from the above observation, the idea is to find the minimum and the maximum number of 1’s possible by reordering the strings. To find the Maximum ‘1’s: The maximum ‘1’s in the result would occur when maximum {0, 1} and {1, 0} pairs are formed. Therefore," }, { "code": null, "e": 1395, "s": 1266, "text": "To find the Maximum ‘1’s: The maximum ‘1’s in the result would occur when maximum {0, 1} and {1, 0} pairs are formed. Therefore," }, { "code": null, "e": 1665, "s": 1395, "text": "Maximum number of {0, 1} pairs = minimum(count of ‘0’ in A, count of ‘1’ in B) Maximum number of {1, 0} pairs = minimum(count of ‘1’ in A, count of ‘0’ in B)Therefore, Maximum number of ‘1’s in the XOR = Maximum number of {0, 1} pairs + Maximum number of {1, 0} pairs " }, { "code": null, "e": 1888, "s": 1665, "text": "To find the Minimum ‘1’s: This case can be seen as the converse of the maximum number of ‘0’s in the result. Similarly, the maximum ‘0’s in the result would occur when maximum {0, 0} and {1, 1} pairs are formed. Therefore," }, { "code": null, "e": 2232, "s": 1888, "text": "Maximum number of {0, 0} pairs = minimum(count of ‘0’ in A, count of ‘0’ in B) Maximum number of {1, 1} pairs = minimum(count of ‘1’ in A, count of ‘1’ in B) Maximum number of ‘0’s in the XOR = Maximum number of {0, 0} pairs + Maximum number of {1, 1} pairsTherefore, Minimum number of ‘1’s in the XOR = N – Maximum number of ‘0’s in the XOR " }, { "code": null, "e": 2351, "s": 2232, "text": "All the combinations of 1’s can be formed in between these two numbers (minimum and maximum) with the difference of 2." }, { "code": null, "e": 2539, "s": 2351, "text": "Finally, the total number of possible ways to get the result can be calculated by the number of combinations from the minimum number of 1’s and the maximum number of 1’s with a step of 2." }, { "code": null, "e": 2591, "s": 2539, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 2597, "s": 2591, "text": "C++14" }, { "code": null, "e": 2602, "s": 2597, "text": "Java" }, { "code": null, "e": 2610, "s": 2602, "text": "Python3" }, { "code": null, "e": 2613, "s": 2610, "text": "C#" }, { "code": null, "e": 2624, "s": 2613, "text": "Javascript" }, { "code": "// C++ program to find the number of// distinct XORs formed by rearranging// two binary strings#include <bits/stdc++.h> using namespace std; // function to compute modulo powerlong long power(long long a, long long b, long long mod){ long long aa = 1; while(b) { if(b&1) { aa = aa * a; aa %= mod; } a = a * a; a %= mod; b /= 2; } return aa;} // Function to calculate nCr % p// over a rangelong long nCrRangeSum(long long n, long long r1, long long r2, long long p){ // Initialize the numerator // and denominator long long num = 1, den = 1; // Initialize the sum long long sum = 0; // nC0 is 1 if (r1 == 0) sum += 1; // Traversing till the range for (int i = 0; i < r2; i++) { // Computing the numerator num = (num * (n - i)) % p; // Computing the denominator den = (den * (i + 1)) % p; // If 'i' lies between the given range // and is at an even long long interval from // the starting range because // the combinations at a step of 2 // is required if(i - r1 >= -1 and (i - r1 + 1) % 2 == 0) { // Computing nCr and adding the value // sum sum += (num * power(den, p - 2, p)) % p; sum %= p; } } return sum;} // Function to find the number of// distinct XORs formed by// rearranging two binary stringsint compute(string A, string B, int N){ // Initializing the count variable // to 0 int c0A = 0, c1A = 0, c0B = 0, c1B = 0; // Iterating through A for (char c:A) { // Increment the c1A variable // if the current element is 1 if (c == '1') c1A += 1; // Increment the c0A variable // if the current element is 0 else if (c == '0') c0A += 1; } // Iterating through B for (char c:B){ // Increment the c1B variable // if the current element is 1 if (c == '1') c1B += 1; // Increment the c0A variable // if the current element is 0 else if (c == '0') c0B += 1; } // Finding the minimum number of '1's in the XOR // and the maximum number of '1's in the XOR int max1xor = min(c0A, c1B) + min(c1A, c0B); int min1xor = N - min(c0B, c0A) - min(c1A, c1B); // Compute the number of combinations between // the minimum number of 1's and the maximum // number of 1's and perform % with 10^9 + 7 int ans = nCrRangeSum(N, min1xor, max1xor, 1000000000 + 7); // Return the answer return ans;} // Driver codeint main(){ long long N = 3; string A = \"010\"; string B = \"100\"; cout << compute(A, B,N); return 0;} // This code is contributed by mohit kumar 29", "e": 5466, "s": 2624, "text": null }, { "code": "// JAVA program to find the number of// distinct Bitwise XORs formed by rearranging// two binary strings class GFG{ // function to compute modular exponentiation // i.e. to find (a^b) % mod static long mod_power(long a, long b, long mod) { long result = 1l; while(b > 0) { if((b&1) == 0) // b is even { result = a * a; a %= mod; b /= 2; } else // b is odd { result = result * a; result %= mod; } } return result; } // method to evaluate nCr modulo p // over an interval static long nCr_RangeSum(long n, long r1, long r2, long p) { // initializing numerator // and denominator long num = 1, den = 1; // initialize the sum long sum = 0l; // nC0 is 1 if(r1 == 0) sum += 1l; // Iterating through the range for(int i = 0; i < r2; i++) { // computing the numerator num = (num * (n - i)) % p; // computing the denominator den = (den * (i + 1)) % p; // If 'i' lies between the given range // and is at an even interval from // the starting range because // the combinations at a step of 2 // is required if(i - r1 >= -1 && (i - r1 + 1) % 2 == 0) { // Computing nCr and adding the value // to the sum sum += (num * mod_power(den, p - 2, p)) % p; sum %= p; } } return sum; } // method to find the number of // distinct XORs formed by // rearrangement of two binary strings static long compute(String A, String B, int N) { // Initializing the counter variables // to 0 int c0A = 0, c1A = 0, c0B = 0, c1B = 0; // Iterating through A's characters for (char c : A.toCharArray()) { // Increment the c1A variable // if the current element is 1 if (c == '1') c1A += 1; // Increment the c0A variable // if the current element is 0 else if (c == '0') c0A += 1; } // Iterating through B's characters for (char c : B.toCharArray()) { // Increment the c1B variable // if the current element is 1 if (c == '1') c1B += 1; // Increment the c0A variable // if the current element is 0 else if (c == '0') c0B += 1; } // Finding the minimum number of '1's in the XOR // and the maximum number of '1's in the XOR int max1xor = Math.min(c0A, c1B) + Math.min(c1A, c0B); int min1xor = N - Math.min(c0B, c0A) - Math.min(c1A, c1B); // Compute the number of combinations between // the minimum number of 1's and the maximum // number of 1's and perform modulo with 10^9 + 7 long ans = nCr_RangeSum(N, min1xor, max1xor, 1000000000 + 7); // Return the answer return ans; } // Driver code public static void main(String[] args) { int N = 3; // length of each string String A = \"010\"; String B = \"100\"; System.out.print(compute(A, B, N)); }} // This Code is contributed by Soumitri Chattopadhyay.", "e": 9028, "s": 5466, "text": null }, { "code": "# Python3 program to find the number of# distinct XORs formed by rearranging# two binary strings # Function to calculate nCr % p# over a rangedef nCrRangeSum(n, r1, r2, p): # Initialize the numerator # and denominator num = den = 1 # Initialize the sum sum = 0 # nC0 is 1 if r1 == 0: sum += 1 # Traversing till the range for i in range(r2): # Computing the numerator num = (num * (n - i)) % p # Computing the denominator den = (den * (i + 1)) % p # If 'i' lies between the given range # and is at an even interval from # the starting range because # the combinations at a step of 2 # is required if(i - r1 >= -1 and (i - r1 + 1) % 2 == 0): # Computing nCr and adding the value # sum sum += (num * pow(den, p - 2, p)) % p sum %= p return sum # Function to find the number of# distinct XORs formed by# rearranging two binary stringsdef compute(A, B): # Initializing the count variable # to 0 c0A = c1A = c0B = c1B = 0 # Iterating through A for c in A: # Increment the c1A variable # if the current element is 1 if c == '1': c1A += 1 # Increment the c0A variable # if the current element is 0 elif c == '0': c0A += 1 # Iterating through B for c in B: # Increment the c1B variable # if the current element is 1 if c == '1': c1B += 1 # Increment the c0A variable # if the current element is 0 elif c == '0': c0B += 1 # Finding the minimum number of '1's in the XOR # and the maximum number of '1's in the XOR max1xor = min(c0A, c1B) + min(c1A, c0B) min1xor = N - min(c0B, c0A) - min(c1A, c1B) # Compute the number of combinations between # the minimum number of 1's and the maximum # number of 1's and perform % with 10^9 + 7 ans = nCrRangeSum(N, min1xor, max1xor, 10**9 + 7) # Return the answer return ans # Driver codeif __name__ == \"__main__\": N = 3 A = \"010\" B = \"100\" print(compute(A, B))", "e": 11187, "s": 9028, "text": null }, { "code": "// C# program to find the number of // distinct Bitwise XORs formed by// rearranging two binary stringsusing System; class GFG{ // Function to compute modular exponentiation// i.e. to find (a^b) % mod static long mod_power(long a, long b, long mod){ long result = 1; while (b > 0) { if ((b & 1) == 0) // b is even { result = a * a; a %= mod; b /= 2; } else // b is odd { result = result * a; result %= mod; } } return result;} // Function to evaluate nCr modulo p// over an intervalstatic long nCr_RangeSum(long n, long r1, long r2, long p){ // Initializing numerator // and denominator long num = 1, den = 1; // Initialize the sum long sum = 0; // nC0 is 1 if (r1 == 0) sum += 1; // Iterating through the range for(int i = 0; i < r2; i++) { // Computing the numerator num = (num * (n - i)) % p; // Computing the denominator den = (den * (i + 1)) % p; // If 'i' lies between the given range // and is at an even interval from // the starting range because // the combinations at a step of 2 // is required if (i - r1 >= -1 && (i - r1 + 1) % 2 == 0) { // Computing nCr and adding the value // to the sum sum += (num * mod_power( den, p - 2, p)) % p; sum %= p; } } return sum;} // Function to find the number of distinct// XORs formed by rearrangement of two// binary stringsstatic long compute(string A, string B, int N){ // Initializing the counter variables // to 0 int c0A = 0, c1A = 0, c0B = 0, c1B = 0; // Iterating through A's characters foreach(char c in A) { // Increment the c1A variable // if the current element is 1 if (c == '1') c1A += 1; // Increment the c0A variable // if the current element is 0 else if (c == '0') c0A += 1; } // Iterating through B's characters foreach(char c in B) { // Increment the c1B variable // if the current element is 1 if (c == '1') c1B += 1; // Increment the c0A variable // if the current element is 0 else if (c == '0') c0B += 1; } // Finding the minimum number of // '1's in the XOR and the maximum // number of '1's in the XOR int max1xor = Math.Min(c0A, c1B) + Math.Min(c1A, c0B); int min1xor = N - Math.Min(c0B, c0A) - Math.Min(c1A, c1B); // Compute the number of combinations // between the minimum number of 1's // and the maximum number of 1's and // perform modulo with 10^9 + 7 long ans = nCr_RangeSum(N, min1xor, max1xor, 1000000000 + 7); // Return the answer return ans; } // Driver codestatic public void Main(){ // Length of each string int N = 3; string A = \"010\"; string B = \"100\"; Console.WriteLine(compute(A, B, N));}} // This code is contributed by offbeat", "e": 14479, "s": 11187, "text": null }, { "code": "// JavaScript program to find the number of// distinct XORs formed by rearranging// two binary strings // function to compute modulo powerfunction power(a, b, mod){ var aa = 1n; while (b) { if (BigInt(b) & 1n) { aa = aa * a; aa %= mod; } a = a * a; a %= mod; b = Math.floor(Number(BigInt(b) / 2n)); } return aa;} // Function to calculate nCr % p// over a rangefunction nCrRangeSum(n, r1, r2, p){ // Initialize the numerator // and denominator var num = 1n; var den = 1n; // Initialize the sum var sum = 0n; // nC0 is 1 if (r1 == 0) sum += 1n; // Traversing till the range for (var i = 0; i < r2; i++) { // Computing the numerator num = (num * (BigInt(n) - BigInt(i))) % p; // Computing the denominator den = BigInt(den * (BigInt(i) + 1n)) % p; // If 'i' lies between the given range // and is at an even long long interval from // the starting range because // the combinations at a step of 2 // is required if (i - r1 >= -1 && (i - r1 + 1) % 2 == 0) { // Computing nCr and adding the value // sum sum += BigInt(num * power(den, p - 2n, p)) % p; sum %= p; } } return Number(sum);} // Function to find the number of// distinct XORs formed by// rearranging two binary stringsfunction compute(A, B, N){ // Initializing the count variable // to 0 var c0A = 0; var c1A = 0; var c0B = 0; var c1B = 0; // Iterating through A for (var c of A) { // Increment the c1A variable // if the current element is 1 if (c == '1') c1A += 1; // Increment the c0A variable // if the current element is 0 else if (c == '0') c0A += 1; } // Iterating through B for (var c of B) { // Increment the c1B variable // if the current element is 1 if (c == '1') c1B += 1; // Increment the c0A variable // if the current element is 0 else if (c == '0') c0B += 1; } // Finding the minimum number of '1's in the XOR // and the maximum number of '1's in the XOR var max1xor = Math.min(c0A, c1B) + Math.min(c1A, c0B); var min1xor = N - Math.min(c0B, c0A) - Math.min(c1A, c1B); // Compute the number of combinations between // the minimum number of 1's and the maximum // number of 1's and perform % with 10^9 + 7 var ans = nCrRangeSum(N, min1xor, max1xor, BigInt(1000000000 + 7)); // Return the answer return ans;} // Driver codevar N = 3;var A = \"010\";var B = \"100\"; // Function callconsole.log(compute(A, B, N)); // This code is contributed by phasing17", "e": 17278, "s": 14479, "text": null }, { "code": null, "e": 17280, "s": 17278, "text": "4" }, { "code": null, "e": 17297, "s": 17282, "text": "mohit kumar 29" }, { "code": null, "e": 17317, "s": 17297, "text": "chatterjee0soumitri" }, { "code": null, "e": 17325, "s": 17317, "text": "offbeat" }, { "code": null, "e": 17335, "s": 17325, "text": "phasing17" }, { "code": null, "e": 17351, "s": 17335, "text": "array-rearrange" }, { "code": null, "e": 17365, "s": 17351, "text": "binary-string" }, { "code": null, "e": 17377, "s": 17365, "text": "Bitwise-XOR" }, { "code": null, "e": 17405, "s": 17377, "text": "Permutation and Combination" }, { "code": null, "e": 17412, "s": 17405, "text": "Arrays" }, { "code": null, "e": 17422, "s": 17412, "text": "Bit Magic" }, { "code": null, "e": 17436, "s": 17422, "text": "Combinatorial" }, { "code": null, "e": 17449, "s": 17436, "text": "Mathematical" }, { "code": null, "e": 17457, "s": 17449, "text": "Strings" }, { "code": null, "e": 17473, "s": 17457, "text": "Write From Home" }, { "code": null, "e": 17480, "s": 17473, "text": "Arrays" }, { "code": null, "e": 17488, "s": 17480, "text": "Strings" }, { "code": null, "e": 17501, "s": 17488, "text": "Mathematical" }, { "code": null, "e": 17511, "s": 17501, "text": "Bit Magic" }, { "code": null, "e": 17525, "s": 17511, "text": "Combinatorial" }, { "code": null, "e": 17623, "s": 17525, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 17691, "s": 17623, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 17735, "s": 17691, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 17767, "s": 17735, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 17781, "s": 17767, "text": "Linear Search" }, { "code": null, "e": 17866, "s": 17781, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 17893, "s": 17866, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 17939, "s": 17893, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 18007, "s": 17939, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 18036, "s": 18007, "text": "Count set bits in an integer" } ]
Java - The Collection Interface
The Collection interface is the foundation upon which the collections framework is built. It declares the core methods that all collections will have. These methods are summarized in the following table. Because all collections implement Collection, familiarity with its methods is necessary for a clear understanding of the framework. Several of these methods can throw an UnsupportedOperationException. boolean add(Object obj) Adds obj to the invoking collection. Returns true if obj was added to the collection. Returns false if obj is already a member of the collection, or if the collection does not allow duplicates. boolean addAll(Collection c) Adds all the elements of c to the invoking collection. Returns true if the operation succeeds (i.e., the elements were added). Otherwise, returns false. void clear( ) Removes all elements from the invoking collection. boolean contains(Object obj) Returns true if obj is an element of the invoking collection. Otherwise, returns false. boolean containsAll(Collection c) Returns true if the invoking collection contains all elements of c. Otherwise, returns false. boolean equals(Object obj) Returns true if the invoking collection and obj are equal. Otherwise, returns false. int hashCode( ) Returns the hash code for the invoking collection. boolean isEmpty( ) Returns true if the invoking collection is empty. Otherwise, returns false. Iterator iterator( ) Returns an iterator for the invoking collection. boolean remove(Object obj) Removes one instance of obj from the invoking collection. Returns true if the element was removed. Otherwise, returns false. boolean removeAll(Collection c) Removes all elements of c from the invoking collection. Returns true if the collection changed (i.e., elements were removed). Otherwise, returns false. boolean retainAll(Collection c) Removes all elements from the invoking collection except those in c. Returns true if the collection changed (i.e., elements were removed). Otherwise, returns false. int size( ) Returns the number of elements held in the invoking collection. Object[ ] toArray( ) Returns an array that contains all the elements stored in the invoking collection. The array elements are copies of the collection elements. Object[ ] toArray(Object array[ ]) Returns an array containing only those collection elements whose type matches that of array. Following is an example to explain few methods from various class implementations of the above collection methods − import java.util.*; public class CollectionsDemo { public static void main(String[] args) { // ArrayList List a1 = new ArrayList(); a1.add("Zara"); a1.add("Mahnaz"); a1.add("Ayan"); System.out.println(" ArrayList Elements"); System.out.print("\t" + a1); // LinkedList List l1 = new LinkedList(); l1.add("Zara"); l1.add("Mahnaz"); l1.add("Ayan"); System.out.println(); System.out.println(" LinkedList Elements"); System.out.print("\t" + l1); // HashSet Set s1 = new HashSet(); s1.add("Zara"); s1.add("Mahnaz"); s1.add("Ayan"); System.out.println(); System.out.println(" Set Elements"); System.out.print("\t" + s1); // HashMap Map m1 = new HashMap(); m1.put("Zara", "8"); m1.put("Mahnaz", "31"); m1.put("Ayan", "12"); m1.put("Daisy", "14"); System.out.println(); System.out.println(" Map Elements"); System.out.print("\t" + m1); } } This will produce the following result − ArrayList Elements [Zara, Mahnaz, Ayan] LinkedList Elements [Zara, Mahnaz, Ayan] Set Elements [Ayan, Zara, Mahnaz] Map Elements {Daisy = 14, Ayan = 12, Zara = 8, Mahnaz = 31}
[ { "code": null, "e": 2715, "s": 2511, "text": "The Collection interface is the foundation upon which the collections framework is built. It declares the core methods that all collections will have. These methods are summarized in the following table." }, { "code": null, "e": 2916, "s": 2715, "text": "Because all collections implement Collection, familiarity with its methods is necessary for a clear understanding of the framework. Several of these methods can throw an UnsupportedOperationException." }, { "code": null, "e": 2940, "s": 2916, "text": "boolean add(Object obj)" }, { "code": null, "e": 3134, "s": 2940, "text": "Adds obj to the invoking collection. Returns true if obj was added to the collection. Returns false if obj is already a member of the collection, or if the collection does not allow duplicates." }, { "code": null, "e": 3163, "s": 3134, "text": "boolean addAll(Collection c)" }, { "code": null, "e": 3316, "s": 3163, "text": "Adds all the elements of c to the invoking collection. Returns true if the operation succeeds (i.e., the elements were added). Otherwise, returns false." }, { "code": null, "e": 3330, "s": 3316, "text": "void clear( )" }, { "code": null, "e": 3381, "s": 3330, "text": "Removes all elements from the invoking collection." }, { "code": null, "e": 3410, "s": 3381, "text": "boolean contains(Object obj)" }, { "code": null, "e": 3498, "s": 3410, "text": "Returns true if obj is an element of the invoking collection. Otherwise, returns false." }, { "code": null, "e": 3532, "s": 3498, "text": "boolean containsAll(Collection c)" }, { "code": null, "e": 3626, "s": 3532, "text": "Returns true if the invoking collection contains all elements of c. Otherwise, returns false." }, { "code": null, "e": 3653, "s": 3626, "text": "boolean equals(Object obj)" }, { "code": null, "e": 3738, "s": 3653, "text": "Returns true if the invoking collection and obj are equal. Otherwise, returns false." }, { "code": null, "e": 3754, "s": 3738, "text": "int hashCode( )" }, { "code": null, "e": 3805, "s": 3754, "text": "Returns the hash code for the invoking collection." }, { "code": null, "e": 3824, "s": 3805, "text": "boolean isEmpty( )" }, { "code": null, "e": 3900, "s": 3824, "text": "Returns true if the invoking collection is empty. Otherwise, returns false." }, { "code": null, "e": 3921, "s": 3900, "text": "Iterator iterator( )" }, { "code": null, "e": 3970, "s": 3921, "text": "Returns an iterator for the invoking collection." }, { "code": null, "e": 3997, "s": 3970, "text": "boolean remove(Object obj)" }, { "code": null, "e": 4122, "s": 3997, "text": "Removes one instance of obj from the invoking collection. Returns true if the element was removed. Otherwise, returns false." }, { "code": null, "e": 4154, "s": 4122, "text": "boolean removeAll(Collection c)" }, { "code": null, "e": 4306, "s": 4154, "text": "Removes all elements of c from the invoking collection. Returns true if the collection changed (i.e., elements were removed). Otherwise, returns false." }, { "code": null, "e": 4338, "s": 4306, "text": "boolean retainAll(Collection c)" }, { "code": null, "e": 4503, "s": 4338, "text": "Removes all elements from the invoking collection except those in c. Returns true if the collection changed (i.e., elements were removed). Otherwise, returns false." }, { "code": null, "e": 4515, "s": 4503, "text": "int size( )" }, { "code": null, "e": 4579, "s": 4515, "text": "Returns the number of elements held in the invoking collection." }, { "code": null, "e": 4600, "s": 4579, "text": "Object[ ] toArray( )" }, { "code": null, "e": 4741, "s": 4600, "text": "Returns an array that contains all the elements stored in the invoking collection. The array elements are copies of the collection elements." }, { "code": null, "e": 4776, "s": 4741, "text": "Object[ ] toArray(Object array[ ])" }, { "code": null, "e": 4869, "s": 4776, "text": "Returns an array containing only those collection elements whose type matches that of array." }, { "code": null, "e": 4985, "s": 4869, "text": "Following is an example to explain few methods from various class implementations of the above collection methods −" }, { "code": null, "e": 6021, "s": 4985, "text": "import java.util.*;\npublic class CollectionsDemo {\n\n public static void main(String[] args) {\n // ArrayList \n List a1 = new ArrayList();\n a1.add(\"Zara\");\n a1.add(\"Mahnaz\");\n a1.add(\"Ayan\");\n System.out.println(\" ArrayList Elements\");\n System.out.print(\"\\t\" + a1);\n\n // LinkedList\n List l1 = new LinkedList();\n l1.add(\"Zara\");\n l1.add(\"Mahnaz\");\n l1.add(\"Ayan\");\n System.out.println();\n System.out.println(\" LinkedList Elements\");\n System.out.print(\"\\t\" + l1);\n\n // HashSet\n Set s1 = new HashSet(); \n s1.add(\"Zara\");\n s1.add(\"Mahnaz\");\n s1.add(\"Ayan\");\n System.out.println();\n System.out.println(\" Set Elements\");\n System.out.print(\"\\t\" + s1);\n\n // HashMap\n Map m1 = new HashMap(); \n m1.put(\"Zara\", \"8\");\n m1.put(\"Mahnaz\", \"31\");\n m1.put(\"Ayan\", \"12\");\n m1.put(\"Daisy\", \"14\");\n System.out.println();\n System.out.println(\" Map Elements\");\n System.out.print(\"\\t\" + m1);\n }\n}" }, { "code": null, "e": 6062, "s": 6021, "text": "This will produce the following result −" } ]
How to Create a Table With Multiple Foreign Keys in SQL?
26 Sep, 2021 When a non-prime attribute column in one table references the primary key and has the same column as the column of the table which is prime attribute is called a foreign key. It lays the relation between the two tables which majorly helps in the normalization of the tables. A table can have multiple foreign keys based on the requirement. In this article let us see how to create a table with multiple foreign keys in MSSQL. Syntax: column_name(non_prime) data_type REFERENCES table_name(column_name(prime) Step 1: Creating a Database We use the below command to create a database named GeeksforGeeks: Query: CREATE DATABASE GeeksforGeeks Step 2: Using the Database To use the GeeksforGeeks database use the below command: Query: USE GeeksforGeeks Step 3: Creating 3 tables. The table student_details contains two foreign keys that reference the tables student_branch_details and student_address. Query: CREATE TABLE student_details( stu_id VARCHAR(8) NOT NULL PRIMARY KEY, stu_name VARCHAR(20), stu_branch VARCHAR(20) FOREIGN KEY REFERENCES student_branch_details(stu_branch), stu_pin_code VARCHAR(6) FOREIGN KEY REFERENCES student_address(stu_pin_code) ); CREATE TABLE student_branch_details( stu_branch VARCHAR(20) PRIMARY KEY, subjects INT, credits INT ); CREATE TABLE student_address( stu_pin_code VARCHAR(6) PRIMARY KEY, stu_state VARCHAR(20), student_city VARCHAR(20) ); Output: The number and type of keys can be checked in the tables section of object explorer on the left side of the UI. Step 4: Inserting data into the Table Inserting rows into student_branch_details and student_address tables using the following SQL query: Query: INSERT INTO student_branch_details VALUES ('E.C.E',46,170), ('E.E.E',47,178), ('C.S.E',44,160) INSERT INTO student_address VALUES ('555555', 'xyz','abc'), ('666666', 'yyy','aaa'), ('777777','zzz','bbb'), ('888888','www','ccc'), ('999999','vvv','ddd') Inserting rows into student_details Query: INSERT INTO student_details VALUES ('1940001','PRATHAM','E.C.E','555555'), ('1940002','ASHOK','C.S.E','666666'), ('1940003','PAVAN KUMAR','C.S.E','777777'), ('1940004','SANTHOSH','E.C.E','888888'), ('1940005','THAMAN','E.C.E','999999'), ('1940006','HARSH','E.E.E','888888') Step 5: Verifying the inserted data Viewing the tables student_details,student_branch_details,student_address after inserting rows by using the following SQL query: Query: SELECT * FROM student_details SELECT * FROM student_branch_details SELECT * FROM student_address Output: Blogathon-2021 Picked SQL-Server Blogathon SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SQL Query to Insert Multiple Rows How to Connect Python with SQL Database? How to Import JSON Data into SQL Server? Difference Between Local Storage, Session Storage And Cookies Data Mining - Cluster Analysis How to find Nth highest salary from a table CTE in SQL SQL | ALTER (RENAME) SQL Trigger | Student Database How to Update Multiple Columns in Single Update Statement in SQL?
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Sep, 2021" }, { "code": null, "e": 368, "s": 28, "text": "When a non-prime attribute column in one table references the primary key and has the same column as the column of the table which is prime attribute is called a foreign key. It lays the relation between the two tables which majorly helps in the normalization of the tables. A table can have multiple foreign keys based on the requirement." }, { "code": null, "e": 454, "s": 368, "text": "In this article let us see how to create a table with multiple foreign keys in MSSQL." }, { "code": null, "e": 463, "s": 454, "text": " Syntax:" }, { "code": null, "e": 537, "s": 463, "text": "column_name(non_prime) data_type REFERENCES table_name(column_name(prime)" }, { "code": null, "e": 565, "s": 537, "text": "Step 1: Creating a Database" }, { "code": null, "e": 632, "s": 565, "text": "We use the below command to create a database named GeeksforGeeks:" }, { "code": null, "e": 639, "s": 632, "text": "Query:" }, { "code": null, "e": 669, "s": 639, "text": "CREATE DATABASE GeeksforGeeks" }, { "code": null, "e": 696, "s": 669, "text": "Step 2: Using the Database" }, { "code": null, "e": 753, "s": 696, "text": "To use the GeeksforGeeks database use the below command:" }, { "code": null, "e": 760, "s": 753, "text": "Query:" }, { "code": null, "e": 778, "s": 760, "text": "USE GeeksforGeeks" }, { "code": null, "e": 927, "s": 778, "text": "Step 3: Creating 3 tables. The table student_details contains two foreign keys that reference the tables student_branch_details and student_address." }, { "code": null, "e": 934, "s": 927, "text": "Query:" }, { "code": null, "e": 1430, "s": 934, "text": "CREATE TABLE student_details(\n stu_id VARCHAR(8) NOT NULL PRIMARY KEY,\n stu_name VARCHAR(20),\n stu_branch VARCHAR(20) FOREIGN KEY REFERENCES student_branch_details(stu_branch),\n stu_pin_code VARCHAR(6) FOREIGN KEY REFERENCES student_address(stu_pin_code)\n );\nCREATE TABLE student_branch_details(\n stu_branch VARCHAR(20) PRIMARY KEY,\n subjects INT,\n credits INT\n);\nCREATE TABLE student_address(\n stu_pin_code VARCHAR(6) PRIMARY KEY,\n stu_state VARCHAR(20),\n student_city VARCHAR(20)\n);" }, { "code": null, "e": 1438, "s": 1430, "text": "Output:" }, { "code": null, "e": 1550, "s": 1438, "text": "The number and type of keys can be checked in the tables section of object explorer on the left side of the UI." }, { "code": null, "e": 1590, "s": 1550, "text": "Step 4: Inserting data into the Table " }, { "code": null, "e": 1691, "s": 1590, "text": "Inserting rows into student_branch_details and student_address tables using the following SQL query:" }, { "code": null, "e": 1698, "s": 1691, "text": "Query:" }, { "code": null, "e": 1966, "s": 1698, "text": "INSERT INTO student_branch_details VALUES\n ('E.C.E',46,170),\n ('E.E.E',47,178),\n ('C.S.E',44,160)\n\nINSERT INTO student_address VALUES\n ('555555', 'xyz','abc'),\n ('666666', 'yyy','aaa'),\n ('777777','zzz','bbb'),\n ('888888','www','ccc'),\n ('999999','vvv','ddd')" }, { "code": null, "e": 2002, "s": 1966, "text": "Inserting rows into student_details" }, { "code": null, "e": 2009, "s": 2002, "text": "Query:" }, { "code": null, "e": 2283, "s": 2009, "text": "INSERT INTO student_details VALUES\n('1940001','PRATHAM','E.C.E','555555'),\n('1940002','ASHOK','C.S.E','666666'),\n('1940003','PAVAN KUMAR','C.S.E','777777'),\n('1940004','SANTHOSH','E.C.E','888888'),\n('1940005','THAMAN','E.C.E','999999'),\n('1940006','HARSH','E.E.E','888888')" }, { "code": null, "e": 2320, "s": 2283, "text": "Step 5: Verifying the inserted data " }, { "code": null, "e": 2449, "s": 2320, "text": "Viewing the tables student_details,student_branch_details,student_address after inserting rows by using the following SQL query:" }, { "code": null, "e": 2456, "s": 2449, "text": "Query:" }, { "code": null, "e": 2553, "s": 2456, "text": "SELECT * FROM student_details\nSELECT * FROM student_branch_details\nSELECT * FROM student_address" }, { "code": null, "e": 2561, "s": 2553, "text": "Output:" }, { "code": null, "e": 2576, "s": 2561, "text": "Blogathon-2021" }, { "code": null, "e": 2583, "s": 2576, "text": "Picked" }, { "code": null, "e": 2594, "s": 2583, "text": "SQL-Server" }, { "code": null, "e": 2604, "s": 2594, "text": "Blogathon" }, { "code": null, "e": 2608, "s": 2604, "text": "SQL" }, { "code": null, "e": 2612, "s": 2608, "text": "SQL" }, { "code": null, "e": 2710, "s": 2612, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2744, "s": 2710, "text": "SQL Query to Insert Multiple Rows" }, { "code": null, "e": 2785, "s": 2744, "text": "How to Connect Python with SQL Database?" }, { "code": null, "e": 2826, "s": 2785, "text": "How to Import JSON Data into SQL Server?" }, { "code": null, "e": 2888, "s": 2826, "text": "Difference Between Local Storage, Session Storage And Cookies" }, { "code": null, "e": 2919, "s": 2888, "text": "Data Mining - Cluster Analysis" }, { "code": null, "e": 2963, "s": 2919, "text": "How to find Nth highest salary from a table" }, { "code": null, "e": 2974, "s": 2963, "text": "CTE in SQL" }, { "code": null, "e": 2995, "s": 2974, "text": "SQL | ALTER (RENAME)" }, { "code": null, "e": 3026, "s": 2995, "text": "SQL Trigger | Student Database" } ]
Matplotlib.figure.Figure.add_gridspec() in Python
30 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements. The add_gridspec() method figure module of matplotlib library is used to get the GridSpec that has this figure as a parent. Syntax: add_gridspec(self, nrows, ncols, **kwargs) Parameters: This accept the following parameters that are described below: nrows : This parameter is the number of rows in grid. ncols : This parameter is the number or columns in grid. Returns: This method return the GridSpec. Below examples illustrate the matplotlib.figure.Figure.add_gridspec() function in matplotlib.figure: Example 1: # Implementation of matplotlib functionimport matplotlibimport matplotlib.pyplot as pltimport matplotlib.gridspec as gridspec fig = plt.figure(constrained_layout = True)gs = fig.add_gridspec(3, 3)ax = fig.add_subplot(gs[0, :])ax.set_title('gs[0, :]')ax2 = fig.add_subplot(gs[1, :-1])ax2.set_title('gs[1, :-1]') fig.suptitle('matplotlib.figure.Figure.add_gridspec() \function Example\n\n', fontweight ="bold") plt.show() Output: Example 2: # Implementation of matplotlib functionimport matplotlibimport matplotlib.pyplot as pltimport matplotlib.gridspec as gridspec fig = plt.figure()gs = fig.add_gridspec(2, 2)ax1 = fig.add_subplot(gs[0, 0])ax2 = fig.add_subplot(gs[1, 0])ax3 = fig.add_subplot(gs[:, 1]) fig.suptitle('matplotlib.figure.Figure.add_gridspec()\ function Example\n\n', fontweight ="bold") plt.show() Output: Python-matplotlib 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 | os.path.join() method Python OOPs Concepts How to drop one or multiple columns in Pandas Dataframe Introduction To PYTHON How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Apr, 2020" }, { "code": null, "e": 339, "s": 28, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements." }, { "code": null, "e": 463, "s": 339, "text": "The add_gridspec() method figure module of matplotlib library is used to get the GridSpec that has this figure as a parent." }, { "code": null, "e": 514, "s": 463, "text": "Syntax: add_gridspec(self, nrows, ncols, **kwargs)" }, { "code": null, "e": 589, "s": 514, "text": "Parameters: This accept the following parameters that are described below:" }, { "code": null, "e": 643, "s": 589, "text": "nrows : This parameter is the number of rows in grid." }, { "code": null, "e": 700, "s": 643, "text": "ncols : This parameter is the number or columns in grid." }, { "code": null, "e": 742, "s": 700, "text": "Returns: This method return the GridSpec." }, { "code": null, "e": 843, "s": 742, "text": "Below examples illustrate the matplotlib.figure.Figure.add_gridspec() function in matplotlib.figure:" }, { "code": null, "e": 854, "s": 843, "text": "Example 1:" }, { "code": "# Implementation of matplotlib functionimport matplotlibimport matplotlib.pyplot as pltimport matplotlib.gridspec as gridspec fig = plt.figure(constrained_layout = True)gs = fig.add_gridspec(3, 3)ax = fig.add_subplot(gs[0, :])ax.set_title('gs[0, :]')ax2 = fig.add_subplot(gs[1, :-1])ax2.set_title('gs[1, :-1]') fig.suptitle('matplotlib.figure.Figure.add_gridspec() \\function Example\\n\\n', fontweight =\"bold\") plt.show()", "e": 1281, "s": 854, "text": null }, { "code": null, "e": 1289, "s": 1281, "text": "Output:" }, { "code": null, "e": 1300, "s": 1289, "text": "Example 2:" }, { "code": "# Implementation of matplotlib functionimport matplotlibimport matplotlib.pyplot as pltimport matplotlib.gridspec as gridspec fig = plt.figure()gs = fig.add_gridspec(2, 2)ax1 = fig.add_subplot(gs[0, 0])ax2 = fig.add_subplot(gs[1, 0])ax3 = fig.add_subplot(gs[:, 1]) fig.suptitle('matplotlib.figure.Figure.add_gridspec()\\ function Example\\n\\n', fontweight =\"bold\") plt.show()", "e": 1681, "s": 1300, "text": null }, { "code": null, "e": 1689, "s": 1681, "text": "Output:" }, { "code": null, "e": 1707, "s": 1689, "text": "Python-matplotlib" }, { "code": null, "e": 1714, "s": 1707, "text": "Python" }, { "code": null, "e": 1812, "s": 1714, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1844, "s": 1812, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1871, "s": 1844, "text": "Python Classes and Objects" }, { "code": null, "e": 1902, "s": 1871, "text": "Python | os.path.join() method" }, { "code": null, "e": 1923, "s": 1902, "text": "Python OOPs Concepts" }, { "code": null, "e": 1979, "s": 1923, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2002, "s": 1979, "text": "Introduction To PYTHON" }, { "code": null, "e": 2044, "s": 2002, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2086, "s": 2044, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2125, "s": 2086, "text": "Python | datetime.timedelta() function" } ]
Python | Adding markers to volcano locations using folium package
10 Sep, 2021 Python is a multipurpose language and its utilities extend to more than just normal programming. It can be used to develop games, crawl the internet, or develop deep learning models. We’ll be using the Python library named folium (with Pandas) along with the Volcanoes_USA dataset (which contains the necessary data used in this project). The script will create a saved web page. Upon opening it the user will be directed to google maps, where the locations of the volcanoes will be marked, their colors set according to the elevation. Setup: First, Install libraries like folium, pandas, and the dataset mention above: pip3 install folium pip3 install pandas Now, you need to download the required dataset, Volcanoes_USA.txt. Remember to download this in the same directory in which you will save the Python script. Also, do remove the apostrophes “‘” from the values of the ‘NAME’ column in the dataset, wherever present. Pre-defined functions: Mean() – A pandas function which can calculate the mean of the values of in an array/Series. Map() – Generate a base map of given width and height with either default tilesets or a custom tileset URL. Marker() – Create a simple stock Leaflet marker on the map, with optional popup text or Vincent visualization. User defined functions : color() – used to assign color to the marker according to the elevation of volcano. Below is the implementation: Python3 #import the necessary packagesimport foliumimport pandas as pd # importing the dataset as a csv file,# and storing it as a dataframe in 'df'df=pd.read_csv('Volcanoes.txt') # calculating the mean of the latitudes# and longitudes of the locations of volcanoeslatmean=df['LAT'].mean()lonmean=df['LON'].mean() # Creating a map object using Map() function.# Location parameter takes latitudes and# longitudes as starting location.# (Map will be centered at those co-ordinates)map5 = folium.Map(location=[latmean,lonmean], zoom_start=6,tiles = 'Mapbox bright') # Function to change the marker color# according to the elevation of volcanodef color(elev): if elev in range(0,1000): col = 'green' elif elev in range(1001,1999): col = 'blue' elif elev in range(2000,2999): col = 'orange' else: col='red' return col # Iterating over the LAT,LON,NAME and# ELEV columns simultaneously using zip()for lat,lan,name,elev in zip(df['LAT'],df['LON'],df['NAME'],df['ELEV']): # Marker() takes location coordinates # as a list as an argument folium.Marker(location=[lat,lan],popup = name, icon= folium.Icon(color=color(elev), icon_color='yellow',icon = 'cloud')).add_to(map5) # Save the file created aboveprint(map5.save('test7.html')) Output: Reference: http://python-visualization.github.io/folium/docs-v0.5.0/modules.html surindertarika1234 python-utility Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python 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": 52, "s": 24, "text": "\n10 Sep, 2021" }, { "code": null, "e": 588, "s": 52, "text": "Python is a multipurpose language and its utilities extend to more than just normal programming. It can be used to develop games, crawl the internet, or develop deep learning models. We’ll be using the Python library named folium (with Pandas) along with the Volcanoes_USA dataset (which contains the necessary data used in this project). The script will create a saved web page. Upon opening it the user will be directed to google maps, where the locations of the volcanoes will be marked, their colors set according to the elevation." }, { "code": null, "e": 673, "s": 588, "text": "Setup: First, Install libraries like folium, pandas, and the dataset mention above: " }, { "code": null, "e": 713, "s": 673, "text": "pip3 install folium\npip3 install pandas" }, { "code": null, "e": 977, "s": 713, "text": "Now, you need to download the required dataset, Volcanoes_USA.txt. Remember to download this in the same directory in which you will save the Python script. Also, do remove the apostrophes “‘” from the values of the ‘NAME’ column in the dataset, wherever present." }, { "code": null, "e": 1002, "s": 977, "text": "Pre-defined functions: " }, { "code": null, "e": 1096, "s": 1002, "text": "Mean() – A pandas function which can calculate the mean of the values of in an array/Series. " }, { "code": null, "e": 1205, "s": 1096, "text": "Map() – Generate a base map of given width and height with either default tilesets or a custom tileset URL. " }, { "code": null, "e": 1317, "s": 1205, "text": "Marker() – Create a simple stock Leaflet marker on the map, with optional popup text or Vincent visualization. " }, { "code": null, "e": 1343, "s": 1317, "text": "User defined functions : " }, { "code": null, "e": 1428, "s": 1343, "text": "color() – used to assign color to the marker according to the elevation of volcano. " }, { "code": null, "e": 1458, "s": 1428, "text": "Below is the implementation: " }, { "code": null, "e": 1466, "s": 1458, "text": "Python3" }, { "code": "#import the necessary packagesimport foliumimport pandas as pd # importing the dataset as a csv file,# and storing it as a dataframe in 'df'df=pd.read_csv('Volcanoes.txt') # calculating the mean of the latitudes# and longitudes of the locations of volcanoeslatmean=df['LAT'].mean()lonmean=df['LON'].mean() # Creating a map object using Map() function.# Location parameter takes latitudes and# longitudes as starting location.# (Map will be centered at those co-ordinates)map5 = folium.Map(location=[latmean,lonmean], zoom_start=6,tiles = 'Mapbox bright') # Function to change the marker color# according to the elevation of volcanodef color(elev): if elev in range(0,1000): col = 'green' elif elev in range(1001,1999): col = 'blue' elif elev in range(2000,2999): col = 'orange' else: col='red' return col # Iterating over the LAT,LON,NAME and# ELEV columns simultaneously using zip()for lat,lan,name,elev in zip(df['LAT'],df['LON'],df['NAME'],df['ELEV']): # Marker() takes location coordinates # as a list as an argument folium.Marker(location=[lat,lan],popup = name, icon= folium.Icon(color=color(elev), icon_color='yellow',icon = 'cloud')).add_to(map5) # Save the file created aboveprint(map5.save('test7.html'))", "e": 2804, "s": 1466, "text": null }, { "code": null, "e": 2813, "s": 2804, "text": "Output: " }, { "code": null, "e": 2895, "s": 2813, "text": "Reference: http://python-visualization.github.io/folium/docs-v0.5.0/modules.html " }, { "code": null, "e": 2914, "s": 2895, "text": "surindertarika1234" }, { "code": null, "e": 2929, "s": 2914, "text": "python-utility" }, { "code": null, "e": 2936, "s": 2929, "text": "Python" }, { "code": null, "e": 2952, "s": 2936, "text": "Python Programs" }, { "code": null, "e": 3050, "s": 2952, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3068, "s": 3050, "text": "Python Dictionary" }, { "code": null, "e": 3110, "s": 3068, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3132, "s": 3110, "text": "Enumerate() in Python" }, { "code": null, "e": 3167, "s": 3132, "text": "Read a file line by line in Python" }, { "code": null, "e": 3193, "s": 3167, "text": "Python String | replace()" }, { "code": null, "e": 3236, "s": 3193, "text": "Python program to convert a list to string" }, { "code": null, "e": 3258, "s": 3236, "text": "Defaultdict in Python" }, { "code": null, "e": 3297, "s": 3258, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 3335, "s": 3297, "text": "Python | Convert a list to dictionary" } ]
Accessing Values of Tuples in Python
To access values in tuple, use the square brackets for slicing along with the index or indices to obtain value available at that index. Live Demo #!/usr/bin/python tup1 = ('physics', 'chemistry', 1997, 2000); tup2 = (1, 2, 3, 4, 5, 6, 7 ); print "tup1[0]: ", tup1[0]; print "tup2[1:5]: ", tup2[1:5]; When the above code is executed, it produces the following result − tup1[0]: physics tup2[1:5]: [2, 3, 4, 5]
[ { "code": null, "e": 1198, "s": 1062, "text": "To access values in tuple, use the square brackets for slicing along with the index or indices to obtain value available at that index." }, { "code": null, "e": 1209, "s": 1198, "text": " Live Demo" }, { "code": null, "e": 1363, "s": 1209, "text": "#!/usr/bin/python\ntup1 = ('physics', 'chemistry', 1997, 2000);\ntup2 = (1, 2, 3, 4, 5, 6, 7 );\nprint \"tup1[0]: \", tup1[0];\nprint \"tup2[1:5]: \", tup2[1:5];" }, { "code": null, "e": 1431, "s": 1363, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 1472, "s": 1431, "text": "tup1[0]: physics\ntup2[1:5]: [2, 3, 4, 5]" } ]
ClassLoader in Java - GeeksforGeeks
07 Sep, 2020 The Java ClassLoader is a part of the Java Runtime Environment that dynamically loads Java classes into the Java Virtual Machine. The Java run time system does not need to know about files and file systems because of classloaders. Java classes aren’t loaded into memory all at once, but when required by an application. At this point, the Java ClassLoader is called by the JRE and these ClassLoaders load classes into memory dynamically. Types of ClassLoaders in Java Not all classes are loaded by a single ClassLoader. Depending on the type of class and the path of class, the ClassLoader that loads that particular class is decided. To know the ClassLoader that loads a class the getClassLoader() method is used. All classes are loaded based on their names and if any of these classes are not found then it returns a NoClassDefFoundError or ClassNotFoundException. A Java Classloader is of three types: BootStrap ClassLoader: A Bootstrap Classloader is a Machine code which kickstarts the operation when the JVM calls it. It is not a java class. Its job is to load the first pure Java ClassLoader. Bootstrap ClassLoader loads classes from the location rt.jar. Bootstrap ClassLoader doesn’t have any parent ClassLoaders. It is also called as the Primodial ClassLoader.Extension ClassLoader: The Extension ClassLoader is a child of Bootstrap ClassLoader and loads the extensions of core java classes from the respective JDK Extension library. It loads files from jre/lib/ext directory or any other directory pointed by the system property java.ext.dirs.System ClassLoader: An Application ClassLoader is also known as a System ClassLoader. It loads the Application type classes found in the environment variable CLASSPATH, -classpath or -cp command line option. The Application ClassLoader is a child class of Extension ClassLoader. BootStrap ClassLoader: A Bootstrap Classloader is a Machine code which kickstarts the operation when the JVM calls it. It is not a java class. Its job is to load the first pure Java ClassLoader. Bootstrap ClassLoader loads classes from the location rt.jar. Bootstrap ClassLoader doesn’t have any parent ClassLoaders. It is also called as the Primodial ClassLoader. Extension ClassLoader: The Extension ClassLoader is a child of Bootstrap ClassLoader and loads the extensions of core java classes from the respective JDK Extension library. It loads files from jre/lib/ext directory or any other directory pointed by the system property java.ext.dirs. System ClassLoader: An Application ClassLoader is also known as a System ClassLoader. It loads the Application type classes found in the environment variable CLASSPATH, -classpath or -cp command line option. The Application ClassLoader is a child class of Extension ClassLoader. Note: The ClassLoader Delegation Hierarchy Model always functions in the order Application ClassLoader->Extension ClassLoader->Bootstrap ClassLoader. The Bootstrap ClassLoader is always given the higher priority, next is Extension ClassLoader and then Application ClassLoader. Principles of functionality of a Java ClassLoader Principles of functionality are the set of rules or features on which a Java ClassLoader works. There are three principles of functionality, they are: Delegation Model: The Java Virtual Machine and the Java ClassLoader use an algorithm called the Delegation Hierarchy Algorithm to Load the classes into the Java file.The ClassLoader works based on a set of operations given by the delegation model. They are:ClassLoader always follows the Delegation Hierarchy Principle.Whenever JVM comes across a class, it checks whether that class is already loaded or not.If the Class is already loaded in the method area then the JVM proceeds with execution.If the class is not present in the method area then the JVM asks the Java ClassLoader Sub-System to load that particular class, then ClassLoader sub-system hands over the control to Application ClassLoader.Application ClassLoader then delegates the request to Extension ClassLoader and the Extension ClassLoader in turn delegates the request to Bootstrap ClassLoader.Bootstrap ClassLoader will search in the Bootstrap classpath(JDK/JRE/LIB). If the class is available then it is loaded, if not the request is delegated to Extension ClassLoader.Extension ClassLoader searches for the class in the Extension Classpath(JDK/JRE/LIB/EXT). If the class is available then it is loaded, if not the request is delegated to the Application ClassLoader.Application ClassLoader searches for the class in the Application Classpath. If the class is available then it is loaded, if not then a ClassNotFoundException exception is generated.Visibility Principle: The Visibility Principle states that a class loaded by a parent ClassLoader is visible to the child ClassLoaders but a class loaded by a child ClassLoader is not visible to the parent ClassLoaders. Suppose a class GEEKS.class has been loaded by the Extension ClassLoader, then that class is only visible to the Extension ClassLoader and Application ClassLoader but not to the Bootstrap ClassLoader. If that class is again tried to load using Bootstrap ClassLoader it gives an exception java.lang.ClassNotFoundException.Uniqueness Property: The Uniquesness Property ensures that the classes are unique and there is no repetition of classes. This also ensures that the classes loaded by parent classloaders are not loaded by the child classloaders. If the parent class loader isn’t able to find the class, only then the current instance would attempt to do so itself. Delegation Model: The Java Virtual Machine and the Java ClassLoader use an algorithm called the Delegation Hierarchy Algorithm to Load the classes into the Java file.The ClassLoader works based on a set of operations given by the delegation model. They are:ClassLoader always follows the Delegation Hierarchy Principle.Whenever JVM comes across a class, it checks whether that class is already loaded or not.If the Class is already loaded in the method area then the JVM proceeds with execution.If the class is not present in the method area then the JVM asks the Java ClassLoader Sub-System to load that particular class, then ClassLoader sub-system hands over the control to Application ClassLoader.Application ClassLoader then delegates the request to Extension ClassLoader and the Extension ClassLoader in turn delegates the request to Bootstrap ClassLoader.Bootstrap ClassLoader will search in the Bootstrap classpath(JDK/JRE/LIB). If the class is available then it is loaded, if not the request is delegated to Extension ClassLoader.Extension ClassLoader searches for the class in the Extension Classpath(JDK/JRE/LIB/EXT). If the class is available then it is loaded, if not the request is delegated to the Application ClassLoader.Application ClassLoader searches for the class in the Application Classpath. If the class is available then it is loaded, if not then a ClassNotFoundException exception is generated. The ClassLoader works based on a set of operations given by the delegation model. They are: ClassLoader always follows the Delegation Hierarchy Principle. Whenever JVM comes across a class, it checks whether that class is already loaded or not. If the Class is already loaded in the method area then the JVM proceeds with execution. If the class is not present in the method area then the JVM asks the Java ClassLoader Sub-System to load that particular class, then ClassLoader sub-system hands over the control to Application ClassLoader. Application ClassLoader then delegates the request to Extension ClassLoader and the Extension ClassLoader in turn delegates the request to Bootstrap ClassLoader. Bootstrap ClassLoader will search in the Bootstrap classpath(JDK/JRE/LIB). If the class is available then it is loaded, if not the request is delegated to Extension ClassLoader. Extension ClassLoader searches for the class in the Extension Classpath(JDK/JRE/LIB/EXT). If the class is available then it is loaded, if not the request is delegated to the Application ClassLoader. Application ClassLoader searches for the class in the Application Classpath. If the class is available then it is loaded, if not then a ClassNotFoundException exception is generated. Visibility Principle: The Visibility Principle states that a class loaded by a parent ClassLoader is visible to the child ClassLoaders but a class loaded by a child ClassLoader is not visible to the parent ClassLoaders. Suppose a class GEEKS.class has been loaded by the Extension ClassLoader, then that class is only visible to the Extension ClassLoader and Application ClassLoader but not to the Bootstrap ClassLoader. If that class is again tried to load using Bootstrap ClassLoader it gives an exception java.lang.ClassNotFoundException. Uniqueness Property: The Uniquesness Property ensures that the classes are unique and there is no repetition of classes. This also ensures that the classes loaded by parent classloaders are not loaded by the child classloaders. If the parent class loader isn’t able to find the class, only then the current instance would attempt to do so itself. Methods of Java.lang.ClassLoader After the JVM requests for the class, a few steps are to be followed in order to load a class. The Classes are loaded as per the delegation model but there are a few important Methods or Functions that play a vital role in loading a Class. loadClass(String name, boolean resolve): This method is used to load the classes which are referenced by the JVM. It takes the name of the class as a parameter. This is of type loadClass(String, boolean).defineClass(): The defineClass() method is a final method and cannot be overriden. This method is used to define a array of bytes as an instance of class. If the class is invalid then it throws ClassFormatError.findClass(String name): This method is used to find a specified class. This method only finds but doesn’t load the class.findLoadedClass(String name): This method is used to verify whether the Class referenced by the JVM was previously loaded or not.Class.forName(String name, boolean initialize, ClassLoader loader): This method is used to load the class as well as initialize the class. This method also gives the option to choose any one of the ClassLoaders. If the ClassLoader parameter is NULL then Bootstrap ClassLoader is used. loadClass(String name, boolean resolve): This method is used to load the classes which are referenced by the JVM. It takes the name of the class as a parameter. This is of type loadClass(String, boolean). defineClass(): The defineClass() method is a final method and cannot be overriden. This method is used to define a array of bytes as an instance of class. If the class is invalid then it throws ClassFormatError. findClass(String name): This method is used to find a specified class. This method only finds but doesn’t load the class. findLoadedClass(String name): This method is used to verify whether the Class referenced by the JVM was previously loaded or not. Class.forName(String name, boolean initialize, ClassLoader loader): This method is used to load the class as well as initialize the class. This method also gives the option to choose any one of the ClassLoaders. If the ClassLoader parameter is NULL then Bootstrap ClassLoader is used. Example: The following code is executed before a class is loaded: protected synchronized Class<?>loadClass(String name, boolean resolve) throws ClassNotFoundException{ Class c = findLoadedClass(name); try { if (c == NULL) { if (parent != NULL) { c = parent.loadClass(name, false); } else { c = findBootstrapClass0(name); } } catch (ClassNotFoundException e) { System.out.println(e); } }} Note: If a class has already been loaded, it returns it. Otherwise, it delegates the search for the new class to the parent class loader. If the parent class loader doesn’t find the class, loadClass() calls the method findClass() to find and load the class. The findClass() method searches for the class in the current ClassLoader if the class wasn’t found by the parent ClassLoader. brnunes bbsusheelkumar java-basics Picked Java 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 ArrayList in Java Multidimensional Arrays in Java Stack Class in Java Singleton Class in Java LinkedList in Java
[ { "code": null, "e": 23875, "s": 23847, "text": "\n07 Sep, 2020" }, { "code": null, "e": 24106, "s": 23875, "text": "The Java ClassLoader is a part of the Java Runtime Environment that dynamically loads Java classes into the Java Virtual Machine. The Java run time system does not need to know about files and file systems because of classloaders." }, { "code": null, "e": 24313, "s": 24106, "text": "Java classes aren’t loaded into memory all at once, but when required by an application. At this point, the Java ClassLoader is called by the JRE and these ClassLoaders load classes into memory dynamically." }, { "code": null, "e": 24343, "s": 24313, "text": "Types of ClassLoaders in Java" }, { "code": null, "e": 24742, "s": 24343, "text": "Not all classes are loaded by a single ClassLoader. Depending on the type of class and the path of class, the ClassLoader that loads that particular class is decided. To know the ClassLoader that loads a class the getClassLoader() method is used. All classes are loaded based on their names and if any of these classes are not found then it returns a NoClassDefFoundError or ClassNotFoundException." }, { "code": null, "e": 24780, "s": 24742, "text": "A Java Classloader is of three types:" }, { "code": null, "e": 25707, "s": 24780, "text": "BootStrap ClassLoader: A Bootstrap Classloader is a Machine code which kickstarts the operation when the JVM calls it. It is not a java class. Its job is to load the first pure Java ClassLoader. Bootstrap ClassLoader loads classes from the location rt.jar. Bootstrap ClassLoader doesn’t have any parent ClassLoaders. It is also called as the Primodial ClassLoader.Extension ClassLoader: The Extension ClassLoader is a child of Bootstrap ClassLoader and loads the extensions of core java classes from the respective JDK Extension library. It loads files from jre/lib/ext directory or any other directory pointed by the system property java.ext.dirs.System ClassLoader: An Application ClassLoader is also known as a System ClassLoader. It loads the Application type classes found in the environment variable CLASSPATH, -classpath or -cp command line option. The Application ClassLoader is a child class of Extension ClassLoader." }, { "code": null, "e": 26072, "s": 25707, "text": "BootStrap ClassLoader: A Bootstrap Classloader is a Machine code which kickstarts the operation when the JVM calls it. It is not a java class. Its job is to load the first pure Java ClassLoader. Bootstrap ClassLoader loads classes from the location rt.jar. Bootstrap ClassLoader doesn’t have any parent ClassLoaders. It is also called as the Primodial ClassLoader." }, { "code": null, "e": 26357, "s": 26072, "text": "Extension ClassLoader: The Extension ClassLoader is a child of Bootstrap ClassLoader and loads the extensions of core java classes from the respective JDK Extension library. It loads files from jre/lib/ext directory or any other directory pointed by the system property java.ext.dirs." }, { "code": null, "e": 26636, "s": 26357, "text": "System ClassLoader: An Application ClassLoader is also known as a System ClassLoader. It loads the Application type classes found in the environment variable CLASSPATH, -classpath or -cp command line option. The Application ClassLoader is a child class of Extension ClassLoader." }, { "code": null, "e": 26913, "s": 26636, "text": "Note: The ClassLoader Delegation Hierarchy Model always functions in the order Application ClassLoader->Extension ClassLoader->Bootstrap ClassLoader. The Bootstrap ClassLoader is always given the higher priority, next is Extension ClassLoader and then Application ClassLoader." }, { "code": null, "e": 26963, "s": 26913, "text": "Principles of functionality of a Java ClassLoader" }, { "code": null, "e": 27114, "s": 26963, "text": "Principles of functionality are the set of rules or features on which a Java ClassLoader works. There are three principles of functionality, they are:" }, { "code": null, "e": 29421, "s": 27114, "text": "Delegation Model: The Java Virtual Machine and the Java ClassLoader use an algorithm called the Delegation Hierarchy Algorithm to Load the classes into the Java file.The ClassLoader works based on a set of operations given by the delegation model. They are:ClassLoader always follows the Delegation Hierarchy Principle.Whenever JVM comes across a class, it checks whether that class is already loaded or not.If the Class is already loaded in the method area then the JVM proceeds with execution.If the class is not present in the method area then the JVM asks the Java ClassLoader Sub-System to load that particular class, then ClassLoader sub-system hands over the control to Application ClassLoader.Application ClassLoader then delegates the request to Extension ClassLoader and the Extension ClassLoader in turn delegates the request to Bootstrap ClassLoader.Bootstrap ClassLoader will search in the Bootstrap classpath(JDK/JRE/LIB). If the class is available then it is loaded, if not the request is delegated to Extension ClassLoader.Extension ClassLoader searches for the class in the Extension Classpath(JDK/JRE/LIB/EXT). If the class is available then it is loaded, if not the request is delegated to the Application ClassLoader.Application ClassLoader searches for the class in the Application Classpath. If the class is available then it is loaded, if not then a ClassNotFoundException exception is generated.Visibility Principle: The Visibility Principle states that a class loaded by a parent ClassLoader is visible to the child ClassLoaders but a class loaded by a child ClassLoader is not visible to the parent ClassLoaders. Suppose a class GEEKS.class has been loaded by the Extension ClassLoader, then that class is only visible to the Extension ClassLoader and Application ClassLoader but not to the Bootstrap ClassLoader. If that class is again tried to load using Bootstrap ClassLoader it gives an exception java.lang.ClassNotFoundException.Uniqueness Property: The Uniquesness Property ensures that the classes are unique and there is no repetition of classes. This also ensures that the classes loaded by parent classloaders are not loaded by the child classloaders. If the parent class loader isn’t able to find the class, only then the current instance would attempt to do so itself." }, { "code": null, "e": 30841, "s": 29421, "text": "Delegation Model: The Java Virtual Machine and the Java ClassLoader use an algorithm called the Delegation Hierarchy Algorithm to Load the classes into the Java file.The ClassLoader works based on a set of operations given by the delegation model. They are:ClassLoader always follows the Delegation Hierarchy Principle.Whenever JVM comes across a class, it checks whether that class is already loaded or not.If the Class is already loaded in the method area then the JVM proceeds with execution.If the class is not present in the method area then the JVM asks the Java ClassLoader Sub-System to load that particular class, then ClassLoader sub-system hands over the control to Application ClassLoader.Application ClassLoader then delegates the request to Extension ClassLoader and the Extension ClassLoader in turn delegates the request to Bootstrap ClassLoader.Bootstrap ClassLoader will search in the Bootstrap classpath(JDK/JRE/LIB). If the class is available then it is loaded, if not the request is delegated to Extension ClassLoader.Extension ClassLoader searches for the class in the Extension Classpath(JDK/JRE/LIB/EXT). If the class is available then it is loaded, if not the request is delegated to the Application ClassLoader.Application ClassLoader searches for the class in the Application Classpath. If the class is available then it is loaded, if not then a ClassNotFoundException exception is generated." }, { "code": null, "e": 30933, "s": 30841, "text": "The ClassLoader works based on a set of operations given by the delegation model. They are:" }, { "code": null, "e": 30996, "s": 30933, "text": "ClassLoader always follows the Delegation Hierarchy Principle." }, { "code": null, "e": 31086, "s": 30996, "text": "Whenever JVM comes across a class, it checks whether that class is already loaded or not." }, { "code": null, "e": 31174, "s": 31086, "text": "If the Class is already loaded in the method area then the JVM proceeds with execution." }, { "code": null, "e": 31381, "s": 31174, "text": "If the class is not present in the method area then the JVM asks the Java ClassLoader Sub-System to load that particular class, then ClassLoader sub-system hands over the control to Application ClassLoader." }, { "code": null, "e": 31543, "s": 31381, "text": "Application ClassLoader then delegates the request to Extension ClassLoader and the Extension ClassLoader in turn delegates the request to Bootstrap ClassLoader." }, { "code": null, "e": 31721, "s": 31543, "text": "Bootstrap ClassLoader will search in the Bootstrap classpath(JDK/JRE/LIB). If the class is available then it is loaded, if not the request is delegated to Extension ClassLoader." }, { "code": null, "e": 31920, "s": 31721, "text": "Extension ClassLoader searches for the class in the Extension Classpath(JDK/JRE/LIB/EXT). If the class is available then it is loaded, if not the request is delegated to the Application ClassLoader." }, { "code": null, "e": 32103, "s": 31920, "text": "Application ClassLoader searches for the class in the Application Classpath. If the class is available then it is loaded, if not then a ClassNotFoundException exception is generated." }, { "code": null, "e": 32645, "s": 32103, "text": "Visibility Principle: The Visibility Principle states that a class loaded by a parent ClassLoader is visible to the child ClassLoaders but a class loaded by a child ClassLoader is not visible to the parent ClassLoaders. Suppose a class GEEKS.class has been loaded by the Extension ClassLoader, then that class is only visible to the Extension ClassLoader and Application ClassLoader but not to the Bootstrap ClassLoader. If that class is again tried to load using Bootstrap ClassLoader it gives an exception java.lang.ClassNotFoundException." }, { "code": null, "e": 32992, "s": 32645, "text": "Uniqueness Property: The Uniquesness Property ensures that the classes are unique and there is no repetition of classes. This also ensures that the classes loaded by parent classloaders are not loaded by the child classloaders. If the parent class loader isn’t able to find the class, only then the current instance would attempt to do so itself." }, { "code": null, "e": 33025, "s": 32992, "text": "Methods of Java.lang.ClassLoader" }, { "code": null, "e": 33265, "s": 33025, "text": "After the JVM requests for the class, a few steps are to be followed in order to load a class. The Classes are loaded as per the delegation model but there are a few important Methods or Functions that play a vital role in loading a Class." }, { "code": null, "e": 34215, "s": 33265, "text": "loadClass(String name, boolean resolve): This method is used to load the classes which are referenced by the JVM. It takes the name of the class as a parameter. This is of type loadClass(String, boolean).defineClass(): The defineClass() method is a final method and cannot be overriden. This method is used to define a array of bytes as an instance of class. If the class is invalid then it throws ClassFormatError.findClass(String name): This method is used to find a specified class. This method only finds but doesn’t load the class.findLoadedClass(String name): This method is used to verify whether the Class referenced by the JVM was previously loaded or not.Class.forName(String name, boolean initialize, ClassLoader loader): This method is used to load the class as well as initialize the class. This method also gives the option to choose any one of the ClassLoaders. If the ClassLoader parameter is NULL then Bootstrap ClassLoader is used." }, { "code": null, "e": 34420, "s": 34215, "text": "loadClass(String name, boolean resolve): This method is used to load the classes which are referenced by the JVM. It takes the name of the class as a parameter. This is of type loadClass(String, boolean)." }, { "code": null, "e": 34632, "s": 34420, "text": "defineClass(): The defineClass() method is a final method and cannot be overriden. This method is used to define a array of bytes as an instance of class. If the class is invalid then it throws ClassFormatError." }, { "code": null, "e": 34754, "s": 34632, "text": "findClass(String name): This method is used to find a specified class. This method only finds but doesn’t load the class." }, { "code": null, "e": 34884, "s": 34754, "text": "findLoadedClass(String name): This method is used to verify whether the Class referenced by the JVM was previously loaded or not." }, { "code": null, "e": 35169, "s": 34884, "text": "Class.forName(String name, boolean initialize, ClassLoader loader): This method is used to load the class as well as initialize the class. This method also gives the option to choose any one of the ClassLoaders. If the ClassLoader parameter is NULL then Bootstrap ClassLoader is used." }, { "code": null, "e": 35235, "s": 35169, "text": "Example: The following code is executed before a class is loaded:" }, { "code": "protected synchronized Class<?>loadClass(String name, boolean resolve) throws ClassNotFoundException{ Class c = findLoadedClass(name); try { if (c == NULL) { if (parent != NULL) { c = parent.loadClass(name, false); } else { c = findBootstrapClass0(name); } } catch (ClassNotFoundException e) { System.out.println(e); } }}", "e": 35689, "s": 35235, "text": null }, { "code": null, "e": 36073, "s": 35689, "text": "Note: If a class has already been loaded, it returns it. Otherwise, it delegates the search for the new class to the parent class loader. If the parent class loader doesn’t find the class, loadClass() calls the method findClass() to find and load the class. The findClass() method searches for the class in the current ClassLoader if the class wasn’t found by the parent ClassLoader." }, { "code": null, "e": 36081, "s": 36073, "text": "brnunes" }, { "code": null, "e": 36096, "s": 36081, "text": "bbsusheelkumar" }, { "code": null, "e": 36108, "s": 36096, "text": "java-basics" }, { "code": null, "e": 36115, "s": 36108, "text": "Picked" }, { "code": null, "e": 36120, "s": 36115, "text": "Java" }, { "code": null, "e": 36125, "s": 36120, "text": "Java" }, { "code": null, "e": 36223, "s": 36125, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36232, "s": 36223, "text": "Comments" }, { "code": null, "e": 36245, "s": 36232, "text": "Old Comments" }, { "code": null, "e": 36296, "s": 36245, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 36326, "s": 36296, "text": "HashMap in Java with Examples" }, { "code": null, "e": 36357, "s": 36326, "text": "How to iterate any Map in Java" }, { "code": null, "e": 36376, "s": 36357, "text": "Interfaces in Java" }, { "code": null, "e": 36408, "s": 36376, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 36426, "s": 36408, "text": "ArrayList in Java" }, { "code": null, "e": 36458, "s": 36426, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 36478, "s": 36458, "text": "Stack Class in Java" }, { "code": null, "e": 36502, "s": 36478, "text": "Singleton Class in Java" } ]
Java Program to Return the Largest Element in a List - GeeksforGeeks
04 Jan, 2021 Given a List, find the largest element in it. There are multiple approaches to tackle this problem like iterating through the List or using various inbuilt functions. Input : List = [5, 3, 234, 114, 154] Output : 234 Input : List = {10, 20, 4} Output : 20 Approach 1: Using ForEach Loop Create List object and store multiple elements in it.Create one variable and initialize it with Integer.MAX_VALUE.Start iterating through the List using for each loop and compare each element with the variable.If the current element is greater than variable then update the variable.At the end of the iteration, print the variable. Create List object and store multiple elements in it. Create one variable and initialize it with Integer.MAX_VALUE. Start iterating through the List using for each loop and compare each element with the variable. If the current element is greater than variable then update the variable. At the end of the iteration, print the variable. Below is the implementation of the above approach: Java // Java Program to Return the Largest Element in a Listimport java.util.Arrays;import java.util.List; public class Test { public static void main(String[] args) { // List input List<Integer> arrayList = Arrays.asList(5, 3, 15, 234, 114, 1540); // Create maxValue variable and initialize with 0 int maxValue = 0; // Check maximum element using for loop for (Integer integer : arrayList) { if (integer > maxValue) maxValue = integer; } System.out.println("The maximum value is " + maxValue); }} The maximum value is 1540 Approach 2: Using Iterators Create List object and store multiple elements in it.Create one variable and initialize it with Integer.MAX_VALUE.Start iterating through the List using List iterator and compare each element with the variable.If the current element is greater than variable then update the variable.At the end of the iteration, print the variable. Create List object and store multiple elements in it. Create one variable and initialize it with Integer.MAX_VALUE. Start iterating through the List using List iterator and compare each element with the variable. If the current element is greater than variable then update the variable. At the end of the iteration, print the variable. Below is the implementation of the above approach: Java // Java Program to Return the Largest Element in a Listimport java.util.Arrays;import java.util.Iterator;import java.util.List; public class Test { public static void main(String[] args) { // List as input List<Integer> arrayList = Arrays.asList(5, 3, 15, 234, 114, 1540); // List iterator Iterator listIterator = arrayList.iterator(); // Create maxValue variable and initialize with 0 Integer maxValue = 0; // Iterate list while (listIterator.hasNext()) { Integer integer = (Integer)listIterator.next(); // If value is greater then update maxValue if (integer > maxValue) maxValue = integer; } System.out.println("The maximum value is " + maxValue); }} The maximum value is 1540 Approach 3: Using Indexing Create List object and store multiple elements in it.Create one variable and initialize it with Integer.MAX_VALUE.Start iterating through the List and compare each element with the variable.If the current element is greater than variable then update the variable.At the end of the iteration, print the variable. Create List object and store multiple elements in it. Create one variable and initialize it with Integer.MAX_VALUE. Start iterating through the List and compare each element with the variable. If the current element is greater than variable then update the variable. At the end of the iteration, print the variable. Below is the implementation of the above approach: Java // Java Program to Return the Largest Element in a Listimport java.util.Arrays;import java.util.List; public class Test { public static void main(String[] args) { // List as input List<Integer> arrayList = Arrays.asList(5, 3, 15, 234, 114, 1540); // Create maxValue variable and initialize with 0 Integer maxValue = 0; // Iterate List using for each loop for (int i = 0; i < arrayList.size(); i++) { // If element is greater the update maxValue if (arrayList.get(i) > maxValue) maxValue = arrayList.get(i); } System.out.println("The maximum value is " + maxValue); }} The maximum value is 1540 Approach 4: Using JDK 8 Java // create maxValue variable and initialize with 0import java.util.Arrays;import java.util.List; public class Test { public static void main(String[] args) { // List as input List<Integer> arrayList = Arrays.asList(5, 3, 15, 234, 114, 1540); // Initialize with inbuilt Max function int maxValue = arrayList.stream() .max(Integer::compareTo) .get(); System.out.println("The maximum value is " + maxValue); }} The maximum value is 1540 java-list Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Functional Interfaces in Java Stream In Java Constructors in Java Different ways of Reading a text file in Java Exceptions in Java Convert a String to Character array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java?
[ { "code": null, "e": 23557, "s": 23529, "text": "\n04 Jan, 2021" }, { "code": null, "e": 23724, "s": 23557, "text": "Given a List, find the largest element in it. There are multiple approaches to tackle this problem like iterating through the List or using various inbuilt functions." }, { "code": null, "e": 23816, "s": 23724, "text": "Input : List = [5, 3, 234, 114, 154]\nOutput : 234\n\nInput : List = {10, 20, 4}\nOutput : 20" }, { "code": null, "e": 23847, "s": 23816, "text": "Approach 1: Using ForEach Loop" }, { "code": null, "e": 24179, "s": 23847, "text": "Create List object and store multiple elements in it.Create one variable and initialize it with Integer.MAX_VALUE.Start iterating through the List using for each loop and compare each element with the variable.If the current element is greater than variable then update the variable.At the end of the iteration, print the variable." }, { "code": null, "e": 24233, "s": 24179, "text": "Create List object and store multiple elements in it." }, { "code": null, "e": 24295, "s": 24233, "text": "Create one variable and initialize it with Integer.MAX_VALUE." }, { "code": null, "e": 24392, "s": 24295, "text": "Start iterating through the List using for each loop and compare each element with the variable." }, { "code": null, "e": 24466, "s": 24392, "text": "If the current element is greater than variable then update the variable." }, { "code": null, "e": 24515, "s": 24466, "text": "At the end of the iteration, print the variable." }, { "code": null, "e": 24566, "s": 24515, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 24571, "s": 24566, "text": "Java" }, { "code": "// Java Program to Return the Largest Element in a Listimport java.util.Arrays;import java.util.List; public class Test { public static void main(String[] args) { // List input List<Integer> arrayList = Arrays.asList(5, 3, 15, 234, 114, 1540); // Create maxValue variable and initialize with 0 int maxValue = 0; // Check maximum element using for loop for (Integer integer : arrayList) { if (integer > maxValue) maxValue = integer; } System.out.println(\"The maximum value is \" + maxValue); }}", "e": 25199, "s": 24571, "text": null }, { "code": null, "e": 25225, "s": 25199, "text": "The maximum value is 1540" }, { "code": null, "e": 25253, "s": 25225, "text": "Approach 2: Using Iterators" }, { "code": null, "e": 25585, "s": 25253, "text": "Create List object and store multiple elements in it.Create one variable and initialize it with Integer.MAX_VALUE.Start iterating through the List using List iterator and compare each element with the variable.If the current element is greater than variable then update the variable.At the end of the iteration, print the variable." }, { "code": null, "e": 25639, "s": 25585, "text": "Create List object and store multiple elements in it." }, { "code": null, "e": 25701, "s": 25639, "text": "Create one variable and initialize it with Integer.MAX_VALUE." }, { "code": null, "e": 25798, "s": 25701, "text": "Start iterating through the List using List iterator and compare each element with the variable." }, { "code": null, "e": 25872, "s": 25798, "text": "If the current element is greater than variable then update the variable." }, { "code": null, "e": 25921, "s": 25872, "text": "At the end of the iteration, print the variable." }, { "code": null, "e": 25972, "s": 25921, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 25977, "s": 25972, "text": "Java" }, { "code": "// Java Program to Return the Largest Element in a Listimport java.util.Arrays;import java.util.Iterator;import java.util.List; public class Test { public static void main(String[] args) { // List as input List<Integer> arrayList = Arrays.asList(5, 3, 15, 234, 114, 1540); // List iterator Iterator listIterator = arrayList.iterator(); // Create maxValue variable and initialize with 0 Integer maxValue = 0; // Iterate list while (listIterator.hasNext()) { Integer integer = (Integer)listIterator.next(); // If value is greater then update maxValue if (integer > maxValue) maxValue = integer; } System.out.println(\"The maximum value is \" + maxValue); }}", "e": 26805, "s": 25977, "text": null }, { "code": null, "e": 26832, "s": 26805, "text": "The maximum value is 1540" }, { "code": null, "e": 26859, "s": 26832, "text": "Approach 3: Using Indexing" }, { "code": null, "e": 27171, "s": 26859, "text": "Create List object and store multiple elements in it.Create one variable and initialize it with Integer.MAX_VALUE.Start iterating through the List and compare each element with the variable.If the current element is greater than variable then update the variable.At the end of the iteration, print the variable." }, { "code": null, "e": 27225, "s": 27171, "text": "Create List object and store multiple elements in it." }, { "code": null, "e": 27287, "s": 27225, "text": "Create one variable and initialize it with Integer.MAX_VALUE." }, { "code": null, "e": 27364, "s": 27287, "text": "Start iterating through the List and compare each element with the variable." }, { "code": null, "e": 27438, "s": 27364, "text": "If the current element is greater than variable then update the variable." }, { "code": null, "e": 27487, "s": 27438, "text": "At the end of the iteration, print the variable." }, { "code": null, "e": 27538, "s": 27487, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27543, "s": 27538, "text": "Java" }, { "code": "// Java Program to Return the Largest Element in a Listimport java.util.Arrays;import java.util.List; public class Test { public static void main(String[] args) { // List as input List<Integer> arrayList = Arrays.asList(5, 3, 15, 234, 114, 1540); // Create maxValue variable and initialize with 0 Integer maxValue = 0; // Iterate List using for each loop for (int i = 0; i < arrayList.size(); i++) { // If element is greater the update maxValue if (arrayList.get(i) > maxValue) maxValue = arrayList.get(i); } System.out.println(\"The maximum value is \" + maxValue); }}", "e": 28261, "s": 27543, "text": null }, { "code": null, "e": 28287, "s": 28261, "text": "The maximum value is 1540" }, { "code": null, "e": 28311, "s": 28287, "text": "Approach 4: Using JDK 8" }, { "code": null, "e": 28316, "s": 28311, "text": "Java" }, { "code": "// create maxValue variable and initialize with 0import java.util.Arrays;import java.util.List; public class Test { public static void main(String[] args) { // List as input List<Integer> arrayList = Arrays.asList(5, 3, 15, 234, 114, 1540); // Initialize with inbuilt Max function int maxValue = arrayList.stream() .max(Integer::compareTo) .get(); System.out.println(\"The maximum value is \" + maxValue); }}", "e": 28861, "s": 28316, "text": null }, { "code": null, "e": 28887, "s": 28861, "text": "The maximum value is 1540" }, { "code": null, "e": 28897, "s": 28887, "text": "java-list" }, { "code": null, "e": 28904, "s": 28897, "text": "Picked" }, { "code": null, "e": 28909, "s": 28904, "text": "Java" }, { "code": null, "e": 28923, "s": 28909, "text": "Java Programs" }, { "code": null, "e": 28928, "s": 28923, "text": "Java" }, { "code": null, "e": 29026, "s": 28928, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29035, "s": 29026, "text": "Comments" }, { "code": null, "e": 29048, "s": 29035, "text": "Old Comments" }, { "code": null, "e": 29078, "s": 29048, "text": "Functional Interfaces in Java" }, { "code": null, "e": 29093, "s": 29078, "text": "Stream In Java" }, { "code": null, "e": 29114, "s": 29093, "text": "Constructors in Java" }, { "code": null, "e": 29160, "s": 29114, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 29179, "s": 29160, "text": "Exceptions in Java" }, { "code": null, "e": 29223, "s": 29179, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 29249, "s": 29223, "text": "Java Programming Examples" }, { "code": null, "e": 29283, "s": 29249, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 29330, "s": 29283, "text": "Implementing a Linked List in Java using Class" } ]
Data Science For Cycling — How To Read GPX Strava Routes With Python | by Dario Radečić | Towards Data Science
I love cycling, and I love using Strava to keep track of my training activities. As a data nerd, I’m a bit disappointed with their workout analysis. Sure, you can analyze speed, power, cadence, heart rate, and whatnot — depending on the sensors you have available — but what I really miss is a deep gradient analysis. Now, a gradient in data science and cycling don’t necessarily represent the same thing. In cycling, it’s basically the slope of the surface you’re riding on. Being a tall and somewhat heavy rider I find hills challenging, so a deeper gradient analysis would be helpful. For example, I’d like to see how much distance I’ve covered between 3 and 5 percent grade, how much was above 10, and everything in between. You get the point. Strava doesn’t offer that functionality, so I decided to do the calculations from scratch using my Python skills. Join me in a 6 article mini-series that will kick of with a crash course in GPX file format and end in a dashboard that displays your training data in more depth than Strava. Don’t feel like reading? Watch my video instead: You can download the source code on GitHub. Strava lets you export your workouts and routes in GPX file format. Put simply, GPX stands for GPS Exchange Format, and it’s nothing but a text file with geographical information, such as latitude, longitude, elevations, tracks, waypoints, and so on. An exported Strava route GPX file has many points taken at different times, each containing latitude, longitude, and elevation. In simple terms, you know exactly where you were and what was your altitude. This is essential for calculating gradients and gradient ranges, which we’ll do in a couple of articles. If you’re following along, head over to Strava and download any of your saved routes (Export GPX button): Creating routes requires a paid Strava subscription, so for safety concerns I won’t share my GPX files with you. Use any GPX file from your routes or the training log. If you’re not using Strava, simply find a sample GPX file online, it should still work. Got the GPX file ready? Awesome — let’s see how to read it with Python next. You’ll need a dedicated gpxpy package to read GPX with Python. Install it with Pip: pip install gpxpy You can now launch Jupyter or any other code editor to get started. First things first, let’s get the library imports out of the way: Use Python’s context manager syntax to read and parse a GPX file: Please note you’ll have to change the path to match your system and GPX file name. If everything went well, you should have the file now available in Python. But what’s inside? Let’s see: It’s a specific GPX object with the track name and segment, where each segment contains data points (latitude, longitude, and elevation). We’ll dive deeper into these in the following section, but first, let’s explore a couple of useful functions. For example, you can extract the total number of data points in a GPX file: There are 835 points in total, each containing latitude, longitude, and elevation data. That will come useful later. You can also get the altitude range: In plain English, this means that the lowest point of the ride is 113,96 meters above sea level, while the highest is at 239,16 meters. You can also extract the total meters of elevation gained and lost: My route represents a roundtrip, so it’s expected to see identical or almost identical values. Lastly, you can display the contents of your GPX file in XML format: It’s not super-readable, but it might come in handy if you have an XML processing pipeline. And that does it for the basics. Next, you’ll see how to extract individual data points and convert them into a more readable format — Pandas DataFrame. You can check how many tracks your GPX file has by running len(gpx.tracks). Mine has only one, and I can access it with Python’s list indexing notation: We don’t care for the name of the track, as it’s arbitrary in this case. What we do care about are the segments. As with tracks, my GPX file has only one segment on this track. Here’s how to access it: And now you can access individual data points by accessing the points array. Here are the first ten for my route: That’s all we need to have some fun. You’ll now see how to extract individual data points from the GPX file: It’s not the prettiest code you’ve ever seen, but gets the job done. Let’s print the first three entries to verify we did everything correctly: Do you know what’s extra handy about a list of dictionaries? You can convert it to a Pandas DataFrame in a heartbeat: You have to admit — that was pretty easy! We’ll need this dataset in the following articles, so let’s dump it into a CSV file: That’s all for the basic analysis and preprocessing we’ll do today. I’ll also show you how to visualize this dataset with Matplotlib — just to see if we’re on the right track. We’ll work on route visualization with Python and Folium in the following article, but today I want to show you how to make a basic visualization with Matplotlib. You won’t see the map, sure, but the location points should resemble the route from Image 1. Hint: don’t go too wide with the figure size, as it would make the map look weird. Copy the following code to visualize the route: And who would tell — it’s identical to what we had in Image 1, not taking the obvious into account. You’ll learn all about map and route visualization in the following article. And there you have it — you’ve successfully exported a GPX route/training file from Strava, parsed it with Python, and extracted key characteristics like latitude, longitude, and elevation. It’s just the tip of the iceberg, and you can expect to learn more applications of programming and data science in cycling in the upcoming articles. Here’s a brief overview to get you motivated — I’ll add the URLs as I release the articles: Article 1: Load and analyze GPX files from Strava Article 2: Visualize GPX files from Strava with Folium — circle markers and polygon lines Article 3: Calculate elevation difference and distance between points, visualize elevation profile of the route Article 4: Calculate route gradients based on elevation difference and distance between points Article 5: Calculate and visualize gradient profiles — distance cycled in gradient ranges Article 6: Create a web application that analyzes and visualizes a user-uploaded GPX file from Strava Thanks for reading, and stay tuned for more! Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you. medium.com Sign up for my newsletter Subscribe on YouTube Connect on LinkedIn
[ { "code": null, "e": 489, "s": 171, "text": "I love cycling, and I love using Strava to keep track of my training activities. As a data nerd, I’m a bit disappointed with their workout analysis. Sure, you can analyze speed, power, cadence, heart rate, and whatnot — depending on the sensors you have available — but what I really miss is a deep gradient analysis." }, { "code": null, "e": 919, "s": 489, "text": "Now, a gradient in data science and cycling don’t necessarily represent the same thing. In cycling, it’s basically the slope of the surface you’re riding on. Being a tall and somewhat heavy rider I find hills challenging, so a deeper gradient analysis would be helpful. For example, I’d like to see how much distance I’ve covered between 3 and 5 percent grade, how much was above 10, and everything in between. You get the point." }, { "code": null, "e": 1033, "s": 919, "text": "Strava doesn’t offer that functionality, so I decided to do the calculations from scratch using my Python skills." }, { "code": null, "e": 1208, "s": 1033, "text": "Join me in a 6 article mini-series that will kick of with a crash course in GPX file format and end in a dashboard that displays your training data in more depth than Strava." }, { "code": null, "e": 1257, "s": 1208, "text": "Don’t feel like reading? Watch my video instead:" }, { "code": null, "e": 1301, "s": 1257, "text": "You can download the source code on GitHub." }, { "code": null, "e": 1552, "s": 1301, "text": "Strava lets you export your workouts and routes in GPX file format. Put simply, GPX stands for GPS Exchange Format, and it’s nothing but a text file with geographical information, such as latitude, longitude, elevations, tracks, waypoints, and so on." }, { "code": null, "e": 1862, "s": 1552, "text": "An exported Strava route GPX file has many points taken at different times, each containing latitude, longitude, and elevation. In simple terms, you know exactly where you were and what was your altitude. This is essential for calculating gradients and gradient ranges, which we’ll do in a couple of articles." }, { "code": null, "e": 1968, "s": 1862, "text": "If you’re following along, head over to Strava and download any of your saved routes (Export GPX button):" }, { "code": null, "e": 2224, "s": 1968, "text": "Creating routes requires a paid Strava subscription, so for safety concerns I won’t share my GPX files with you. Use any GPX file from your routes or the training log. If you’re not using Strava, simply find a sample GPX file online, it should still work." }, { "code": null, "e": 2301, "s": 2224, "text": "Got the GPX file ready? Awesome — let’s see how to read it with Python next." }, { "code": null, "e": 2385, "s": 2301, "text": "You’ll need a dedicated gpxpy package to read GPX with Python. Install it with Pip:" }, { "code": null, "e": 2403, "s": 2385, "text": "pip install gpxpy" }, { "code": null, "e": 2537, "s": 2403, "text": "You can now launch Jupyter or any other code editor to get started. First things first, let’s get the library imports out of the way:" }, { "code": null, "e": 2603, "s": 2537, "text": "Use Python’s context manager syntax to read and parse a GPX file:" }, { "code": null, "e": 2761, "s": 2603, "text": "Please note you’ll have to change the path to match your system and GPX file name. If everything went well, you should have the file now available in Python." }, { "code": null, "e": 2791, "s": 2761, "text": "But what’s inside? Let’s see:" }, { "code": null, "e": 3039, "s": 2791, "text": "It’s a specific GPX object with the track name and segment, where each segment contains data points (latitude, longitude, and elevation). We’ll dive deeper into these in the following section, but first, let’s explore a couple of useful functions." }, { "code": null, "e": 3115, "s": 3039, "text": "For example, you can extract the total number of data points in a GPX file:" }, { "code": null, "e": 3232, "s": 3115, "text": "There are 835 points in total, each containing latitude, longitude, and elevation data. That will come useful later." }, { "code": null, "e": 3269, "s": 3232, "text": "You can also get the altitude range:" }, { "code": null, "e": 3405, "s": 3269, "text": "In plain English, this means that the lowest point of the ride is 113,96 meters above sea level, while the highest is at 239,16 meters." }, { "code": null, "e": 3473, "s": 3405, "text": "You can also extract the total meters of elevation gained and lost:" }, { "code": null, "e": 3637, "s": 3473, "text": "My route represents a roundtrip, so it’s expected to see identical or almost identical values. Lastly, you can display the contents of your GPX file in XML format:" }, { "code": null, "e": 3729, "s": 3637, "text": "It’s not super-readable, but it might come in handy if you have an XML processing pipeline." }, { "code": null, "e": 3882, "s": 3729, "text": "And that does it for the basics. Next, you’ll see how to extract individual data points and convert them into a more readable format — Pandas DataFrame." }, { "code": null, "e": 4035, "s": 3882, "text": "You can check how many tracks your GPX file has by running len(gpx.tracks). Mine has only one, and I can access it with Python’s list indexing notation:" }, { "code": null, "e": 4237, "s": 4035, "text": "We don’t care for the name of the track, as it’s arbitrary in this case. What we do care about are the segments. As with tracks, my GPX file has only one segment on this track. Here’s how to access it:" }, { "code": null, "e": 4351, "s": 4237, "text": "And now you can access individual data points by accessing the points array. Here are the first ten for my route:" }, { "code": null, "e": 4460, "s": 4351, "text": "That’s all we need to have some fun. You’ll now see how to extract individual data points from the GPX file:" }, { "code": null, "e": 4604, "s": 4460, "text": "It’s not the prettiest code you’ve ever seen, but gets the job done. Let’s print the first three entries to verify we did everything correctly:" }, { "code": null, "e": 4722, "s": 4604, "text": "Do you know what’s extra handy about a list of dictionaries? You can convert it to a Pandas DataFrame in a heartbeat:" }, { "code": null, "e": 4849, "s": 4722, "text": "You have to admit — that was pretty easy! We’ll need this dataset in the following articles, so let’s dump it into a CSV file:" }, { "code": null, "e": 5025, "s": 4849, "text": "That’s all for the basic analysis and preprocessing we’ll do today. I’ll also show you how to visualize this dataset with Matplotlib — just to see if we’re on the right track." }, { "code": null, "e": 5281, "s": 5025, "text": "We’ll work on route visualization with Python and Folium in the following article, but today I want to show you how to make a basic visualization with Matplotlib. You won’t see the map, sure, but the location points should resemble the route from Image 1." }, { "code": null, "e": 5364, "s": 5281, "text": "Hint: don’t go too wide with the figure size, as it would make the map look weird." }, { "code": null, "e": 5412, "s": 5364, "text": "Copy the following code to visualize the route:" }, { "code": null, "e": 5589, "s": 5412, "text": "And who would tell — it’s identical to what we had in Image 1, not taking the obvious into account. You’ll learn all about map and route visualization in the following article." }, { "code": null, "e": 5928, "s": 5589, "text": "And there you have it — you’ve successfully exported a GPX route/training file from Strava, parsed it with Python, and extracted key characteristics like latitude, longitude, and elevation. It’s just the tip of the iceberg, and you can expect to learn more applications of programming and data science in cycling in the upcoming articles." }, { "code": null, "e": 6020, "s": 5928, "text": "Here’s a brief overview to get you motivated — I’ll add the URLs as I release the articles:" }, { "code": null, "e": 6070, "s": 6020, "text": "Article 1: Load and analyze GPX files from Strava" }, { "code": null, "e": 6160, "s": 6070, "text": "Article 2: Visualize GPX files from Strava with Folium — circle markers and polygon lines" }, { "code": null, "e": 6272, "s": 6160, "text": "Article 3: Calculate elevation difference and distance between points, visualize elevation profile of the route" }, { "code": null, "e": 6367, "s": 6272, "text": "Article 4: Calculate route gradients based on elevation difference and distance between points" }, { "code": null, "e": 6457, "s": 6367, "text": "Article 5: Calculate and visualize gradient profiles — distance cycled in gradient ranges" }, { "code": null, "e": 6559, "s": 6457, "text": "Article 6: Create a web application that analyzes and visualizes a user-uploaded GPX file from Strava" }, { "code": null, "e": 6604, "s": 6559, "text": "Thanks for reading, and stay tuned for more!" }, { "code": null, "e": 6787, "s": 6604, "text": "Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you." }, { "code": null, "e": 6798, "s": 6787, "text": "medium.com" }, { "code": null, "e": 6824, "s": 6798, "text": "Sign up for my newsletter" }, { "code": null, "e": 6845, "s": 6824, "text": "Subscribe on YouTube" } ]
Insertion sort using C++ STL
In this tutorial, we will be discussing a program to understand the insertion sort using C++ STL. In this we use std::upper_bound to find the element at the wrong position, then rotate the unsorted part of the array to make it sorted. Live Demo #include <bits/stdc++.h> //function to perform insertion sort void insertionSort(std::vector<int> &vec){ for (auto it = vec.begin(); it != vec.end(); it++){ auto const insertion_point = std::upper_bound(vec.begin(), it, *it); std::rotate(insertion_point, it, it+1); } } //printing the array void print(std::vector<int> vec){ for( int x : vec) std::cout << x << " "; std::cout << '\n'; } int main(){ std::vector<int> arr = {2, 1, 5, 3, 7, 5, 4, 6}; insertionSort(arr); print(arr); return 0; } 1 2 3 4 5 5 6 7
[ { "code": null, "e": 1160, "s": 1062, "text": "In this tutorial, we will be discussing a program to understand the insertion sort using C++ STL." }, { "code": null, "e": 1297, "s": 1160, "text": "In this we use std::upper_bound to find the element at the wrong position, then rotate the unsorted part of the array to make it sorted." }, { "code": null, "e": 1308, "s": 1297, "text": " Live Demo" }, { "code": null, "e": 1845, "s": 1308, "text": "#include <bits/stdc++.h>\n//function to perform insertion sort\nvoid insertionSort(std::vector<int> &vec){\n for (auto it = vec.begin(); it != vec.end(); it++){\n auto const insertion_point =\n std::upper_bound(vec.begin(), it, *it);\n std::rotate(insertion_point, it, it+1);\n }\n}\n//printing the array\nvoid print(std::vector<int> vec){\n for( int x : vec)\n std::cout << x << \" \";\n std::cout << '\\n';\n}\nint main(){\n std::vector<int> arr = {2, 1, 5, 3, 7, 5, 4, 6};\n insertionSort(arr);\n print(arr);\n return 0;\n}" }, { "code": null, "e": 1861, "s": 1845, "text": "1 2 3 4 5 5 6 7" } ]
Count minimum number of fountains to be activated to cover the entire garden - GeeksforGeeks
26 Aug, 2021 There is a one-dimensional garden of length N. In each position of the N length garden, a fountain has been installed. Given an array a[]such that a[i] describes the coverage limit of ith fountain. A fountain can cover the range from the position max(i – a[i], 1) to min(i + a[i], N). In beginning, all the fountains are switched off. The task is to find the minimum number of fountains needed to be activated such that the whole N-length garden can be covered by water. Examples: Input: a[] = {1, 2, 1}Output: 1Explanation:For position 1: a[1] = 1, range = 1 to 2For position 2: a[2] = 2, range = 1 to 3For position 3: a[3] = 1, range = 2 to 3Therefore, the fountain at position a[2] covers the whole garden.Therefore, the required output is 1. Input: a[] = {2, 1, 1, 2, 1} Output: 2 Approach: The problem can be solved using Dynamic Programming. Follow the steps below to solve the problem: traverse the array and for every array index, i.e. ith fountain, find the leftmost fountain up to which the current fountain covers. Then, find the rightmost fountain that the leftmost fountain obtained in the above step covers up to and update it in the dp[] array. Initialize a variable cntFount to store the minimum number of fountains that need to be activated. Now, traverse the dp[] array and keep activating the fountains from the left that covers maximum fountains currently on the right and increment cntFount by 1. Finally, print cntFount as the required answer. Below is the implementation of the above approach. C++14 Java Python3 C# Javascript // C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to find minimum// number of fountains to be// activatedint minCntFoun(int a[], int N){ // dp[i]: Stores the position of // rightmost fountain that can // be covered by water of leftmost // fountain of the i-th fountain int dp[N]; // initializing all dp[i] values to be -1, // so that we don't get garbage value for(int i=0;i<N;i++){ dp[i]=-1; } // Stores index of leftmost fountain // in the range of i-th fountain int idxLeft; // Stores index of rightmost fountain // in the range of i-th fountain int idxRight; // Traverse the array for (int i = 0; i < N; i++) { idxLeft = max(i - a[i], 0); idxRight = min(i + (a[i] + 1), N); dp[idxLeft] = max(dp[idxLeft], idxRight); } // Stores count of fountains // needed to be activated int cntfount = 1; idxRight = dp[0]; // Stores index of next fountain // that needed to be activated // initializing idxNext with -1 // so that we don't get garbage value int idxNext=-1; // Traverse dp[] array for (int i = 0; i < N; i++) { idxNext = max(idxNext, dp[i]); // If left most fountain // cover all its range if (i == idxRight) { cntfount++; idxRight = idxNext; } } return cntfount;} // Driver Codeint main(){ int a[] = { 1, 2, 1 }; int N = sizeof(a) / sizeof(a[0]); cout << minCntFoun(a, N);} // Java program to implement// the above approachimport java.util.*; class GFG { // Function to find minimum // number of fountains to be // activated static int minCntFoun(int a[], int N) { // dp[i]: Stores the position of // rightmost fountain that can // be covered by water of leftmost // fountain of the i-th fountain int[] dp = new int[N]; for(int i=0;i<N;i++) { dp[i]=-1; } // Stores index of leftmost fountain // in the range of i-th fountain int idxLeft; // Stores index of rightmost fountain // in the range of i-th fountain int idxRight; // Traverse the array for (int i = 0; i < N; i++) { idxLeft = Math.max(i - a[i], 0); idxRight = Math.min(i + (a[i] + 1), N); dp[idxLeft] = Math.max(dp[idxLeft], idxRight); } // Stores count of fountains // needed to be activated int cntfount = 1; // Stores index of next fountain // that needed to be activated int idxNext = 0; idxRight = dp[0]; // Traverse dp[] array for (int i = 0; i < N; i++) { idxNext = Math.max(idxNext, dp[i]); // If left most fountain // cover all its range if (i == idxRight) { cntfount++; idxRight = idxNext; } } return cntfount; } // Driver Code public static void main(String[] args) { int a[] = { 1, 2, 1 }; int N = a.length; System.out.print(minCntFoun(a, N)); }} // This code is contributed by Amit Katiyar # Python3 program to implement# the above approach # Function to find minimum# number of fountains to be# activated def minCntFoun(a, N): # dp[i]: Stores the position of # rightmost fountain that can # be covered by water of leftmost # fountain of the i-th fountain dp = [0] * N for i in range(N): dp[i] = -1 # Traverse the array for i in range(N): idxLeft = max(i - a[i], 0) idxRight = min(i + (a[i] + 1), N) dp[idxLeft] = max(dp[idxLeft], idxRight) # Stores count of fountains # needed to be activated cntfount = 1 idxRight = dp[0] # Stores index of next fountain # that needed to be activated idxNext = 0 # Traverse dp[] array for i in range(N): idxNext = max(idxNext, dp[i]) # If left most fountain # cover all its range if (i == idxRight): cntfount += 1 idxRight = idxNext return cntfount # Driver codeif __name__ == '__main__': a = [1, 2, 1] N = len(a) print(minCntFoun(a, N)) # This code is contributed by Shivam Singh // C# program to implement// the above approachusing System;class GFG { // Function to find minimum // number of fountains to be // activated static int minCntFoun(int[] a, int N) { // dp[i]: Stores the position of // rightmost fountain that can // be covered by water of leftmost // fountain of the i-th fountain int[] dp = new int[N]; for (int i = 0; i < N; i++) { dp[i] = -1; } // Stores index of leftmost // fountain in the range of // i-th fountain int idxLeft; // Stores index of rightmost // fountain in the range of // i-th fountain int idxRight; // Traverse the array for (int i = 0; i < N; i++) { idxLeft = Math.Max(i - a[i], 0); idxRight = Math.Min(i + (a[i] + 1), N); dp[idxLeft] = Math.Max(dp[idxLeft], idxRight); } // Stores count of fountains // needed to be activated int cntfount = 1; // Stores index of next // fountain that needed // to be activated int idxNext = 0; idxRight = dp[0]; // Traverse []dp array for (int i = 0; i < N; i++) { idxNext = Math.Max(idxNext, dp[i]); // If left most fountain // cover all its range if (i == idxRight) { cntfount++; idxRight = idxNext; } } return cntfount; } // Driver Code public static void Main(String[] args) { int[] a = { 1, 2, 1 }; int N = a.Length; Console.Write(minCntFoun(a, N)); }} // This code is contributed by gauravrajput1 <script> // Javascript program to implement// the above approach // Function to find minimum// number of fountains to be// activatedfunction minCntFoun(a, N){ // dp[i]: Stores the position of // rightmost fountain that can // be covered by water of leftmost // fountain of the i-th fountain let dp = []; for(let i = 0; i < N; i++) { dp[i] = -1; } // Stores index of leftmost fountain // in the range of i-th fountain let idxLeft; // Stores index of rightmost fountain // in the range of i-th fountain let idxRight; // Traverse the array for(let i = 0; i < N; i++) { idxLeft = Math.max(i - a[i], 0); idxRight = Math.min(i + (a[i] + 1), N); dp[idxLeft] = Math.max(dp[idxLeft], idxRight); } // Stores count of fountains // needed to be activated let cntfount = 1; // Stores index of next fountain // that needed to be activated let idxNext = 0; idxRight = dp[0]; // Traverse dp[] array for(let i = 0; i < N; i++) { idxNext = Math.max(idxNext, dp[i]); // If left most fountain // cover all its range if (i == idxRight) { cntfount++; idxRight = idxNext; } } return cntfount;} // Driver Codelet a = [ 1, 2, 1 ];let N = a.length; document.write(minCntFoun(a, N)); // This code is contributed by souravghosh0416 </script> 1 Time Complexity: O(N)Auxiliary Space: O(N) SHIVAMSINGH67 amit143katiyar GauravRajput1 sharmadevesh360 souravghosh0416 kanika199425jain ruhelaa48 Codenation Gameskraft Technologies interview-preparation Morgan Stanley two-pointer-algorithm Arrays Dynamic Programming Mathematical Morgan Stanley Codenation two-pointer-algorithm Arrays Dynamic Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Introduction to Arrays Multidimensional Arrays in Java Linear Search Linked List vs Array Python | Using 2D arrays/lists the right way 0-1 Knapsack Problem | DP-10 Program for Fibonacci numbers Longest Common Subsequence | DP-4 Longest Increasing Subsequence | DP-3 Bellman–Ford Algorithm | DP-23
[ { "code": null, "e": 25379, "s": 25351, "text": "\n26 Aug, 2021" }, { "code": null, "e": 25850, "s": 25379, "text": "There is a one-dimensional garden of length N. In each position of the N length garden, a fountain has been installed. Given an array a[]such that a[i] describes the coverage limit of ith fountain. A fountain can cover the range from the position max(i – a[i], 1) to min(i + a[i], N). In beginning, all the fountains are switched off. The task is to find the minimum number of fountains needed to be activated such that the whole N-length garden can be covered by water." }, { "code": null, "e": 25860, "s": 25850, "text": "Examples:" }, { "code": null, "e": 26125, "s": 25860, "text": "Input: a[] = {1, 2, 1}Output: 1Explanation:For position 1: a[1] = 1, range = 1 to 2For position 2: a[2] = 2, range = 1 to 3For position 3: a[3] = 1, range = 2 to 3Therefore, the fountain at position a[2] covers the whole garden.Therefore, the required output is 1." }, { "code": null, "e": 26165, "s": 26125, "text": "Input: a[] = {2, 1, 1, 2, 1} Output: 2 " }, { "code": null, "e": 26274, "s": 26165, "text": "Approach: The problem can be solved using Dynamic Programming. Follow the steps below to solve the problem: " }, { "code": null, "e": 26407, "s": 26274, "text": "traverse the array and for every array index, i.e. ith fountain, find the leftmost fountain up to which the current fountain covers." }, { "code": null, "e": 26541, "s": 26407, "text": "Then, find the rightmost fountain that the leftmost fountain obtained in the above step covers up to and update it in the dp[] array." }, { "code": null, "e": 26640, "s": 26541, "text": "Initialize a variable cntFount to store the minimum number of fountains that need to be activated." }, { "code": null, "e": 26847, "s": 26640, "text": "Now, traverse the dp[] array and keep activating the fountains from the left that covers maximum fountains currently on the right and increment cntFount by 1. Finally, print cntFount as the required answer." }, { "code": null, "e": 26898, "s": 26847, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 26904, "s": 26898, "text": "C++14" }, { "code": null, "e": 26909, "s": 26904, "text": "Java" }, { "code": null, "e": 26917, "s": 26909, "text": "Python3" }, { "code": null, "e": 26920, "s": 26917, "text": "C#" }, { "code": null, "e": 26931, "s": 26920, "text": "Javascript" }, { "code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to find minimum// number of fountains to be// activatedint minCntFoun(int a[], int N){ // dp[i]: Stores the position of // rightmost fountain that can // be covered by water of leftmost // fountain of the i-th fountain int dp[N]; // initializing all dp[i] values to be -1, // so that we don't get garbage value for(int i=0;i<N;i++){ dp[i]=-1; } // Stores index of leftmost fountain // in the range of i-th fountain int idxLeft; // Stores index of rightmost fountain // in the range of i-th fountain int idxRight; // Traverse the array for (int i = 0; i < N; i++) { idxLeft = max(i - a[i], 0); idxRight = min(i + (a[i] + 1), N); dp[idxLeft] = max(dp[idxLeft], idxRight); } // Stores count of fountains // needed to be activated int cntfount = 1; idxRight = dp[0]; // Stores index of next fountain // that needed to be activated // initializing idxNext with -1 // so that we don't get garbage value int idxNext=-1; // Traverse dp[] array for (int i = 0; i < N; i++) { idxNext = max(idxNext, dp[i]); // If left most fountain // cover all its range if (i == idxRight) { cntfount++; idxRight = idxNext; } } return cntfount;} // Driver Codeint main(){ int a[] = { 1, 2, 1 }; int N = sizeof(a) / sizeof(a[0]); cout << minCntFoun(a, N);}", "e": 28529, "s": 26931, "text": null }, { "code": "// Java program to implement// the above approachimport java.util.*; class GFG { // Function to find minimum // number of fountains to be // activated static int minCntFoun(int a[], int N) { // dp[i]: Stores the position of // rightmost fountain that can // be covered by water of leftmost // fountain of the i-th fountain int[] dp = new int[N]; for(int i=0;i<N;i++) { dp[i]=-1; } // Stores index of leftmost fountain // in the range of i-th fountain int idxLeft; // Stores index of rightmost fountain // in the range of i-th fountain int idxRight; // Traverse the array for (int i = 0; i < N; i++) { idxLeft = Math.max(i - a[i], 0); idxRight = Math.min(i + (a[i] + 1), N); dp[idxLeft] = Math.max(dp[idxLeft], idxRight); } // Stores count of fountains // needed to be activated int cntfount = 1; // Stores index of next fountain // that needed to be activated int idxNext = 0; idxRight = dp[0]; // Traverse dp[] array for (int i = 0; i < N; i++) { idxNext = Math.max(idxNext, dp[i]); // If left most fountain // cover all its range if (i == idxRight) { cntfount++; idxRight = idxNext; } } return cntfount; } // Driver Code public static void main(String[] args) { int a[] = { 1, 2, 1 }; int N = a.length; System.out.print(minCntFoun(a, N)); }} // This code is contributed by Amit Katiyar", "e": 30264, "s": 28529, "text": null }, { "code": "# Python3 program to implement# the above approach # Function to find minimum# number of fountains to be# activated def minCntFoun(a, N): # dp[i]: Stores the position of # rightmost fountain that can # be covered by water of leftmost # fountain of the i-th fountain dp = [0] * N for i in range(N): dp[i] = -1 # Traverse the array for i in range(N): idxLeft = max(i - a[i], 0) idxRight = min(i + (a[i] + 1), N) dp[idxLeft] = max(dp[idxLeft], idxRight) # Stores count of fountains # needed to be activated cntfount = 1 idxRight = dp[0] # Stores index of next fountain # that needed to be activated idxNext = 0 # Traverse dp[] array for i in range(N): idxNext = max(idxNext, dp[i]) # If left most fountain # cover all its range if (i == idxRight): cntfount += 1 idxRight = idxNext return cntfount # Driver codeif __name__ == '__main__': a = [1, 2, 1] N = len(a) print(minCntFoun(a, N)) # This code is contributed by Shivam Singh", "e": 31387, "s": 30264, "text": null }, { "code": "// C# program to implement// the above approachusing System;class GFG { // Function to find minimum // number of fountains to be // activated static int minCntFoun(int[] a, int N) { // dp[i]: Stores the position of // rightmost fountain that can // be covered by water of leftmost // fountain of the i-th fountain int[] dp = new int[N]; for (int i = 0; i < N; i++) { dp[i] = -1; } // Stores index of leftmost // fountain in the range of // i-th fountain int idxLeft; // Stores index of rightmost // fountain in the range of // i-th fountain int idxRight; // Traverse the array for (int i = 0; i < N; i++) { idxLeft = Math.Max(i - a[i], 0); idxRight = Math.Min(i + (a[i] + 1), N); dp[idxLeft] = Math.Max(dp[idxLeft], idxRight); } // Stores count of fountains // needed to be activated int cntfount = 1; // Stores index of next // fountain that needed // to be activated int idxNext = 0; idxRight = dp[0]; // Traverse []dp array for (int i = 0; i < N; i++) { idxNext = Math.Max(idxNext, dp[i]); // If left most fountain // cover all its range if (i == idxRight) { cntfount++; idxRight = idxNext; } } return cntfount; } // Driver Code public static void Main(String[] args) { int[] a = { 1, 2, 1 }; int N = a.Length; Console.Write(minCntFoun(a, N)); }} // This code is contributed by gauravrajput1", "e": 33172, "s": 31387, "text": null }, { "code": "<script> // Javascript program to implement// the above approach // Function to find minimum// number of fountains to be// activatedfunction minCntFoun(a, N){ // dp[i]: Stores the position of // rightmost fountain that can // be covered by water of leftmost // fountain of the i-th fountain let dp = []; for(let i = 0; i < N; i++) { dp[i] = -1; } // Stores index of leftmost fountain // in the range of i-th fountain let idxLeft; // Stores index of rightmost fountain // in the range of i-th fountain let idxRight; // Traverse the array for(let i = 0; i < N; i++) { idxLeft = Math.max(i - a[i], 0); idxRight = Math.min(i + (a[i] + 1), N); dp[idxLeft] = Math.max(dp[idxLeft], idxRight); } // Stores count of fountains // needed to be activated let cntfount = 1; // Stores index of next fountain // that needed to be activated let idxNext = 0; idxRight = dp[0]; // Traverse dp[] array for(let i = 0; i < N; i++) { idxNext = Math.max(idxNext, dp[i]); // If left most fountain // cover all its range if (i == idxRight) { cntfount++; idxRight = idxNext; } } return cntfount;} // Driver Codelet a = [ 1, 2, 1 ];let N = a.length; document.write(minCntFoun(a, N)); // This code is contributed by souravghosh0416 </script>", "e": 34611, "s": 33172, "text": null }, { "code": null, "e": 34616, "s": 34614, "text": "1" }, { "code": null, "e": 34661, "s": 34618, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 34677, "s": 34663, "text": "SHIVAMSINGH67" }, { "code": null, "e": 34692, "s": 34677, "text": "amit143katiyar" }, { "code": null, "e": 34706, "s": 34692, "text": "GauravRajput1" }, { "code": null, "e": 34722, "s": 34706, "text": "sharmadevesh360" }, { "code": null, "e": 34738, "s": 34722, "text": "souravghosh0416" }, { "code": null, "e": 34755, "s": 34738, "text": "kanika199425jain" }, { "code": null, "e": 34765, "s": 34755, "text": "ruhelaa48" }, { "code": null, "e": 34776, "s": 34765, "text": "Codenation" }, { "code": null, "e": 34800, "s": 34776, "text": "Gameskraft Technologies" }, { "code": null, "e": 34822, "s": 34800, "text": "interview-preparation" }, { "code": null, "e": 34837, "s": 34822, "text": "Morgan Stanley" }, { "code": null, "e": 34859, "s": 34837, "text": "two-pointer-algorithm" }, { "code": null, "e": 34866, "s": 34859, "text": "Arrays" }, { "code": null, "e": 34886, "s": 34866, "text": "Dynamic Programming" }, { "code": null, "e": 34899, "s": 34886, "text": "Mathematical" }, { "code": null, "e": 34914, "s": 34899, "text": "Morgan Stanley" }, { "code": null, "e": 34925, "s": 34914, "text": "Codenation" }, { "code": null, "e": 34947, "s": 34925, "text": "two-pointer-algorithm" }, { "code": null, "e": 34954, "s": 34947, "text": "Arrays" }, { "code": null, "e": 34974, "s": 34954, "text": "Dynamic Programming" }, { "code": null, "e": 34987, "s": 34974, "text": "Mathematical" }, { "code": null, "e": 35085, "s": 34987, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35094, "s": 35085, "text": "Comments" }, { "code": null, "e": 35107, "s": 35094, "text": "Old Comments" }, { "code": null, "e": 35130, "s": 35107, "text": "Introduction to Arrays" }, { "code": null, "e": 35162, "s": 35130, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 35176, "s": 35162, "text": "Linear Search" }, { "code": null, "e": 35197, "s": 35176, "text": "Linked List vs Array" }, { "code": null, "e": 35242, "s": 35197, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 35271, "s": 35242, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 35301, "s": 35271, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 35335, "s": 35301, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 35373, "s": 35335, "text": "Longest Increasing Subsequence | DP-3" } ]
How to set a cookie to a specific domain in selenium webdriver with Python?
We can set a cookie to a specific domain in Selenium webdriver with Python. A cookie is used to hold information sent by the browser. A key−value pair format is utilized and it is like a message provided to the browser by the server. For cookie addition, the method add_cookie is used. The key and value are passed as parameters to the method. To get back all the cookies, get_cookies method is used. To get a specific cookie, the method get_cookie is used. To delete cookies, the method delete_all_cookies is used. driver.add_cookie({"Automation": "QA"}); c= driver.get_cookies(); driver.get_cookie({"Automation"); driver.delete_all_cookies(); from selenium import webdriver #set geckodriver.exe path driver = webdriver.Firefox(executable_path="C:\\geckodriver.exe") driver.maximize_window() #launch URL driver.get("https://www.tutorialspoint.com/index.htm") #add cookie c = {'name' : "Automation", 'value' : 'QA'} driver.add_cookie(c); #count total cookies print(len(driver.get_cookies())) #obtain cookie with name print(driver.get_cookie("Automation")) #delete cookies driver.delete_all_cookies(); #check cookies after delete d = driver.get_cookies() print("Cookie count after all deletion") print(len(d)) #close browser driver.quit()
[ { "code": null, "e": 1296, "s": 1062, "text": "We can set a cookie to a specific domain in Selenium webdriver with Python. A cookie is used to hold information sent by the browser. A key−value pair format is utilized and it is like a message provided to the browser by the server." }, { "code": null, "e": 1520, "s": 1296, "text": "For cookie addition, the method add_cookie is used. The key and value are passed as parameters to the method. To get back all the cookies, get_cookies method is used. To get a specific cookie, the method get_cookie is used." }, { "code": null, "e": 1578, "s": 1520, "text": "To delete cookies, the method delete_all_cookies is used." }, { "code": null, "e": 1707, "s": 1578, "text": "driver.add_cookie({\"Automation\": \"QA\"});\nc= driver.get_cookies();\ndriver.get_cookie({\"Automation\");\ndriver.delete_all_cookies();" }, { "code": null, "e": 2300, "s": 1707, "text": "from selenium import webdriver\n#set geckodriver.exe path\ndriver = webdriver.Firefox(executable_path=\"C:\\\\geckodriver.exe\")\ndriver.maximize_window()\n#launch URL\ndriver.get(\"https://www.tutorialspoint.com/index.htm\")\n#add cookie\nc = {'name' : \"Automation\", 'value' : 'QA'}\ndriver.add_cookie(c);\n#count total cookies\nprint(len(driver.get_cookies()))\n#obtain cookie with name\nprint(driver.get_cookie(\"Automation\"))\n#delete cookies\ndriver.delete_all_cookies();\n#check cookies after delete\nd = driver.get_cookies()\nprint(\"Cookie count after all deletion\")\nprint(len(d))\n#close browser\ndriver.quit()" } ]
Scala | Trait Mixins - GeeksforGeeks
15 Apr, 2019 We can extend several number of scala traits with a class or an abstract class that is known to be trait Mixins. It is worth knowing that only traits or blend of traits and class or blend of traits and abstract class can be extended by us. It is even compulsory here to maintain the sequence of trait Mixins or else the compiler will throw an error.Note: The Mixins traits are utilized in composing a class.A Class can hardly have a single super-class, but it can have numerous trait Mixins. The super-class and the trait Mixins might have identical super-types. The Mixins traits are utilized in composing a class. A Class can hardly have a single super-class, but it can have numerous trait Mixins. The super-class and the trait Mixins might have identical super-types. Now, lets see some examples. Extending abstract class with traitExample :// Scala program of trait Mixins // Trait structuretrait Display{ def Display() } // An abstract class structureabstract class Show{ def Show() } // Extending abstract class with// traitclass CS extends Show with Display{ // Defining abstract class // method def Display() { // Displays output println("GeeksforGeeks") } // Defining trait method def Show() { // Displays output println("CS_portal") } } // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating object of class CS val x = new CS() // Calling abstract method x.Display() // Calling trait method x.Show() } } Output:GeeksforGeeks CS_portal Here, the correct order of Mixins is that, we need to extend any class or abstract class first and then extend any trait by using a keyword with. // Scala program of trait Mixins // Trait structuretrait Display{ def Display() } // An abstract class structureabstract class Show{ def Show() } // Extending abstract class with// traitclass CS extends Show with Display{ // Defining abstract class // method def Display() { // Displays output println("GeeksforGeeks") } // Defining trait method def Show() { // Displays output println("CS_portal") } } // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating object of class CS val x = new CS() // Calling abstract method x.Display() // Calling trait method x.Show() } } GeeksforGeeks CS_portal Here, the correct order of Mixins is that, we need to extend any class or abstract class first and then extend any trait by using a keyword with. Extending abstract class without traitExample :// Scala program of trait Mixins // Trait structuretrait Text{ def txt() } // An abstract class structureabstract class LowerCase{ def lowerCase() } // Extending abstract class // without traitclass Myclass extends LowerCase{ // Defining abstract class // method def lowerCase() { val y = "GEEKSFORGEEKS" // Displays output println(y.toLowerCase()) } // Defining trait method def txt() { // Displays output println("I like GeeksforGeeks") } } // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating object of 'Myclass' // with trait 'Text' val x = new Myclass() with Text // Calling abstract method x.lowerCase() // Calling trait method x.txt() } } Output:geeksforgeeks I like GeeksforGeeks Thus, from this example we can say that the trait can even be extended while creating object.Note: If we extend a trait first and then the abstract class then the compiler will throw an error, as that is not the correct order of trait Mixins. // Scala program of trait Mixins // Trait structuretrait Text{ def txt() } // An abstract class structureabstract class LowerCase{ def lowerCase() } // Extending abstract class // without traitclass Myclass extends LowerCase{ // Defining abstract class // method def lowerCase() { val y = "GEEKSFORGEEKS" // Displays output println(y.toLowerCase()) } // Defining trait method def txt() { // Displays output println("I like GeeksforGeeks") } } // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating object of 'Myclass' // with trait 'Text' val x = new Myclass() with Text // Calling abstract method x.lowerCase() // Calling trait method x.txt() } } geeksforgeeks I like GeeksforGeeks Thus, from this example we can say that the trait can even be extended while creating object.Note: If we extend a trait first and then the abstract class then the compiler will throw an error, as that is not the correct order of trait Mixins. Picked Scala scala-traits Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. For Loop in Scala Scala | flatMap Method Scala | map() method Scala List filter() method with example Scala | reduce() Function String concatenation in Scala Type Casting in Scala Scala Tutorial – Learn Scala with Step By Step Guide Scala List contains() method with example Scala String substring() method with example
[ { "code": null, "e": 26063, "s": 26035, "text": "\n15 Apr, 2019" }, { "code": null, "e": 26418, "s": 26063, "text": "We can extend several number of scala traits with a class or an abstract class that is known to be trait Mixins. It is worth knowing that only traits or blend of traits and class or blend of traits and abstract class can be extended by us. It is even compulsory here to maintain the sequence of trait Mixins or else the compiler will throw an error.Note:" }, { "code": null, "e": 26626, "s": 26418, "text": "The Mixins traits are utilized in composing a class.A Class can hardly have a single super-class, but it can have numerous trait Mixins. The super-class and the trait Mixins might have identical super-types." }, { "code": null, "e": 26679, "s": 26626, "text": "The Mixins traits are utilized in composing a class." }, { "code": null, "e": 26835, "s": 26679, "text": "A Class can hardly have a single super-class, but it can have numerous trait Mixins. The super-class and the trait Mixins might have identical super-types." }, { "code": null, "e": 26864, "s": 26835, "text": "Now, lets see some examples." }, { "code": null, "e": 27906, "s": 26864, "text": "Extending abstract class with traitExample :// Scala program of trait Mixins // Trait structuretrait Display{ def Display() } // An abstract class structureabstract class Show{ def Show() } // Extending abstract class with// traitclass CS extends Show with Display{ // Defining abstract class // method def Display() { // Displays output println(\"GeeksforGeeks\") } // Defining trait method def Show() { // Displays output println(\"CS_portal\") } } // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating object of class CS val x = new CS() // Calling abstract method x.Display() // Calling trait method x.Show() } } Output:GeeksforGeeks\nCS_portal\nHere, the correct order of Mixins is that, we need to extend any class or abstract class first and then extend any trait by using a keyword with." }, { "code": "// Scala program of trait Mixins // Trait structuretrait Display{ def Display() } // An abstract class structureabstract class Show{ def Show() } // Extending abstract class with// traitclass CS extends Show with Display{ // Defining abstract class // method def Display() { // Displays output println(\"GeeksforGeeks\") } // Defining trait method def Show() { // Displays output println(\"CS_portal\") } } // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating object of class CS val x = new CS() // Calling abstract method x.Display() // Calling trait method x.Show() } } ", "e": 28728, "s": 27906, "text": null }, { "code": null, "e": 28753, "s": 28728, "text": "GeeksforGeeks\nCS_portal\n" }, { "code": null, "e": 28899, "s": 28753, "text": "Here, the correct order of Mixins is that, we need to extend any class or abstract class first and then extend any trait by using a keyword with." }, { "code": null, "e": 30153, "s": 28899, "text": "Extending abstract class without traitExample :// Scala program of trait Mixins // Trait structuretrait Text{ def txt() } // An abstract class structureabstract class LowerCase{ def lowerCase() } // Extending abstract class // without traitclass Myclass extends LowerCase{ // Defining abstract class // method def lowerCase() { val y = \"GEEKSFORGEEKS\" // Displays output println(y.toLowerCase()) } // Defining trait method def txt() { // Displays output println(\"I like GeeksforGeeks\") } } // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating object of 'Myclass' // with trait 'Text' val x = new Myclass() with Text // Calling abstract method x.lowerCase() // Calling trait method x.txt() } } Output:geeksforgeeks\nI like GeeksforGeeks\nThus, from this example we can say that the trait can even be extended while creating object.Note: If we extend a trait first and then the abstract class then the compiler will throw an error, as that is not the correct order of trait Mixins." }, { "code": "// Scala program of trait Mixins // Trait structuretrait Text{ def txt() } // An abstract class structureabstract class LowerCase{ def lowerCase() } // Extending abstract class // without traitclass Myclass extends LowerCase{ // Defining abstract class // method def lowerCase() { val y = \"GEEKSFORGEEKS\" // Displays output println(y.toLowerCase()) } // Defining trait method def txt() { // Displays output println(\"I like GeeksforGeeks\") } } // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating object of 'Myclass' // with trait 'Text' val x = new Myclass() with Text // Calling abstract method x.lowerCase() // Calling trait method x.txt() } } ", "e": 31076, "s": 30153, "text": null }, { "code": null, "e": 31112, "s": 31076, "text": "geeksforgeeks\nI like GeeksforGeeks\n" }, { "code": null, "e": 31355, "s": 31112, "text": "Thus, from this example we can say that the trait can even be extended while creating object.Note: If we extend a trait first and then the abstract class then the compiler will throw an error, as that is not the correct order of trait Mixins." }, { "code": null, "e": 31362, "s": 31355, "text": "Picked" }, { "code": null, "e": 31368, "s": 31362, "text": "Scala" }, { "code": null, "e": 31381, "s": 31368, "text": "scala-traits" }, { "code": null, "e": 31387, "s": 31381, "text": "Scala" }, { "code": null, "e": 31485, "s": 31387, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31503, "s": 31485, "text": "For Loop in Scala" }, { "code": null, "e": 31526, "s": 31503, "text": "Scala | flatMap Method" }, { "code": null, "e": 31547, "s": 31526, "text": "Scala | map() method" }, { "code": null, "e": 31587, "s": 31547, "text": "Scala List filter() method with example" }, { "code": null, "e": 31613, "s": 31587, "text": "Scala | reduce() Function" }, { "code": null, "e": 31643, "s": 31613, "text": "String concatenation in Scala" }, { "code": null, "e": 31665, "s": 31643, "text": "Type Casting in Scala" }, { "code": null, "e": 31718, "s": 31665, "text": "Scala Tutorial – Learn Scala with Step By Step Guide" }, { "code": null, "e": 31760, "s": 31718, "text": "Scala List contains() method with example" } ]
List isEmpty() method in Java with Examples - GeeksforGeeks
23 Aug, 2020 The isEmpty() method of List interface in java is used to check if a list is empty or not. It returns true if the list contains no elements otherwise it returns false if the list contains any element. Syntax: boolean isEmpty() Parameter: It does not accepts any parameter. Returns: It returns True if the list has no elements else it returns false. The return type is of datatype boolean. Error and Exceptions: This method has no error or exceptions. Program to demonstrate working of isEmpty() in Java: // Java code to demonstrate the working of// isEmpty() method in List interface import java.util.*; public class GFG { public static void main(String[] args) { // creating an Empty Integer List List<Integer> arr = new ArrayList<Integer>(10); // check if the list is empty or not // using isEmpty() function boolean ans = arr.isEmpty(); if (ans == true) System.out.println("The List is empty"); else System.out.println("The List is not empty"); // addition of a element to // the List arr.add(1); // check if the list is empty or not // after adding an element ans = arr.isEmpty(); if (ans == true) System.out.println("The List is empty"); else System.out.println("The List is not empty"); }} Output: The List is empty The List is not empty Reference: https://docs.oracle.com/javase/7/docs/api/java/util/List.html#isEmpty() Akanksha_Rai Java-Collections Java-Functions java-list Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Stream In Java Interfaces in Java How to iterate any Map in Java Initialize an ArrayList in Java ArrayList in Java Stack Class in Java Singleton Class in Java Multidimensional Arrays in Java
[ { "code": null, "e": 26277, "s": 26249, "text": "\n23 Aug, 2020" }, { "code": null, "e": 26478, "s": 26277, "text": "The isEmpty() method of List interface in java is used to check if a list is empty or not. It returns true if the list contains no elements otherwise it returns false if the list contains any element." }, { "code": null, "e": 26486, "s": 26478, "text": "Syntax:" }, { "code": null, "e": 26504, "s": 26486, "text": "boolean isEmpty()" }, { "code": null, "e": 26550, "s": 26504, "text": "Parameter: It does not accepts any parameter." }, { "code": null, "e": 26666, "s": 26550, "text": "Returns: It returns True if the list has no elements else it returns false. The return type is of datatype boolean." }, { "code": null, "e": 26728, "s": 26666, "text": "Error and Exceptions: This method has no error or exceptions." }, { "code": null, "e": 26781, "s": 26728, "text": "Program to demonstrate working of isEmpty() in Java:" }, { "code": "// Java code to demonstrate the working of// isEmpty() method in List interface import java.util.*; public class GFG { public static void main(String[] args) { // creating an Empty Integer List List<Integer> arr = new ArrayList<Integer>(10); // check if the list is empty or not // using isEmpty() function boolean ans = arr.isEmpty(); if (ans == true) System.out.println(\"The List is empty\"); else System.out.println(\"The List is not empty\"); // addition of a element to // the List arr.add(1); // check if the list is empty or not // after adding an element ans = arr.isEmpty(); if (ans == true) System.out.println(\"The List is empty\"); else System.out.println(\"The List is not empty\"); }}", "e": 27639, "s": 26781, "text": null }, { "code": null, "e": 27647, "s": 27639, "text": "Output:" }, { "code": null, "e": 27688, "s": 27647, "text": "The List is empty\nThe List is not empty\n" }, { "code": null, "e": 27771, "s": 27688, "text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/util/List.html#isEmpty()" }, { "code": null, "e": 27784, "s": 27771, "text": "Akanksha_Rai" }, { "code": null, "e": 27801, "s": 27784, "text": "Java-Collections" }, { "code": null, "e": 27816, "s": 27801, "text": "Java-Functions" }, { "code": null, "e": 27826, "s": 27816, "text": "java-list" }, { "code": null, "e": 27831, "s": 27826, "text": "Java" }, { "code": null, "e": 27836, "s": 27831, "text": "Java" }, { "code": null, "e": 27853, "s": 27836, "text": "Java-Collections" }, { "code": null, "e": 27951, "s": 27853, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28002, "s": 27951, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 28032, "s": 28002, "text": "HashMap in Java with Examples" }, { "code": null, "e": 28047, "s": 28032, "text": "Stream In Java" }, { "code": null, "e": 28066, "s": 28047, "text": "Interfaces in Java" }, { "code": null, "e": 28097, "s": 28066, "text": "How to iterate any Map in Java" }, { "code": null, "e": 28129, "s": 28097, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 28147, "s": 28129, "text": "ArrayList in Java" }, { "code": null, "e": 28167, "s": 28147, "text": "Stack Class in Java" }, { "code": null, "e": 28191, "s": 28167, "text": "Singleton Class in Java" } ]
Pure CSS Disabled Inputs - GeeksforGeeks
28 Feb, 2022 In this article, we will see how to disable the input field in Pure CSS. In some cases, when we ask someone to fill a form few things are activated as well a few things are disabled for their previous choices. In that case, we can use HTML disabled in Pure CSS as well. This attribute works with other types of input like radio, checkbox, number, text, etc. Please refer to the Pure CSS Buttons article for further details. Syntax: <tag disabled></tag> Example 1: In this example, we will use the disabled attribute to disable the username filed in the form. HTML <!DOCTYPE html><html> <head> <title>Pure CSS Required Input</title> <link rel="stylesheet" href= "https://unpkg.com/purecss@1.0.0/build/pure-min.css" integrity="sha384-nn4HPE8lTHyVtfCBi5yW9d20FjT8BJwUXyWZT9InLYax14RDjBj46LmSztkmNP9w" crossorigin="anonymous"></head> <body> <h1>GeeksforGeeks</h1> <strong> Pure CSS Disabled Input </strong> <form action=""> Username: <input type="text" name="username" disabled=""> <br><br> Password: <input type="password" name="password"> <br> <input type="submit"> </form></body> </html> Output: Example 2: To mark a button as disabled, add “pure-button-disabled” with class pure-button. You can also use the disabled attribute directly. Syntax: <button class="pure-button pure-button-disabled"> Disabled Button1 </button> <button class="pure-button" disabled> Disabled Button2 </button> Example: HTML <!DOCTYPE html><html> <head> <!--Import Pure Css files--> <link rel="stylesheet" href="https://unpkg.com/purecss@1.0.0/build/pure-min.css" integrity="sha384-nn4HPE8lTHyVtfCBi5yW9d20FjT8BJwUXyWZT9InLYax14RDjBj46LmSztkmNP9w" crossorigin="anonymous" /></head> <body style="text-align: center"> <h1>GeeksforGeeks</h1> <strong> Pure CSS Disabled Input </strong> <form action=""> Username: <input type="text" name="username" /> Password: <input type="password" name="password" /> <input type="submit" class="pure-button" disabled="" /> </form></body> </html> Output: Example 3: In this example, we will put the disabled attribute for the input type as radio. HTML <!DOCTYPE html><html> <head> <title>Pure CSS Required Input</title> <link rel="stylesheet" href="https://unpkg.com/purecss@1.0.0/build/pure-min.css" integrity="sha384-nn4HPE8lTHyVtfCBi5yW9d20FjT8BJwUXyWZT9InLYax14RDjBj46LmSztkmNP9w" crossorigin="anonymous" /></head> <body> <h1>GeeksforGeeks</h1> <strong> Pure CSS Disabled Input </strong> <form action=""> Without clicking the Radio button: <input type="radio" name="radiocheck" required="" /> <input type="radio" name="radiocheck" disabled="" /> </form></body> </html> Output: varshagumber28 CSS-Questions Picked Pure CSS CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to create footer to stay at the bottom of a Web page? How to apply style to parent if it has child with CSS? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26647, "s": 26619, "text": "\n28 Feb, 2022" }, { "code": null, "e": 27071, "s": 26647, "text": "In this article, we will see how to disable the input field in Pure CSS. In some cases, when we ask someone to fill a form few things are activated as well a few things are disabled for their previous choices. In that case, we can use HTML disabled in Pure CSS as well. This attribute works with other types of input like radio, checkbox, number, text, etc. Please refer to the Pure CSS Buttons article for further details." }, { "code": null, "e": 27079, "s": 27071, "text": "Syntax:" }, { "code": null, "e": 27100, "s": 27079, "text": "<tag disabled></tag>" }, { "code": null, "e": 27206, "s": 27100, "text": "Example 1: In this example, we will use the disabled attribute to disable the username filed in the form." }, { "code": null, "e": 27211, "s": 27206, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Pure CSS Required Input</title> <link rel=\"stylesheet\" href= \"https://unpkg.com/purecss@1.0.0/build/pure-min.css\" integrity=\"sha384-nn4HPE8lTHyVtfCBi5yW9d20FjT8BJwUXyWZT9InLYax14RDjBj46LmSztkmNP9w\" crossorigin=\"anonymous\"></head> <body> <h1>GeeksforGeeks</h1> <strong> Pure CSS Disabled Input </strong> <form action=\"\"> Username: <input type=\"text\" name=\"username\" disabled=\"\"> <br><br> Password: <input type=\"password\" name=\"password\"> <br> <input type=\"submit\"> </form></body> </html>", "e": 27828, "s": 27211, "text": null }, { "code": null, "e": 27836, "s": 27828, "text": "Output:" }, { "code": null, "e": 27978, "s": 27836, "text": "Example 2: To mark a button as disabled, add “pure-button-disabled” with class pure-button. You can also use the disabled attribute directly." }, { "code": null, "e": 27986, "s": 27978, "text": "Syntax:" }, { "code": null, "e": 28136, "s": 27986, "text": "<button class=\"pure-button pure-button-disabled\">\n Disabled Button1\n</button> \n\n<button class=\"pure-button\" disabled> \n Disabled Button2\n</button>" }, { "code": null, "e": 28145, "s": 28136, "text": "Example:" }, { "code": null, "e": 28150, "s": 28145, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!--Import Pure Css files--> <link rel=\"stylesheet\" href=\"https://unpkg.com/purecss@1.0.0/build/pure-min.css\" integrity=\"sha384-nn4HPE8lTHyVtfCBi5yW9d20FjT8BJwUXyWZT9InLYax14RDjBj46LmSztkmNP9w\" crossorigin=\"anonymous\" /></head> <body style=\"text-align: center\"> <h1>GeeksforGeeks</h1> <strong> Pure CSS Disabled Input </strong> <form action=\"\"> Username: <input type=\"text\" name=\"username\" /> Password: <input type=\"password\" name=\"password\" /> <input type=\"submit\" class=\"pure-button\" disabled=\"\" /> </form></body> </html>", "e": 28784, "s": 28150, "text": null }, { "code": null, "e": 28792, "s": 28784, "text": "Output:" }, { "code": null, "e": 28885, "s": 28792, "text": "Example 3: In this example, we will put the disabled attribute for the input type as radio." }, { "code": null, "e": 28890, "s": 28885, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Pure CSS Required Input</title> <link rel=\"stylesheet\" href=\"https://unpkg.com/purecss@1.0.0/build/pure-min.css\" integrity=\"sha384-nn4HPE8lTHyVtfCBi5yW9d20FjT8BJwUXyWZT9InLYax14RDjBj46LmSztkmNP9w\" crossorigin=\"anonymous\" /></head> <body> <h1>GeeksforGeeks</h1> <strong> Pure CSS Disabled Input </strong> <form action=\"\"> Without clicking the Radio button: <input type=\"radio\" name=\"radiocheck\" required=\"\" /> <input type=\"radio\" name=\"radiocheck\" disabled=\"\" /> </form></body> </html>", "e": 29487, "s": 28890, "text": null }, { "code": null, "e": 29495, "s": 29487, "text": "Output:" }, { "code": null, "e": 29510, "s": 29495, "text": "varshagumber28" }, { "code": null, "e": 29524, "s": 29510, "text": "CSS-Questions" }, { "code": null, "e": 29531, "s": 29524, "text": "Picked" }, { "code": null, "e": 29540, "s": 29531, "text": "Pure CSS" }, { "code": null, "e": 29544, "s": 29540, "text": "CSS" }, { "code": null, "e": 29561, "s": 29544, "text": "Web Technologies" }, { "code": null, "e": 29659, "s": 29561, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29709, "s": 29659, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 29771, "s": 29709, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 29819, "s": 29771, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 29877, "s": 29819, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 29932, "s": 29877, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 29972, "s": 29932, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30005, "s": 29972, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30050, "s": 30005, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30093, "s": 30050, "text": "How to fetch data from an API in ReactJS ?" } ]
Pair Class in Java - GeeksforGeeks
28 Jun, 2021 In C++, we have std::pair in the utility library which is of immense use if we want to keep a pair of values together. We were looking for an equivalent class for pair in Java but Pair class did not come into existence till Java 7. JavaFX 2.2 has the javafx.util.Pair class which can be used to store a pair. We need to store the values into Pair using the parameterized constructor provided by the javafx.util.Pair class. Note : Note that the <Key, Value> pair used in HashMap/TreeMap. Here, <Key, Value> simply refers to a pair of values that are stored together. Methods provided by the javafx.util.Pair class Pair (K key, V value) : Creates a new pair boolean equals() : It is used to compare two pair objects. It does a deep comparison, i.e., it compares on the basic of the values (<Key, Value>) which are stored in the pair objects. Example:Pair p1 = new Pair(3,4);Pair p2 = new Pair(3,4);Pair p3 = new Pair(4,4);System.out.println(p1.equals(p2) + “ ” + p2.equals(p3));Output:true false Pair p1 = new Pair(3,4);Pair p2 = new Pair(3,4);Pair p3 = new Pair(4,4);System.out.println(p1.equals(p2) + “ ” + p2.equals(p3)); Output:true false String toString() : This method will return the String representation of the Pair. K getKey() : It returns key for the pair. V getValue() : It returns value for the pair. int hashCode() : Generate a hash code for the Pair. Let us have a look at the following problem.Problem Statement : We are given names of n students with their corresponding scores obtained in a quiz. We need to find the student with maximum score in the class.Note : You need to have Java 8 installed on your machine in order to run the below program./* Java program to find a Pair which has maximum score*/import javafx.util.Pair;import java.util.ArrayList; class Test{ /* This method returns a Pair which hasmaximum score*/ public static Pair <String,Integer> getMaximum(ArrayList < Pair <String,Integer> > l) { // Assign minimum value initially int max = Integer.MIN_VALUE; // Pair to store the maximum marks of a // student with its name Pair <String, Integer> ans = new Pair <String, Integer> ("", 0); // Using for each loop to iterate array of // Pair Objects for (Pair <String,Integer> temp : l) { // Get the score of Student int val = temp.getValue(); // Check if it is greater than the previous // maximum marks if (val > max) { max = val; // update maximum ans = temp; // update the Pair } } return ans; } // Driver method to test above method public static void main (String[] args) { int n = 5;//Number of Students //Create an Array List ArrayList <Pair <String,Integer> > l = new ArrayList <Pair <String,Integer> > (); /* Create pair of name of student with their corresponding score and insert into the Arraylist */ l.add(new Pair <String,Integer> ("Student A", 90)); l.add(new Pair <String,Integer> ("Student B", 54)); l.add(new Pair <String,Integer> ("Student C", 99)); l.add(new Pair <String,Integer> ("Student D", 88)); l.add(new Pair <String,Integer> ("Student E", 89)); // get the Pair which has maximum value Pair <String,Integer> ans = getMaximum(l); System.out.println(ans.getKey() + " is top scorer " + "with score of " + ans.getValue()); }}Output :Student C is top scorer with score of 99Note: The above program might not run in an online IDE, please use an offline compiler. References : https://docs.oracle.com/javafx/2/api/javafx/util/Pair.html This article is contributed by Chirag Agarwal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed aboveMy Personal Notes arrow_drop_upSave Let us have a look at the following problem.Problem Statement : We are given names of n students with their corresponding scores obtained in a quiz. We need to find the student with maximum score in the class. Note : You need to have Java 8 installed on your machine in order to run the below program. /* Java program to find a Pair which has maximum score*/import javafx.util.Pair;import java.util.ArrayList; class Test{ /* This method returns a Pair which hasmaximum score*/ public static Pair <String,Integer> getMaximum(ArrayList < Pair <String,Integer> > l) { // Assign minimum value initially int max = Integer.MIN_VALUE; // Pair to store the maximum marks of a // student with its name Pair <String, Integer> ans = new Pair <String, Integer> ("", 0); // Using for each loop to iterate array of // Pair Objects for (Pair <String,Integer> temp : l) { // Get the score of Student int val = temp.getValue(); // Check if it is greater than the previous // maximum marks if (val > max) { max = val; // update maximum ans = temp; // update the Pair } } return ans; } // Driver method to test above method public static void main (String[] args) { int n = 5;//Number of Students //Create an Array List ArrayList <Pair <String,Integer> > l = new ArrayList <Pair <String,Integer> > (); /* Create pair of name of student with their corresponding score and insert into the Arraylist */ l.add(new Pair <String,Integer> ("Student A", 90)); l.add(new Pair <String,Integer> ("Student B", 54)); l.add(new Pair <String,Integer> ("Student C", 99)); l.add(new Pair <String,Integer> ("Student D", 88)); l.add(new Pair <String,Integer> ("Student E", 89)); // get the Pair which has maximum value Pair <String,Integer> ans = getMaximum(l); System.out.println(ans.getKey() + " is top scorer " + "with score of " + ans.getValue()); }} Output : Student C is top scorer with score of 99 Note: The above program might not run in an online IDE, please use an offline compiler. References : https://docs.oracle.com/javafx/2/api/javafx/util/Pair.html This article is contributed by Chirag Agarwal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Java-Collections Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Stream In Java Interfaces in Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Singleton Class in Java Multidimensional Arrays in Java
[ { "code": null, "e": 25677, "s": 25649, "text": "\n28 Jun, 2021" }, { "code": null, "e": 26244, "s": 25677, "text": "In C++, we have std::pair in the utility library which is of immense use if we want to keep a pair of values together. We were looking for an equivalent class for pair in Java but Pair class did not come into existence till Java 7. JavaFX 2.2 has the javafx.util.Pair class which can be used to store a pair. We need to store the values into Pair using the parameterized constructor provided by the javafx.util.Pair class. Note : Note that the <Key, Value> pair used in HashMap/TreeMap. Here, <Key, Value> simply refers to a pair of values that are stored together. " }, { "code": null, "e": 26291, "s": 26244, "text": "Methods provided by the javafx.util.Pair class" }, { "code": null, "e": 26334, "s": 26291, "text": "Pair (K key, V value) : Creates a new pair" }, { "code": null, "e": 26673, "s": 26334, "text": "boolean equals() : It is used to compare two pair objects. It does a deep comparison, i.e., it compares on the basic of the values (<Key, Value>) which are stored in the pair objects. Example:Pair p1 = new Pair(3,4);Pair p2 = new Pair(3,4);Pair p3 = new Pair(4,4);System.out.println(p1.equals(p2) + “ ” + p2.equals(p3));Output:true false " }, { "code": "Pair p1 = new Pair(3,4);Pair p2 = new Pair(3,4);Pair p3 = new Pair(4,4);System.out.println(p1.equals(p2) + “ ” + p2.equals(p3));", "e": 26802, "s": 26673, "text": null }, { "code": null, "e": 26820, "s": 26802, "text": "Output:true false" }, { "code": null, "e": 26905, "s": 26822, "text": "String toString() : This method will return the String representation of the Pair." }, { "code": null, "e": 26947, "s": 26905, "text": "K getKey() : It returns key for the pair." }, { "code": null, "e": 26993, "s": 26947, "text": "V getValue() : It returns value for the pair." }, { "code": null, "e": 29691, "s": 26993, "text": "int hashCode() : Generate a hash code for the Pair. Let us have a look at the following problem.Problem Statement : We are given names of n students with their corresponding scores obtained in a quiz. We need to find the student with maximum score in the class.Note : You need to have Java 8 installed on your machine in order to run the below program./* Java program to find a Pair which has maximum score*/import javafx.util.Pair;import java.util.ArrayList; class Test{ /* This method returns a Pair which hasmaximum score*/ public static Pair <String,Integer> getMaximum(ArrayList < Pair <String,Integer> > l) { // Assign minimum value initially int max = Integer.MIN_VALUE; // Pair to store the maximum marks of a // student with its name Pair <String, Integer> ans = new Pair <String, Integer> (\"\", 0); // Using for each loop to iterate array of // Pair Objects for (Pair <String,Integer> temp : l) { // Get the score of Student int val = temp.getValue(); // Check if it is greater than the previous // maximum marks if (val > max) { max = val; // update maximum ans = temp; // update the Pair } } return ans; } // Driver method to test above method public static void main (String[] args) { int n = 5;//Number of Students //Create an Array List ArrayList <Pair <String,Integer> > l = new ArrayList <Pair <String,Integer> > (); /* Create pair of name of student with their corresponding score and insert into the Arraylist */ l.add(new Pair <String,Integer> (\"Student A\", 90)); l.add(new Pair <String,Integer> (\"Student B\", 54)); l.add(new Pair <String,Integer> (\"Student C\", 99)); l.add(new Pair <String,Integer> (\"Student D\", 88)); l.add(new Pair <String,Integer> (\"Student E\", 89)); // get the Pair which has maximum value Pair <String,Integer> ans = getMaximum(l); System.out.println(ans.getKey() + \" is top scorer \" + \"with score of \" + ans.getValue()); }}Output :Student C is top scorer with score of 99Note: The above program might not run in an online IDE, please use an offline compiler. References : https://docs.oracle.com/javafx/2/api/javafx/util/Pair.html This article is contributed by Chirag Agarwal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed aboveMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 29903, "s": 29693, "text": "Let us have a look at the following problem.Problem Statement : We are given names of n students with their corresponding scores obtained in a quiz. We need to find the student with maximum score in the class." }, { "code": null, "e": 29995, "s": 29903, "text": "Note : You need to have Java 8 installed on your machine in order to run the below program." }, { "code": "/* Java program to find a Pair which has maximum score*/import javafx.util.Pair;import java.util.ArrayList; class Test{ /* This method returns a Pair which hasmaximum score*/ public static Pair <String,Integer> getMaximum(ArrayList < Pair <String,Integer> > l) { // Assign minimum value initially int max = Integer.MIN_VALUE; // Pair to store the maximum marks of a // student with its name Pair <String, Integer> ans = new Pair <String, Integer> (\"\", 0); // Using for each loop to iterate array of // Pair Objects for (Pair <String,Integer> temp : l) { // Get the score of Student int val = temp.getValue(); // Check if it is greater than the previous // maximum marks if (val > max) { max = val; // update maximum ans = temp; // update the Pair } } return ans; } // Driver method to test above method public static void main (String[] args) { int n = 5;//Number of Students //Create an Array List ArrayList <Pair <String,Integer> > l = new ArrayList <Pair <String,Integer> > (); /* Create pair of name of student with their corresponding score and insert into the Arraylist */ l.add(new Pair <String,Integer> (\"Student A\", 90)); l.add(new Pair <String,Integer> (\"Student B\", 54)); l.add(new Pair <String,Integer> (\"Student C\", 99)); l.add(new Pair <String,Integer> (\"Student D\", 88)); l.add(new Pair <String,Integer> (\"Student E\", 89)); // get the Pair which has maximum value Pair <String,Integer> ans = getMaximum(l); System.out.println(ans.getKey() + \" is top scorer \" + \"with score of \" + ans.getValue()); }}", "e": 31928, "s": 29995, "text": null }, { "code": null, "e": 31937, "s": 31928, "text": "Output :" }, { "code": null, "e": 31978, "s": 31937, "text": "Student C is top scorer with score of 99" }, { "code": null, "e": 32066, "s": 31978, "text": "Note: The above program might not run in an online IDE, please use an offline compiler." }, { "code": null, "e": 32140, "s": 32066, "text": " References : https://docs.oracle.com/javafx/2/api/javafx/util/Pair.html " }, { "code": null, "e": 32311, "s": 32140, "text": "This article is contributed by Chirag Agarwal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 32328, "s": 32311, "text": "Java-Collections" }, { "code": null, "e": 32333, "s": 32328, "text": "Java" }, { "code": null, "e": 32338, "s": 32333, "text": "Java" }, { "code": null, "e": 32355, "s": 32338, "text": "Java-Collections" }, { "code": null, "e": 32453, "s": 32355, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32504, "s": 32453, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 32534, "s": 32504, "text": "HashMap in Java with Examples" }, { "code": null, "e": 32549, "s": 32534, "text": "Stream In Java" }, { "code": null, "e": 32568, "s": 32549, "text": "Interfaces in Java" }, { "code": null, "e": 32599, "s": 32568, "text": "How to iterate any Map in Java" }, { "code": null, "e": 32617, "s": 32599, "text": "ArrayList in Java" }, { "code": null, "e": 32649, "s": 32617, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 32669, "s": 32649, "text": "Stack Class in Java" }, { "code": null, "e": 32693, "s": 32669, "text": "Singleton Class in Java" } ]
Print all distinct permutations of a given string with duplicates - GeeksforGeeks
18 Apr, 2022 Given a string that may contain duplicates, write a function to print all permutations of given string such that no permutation is repeated in output.Examples: Input: str[] = "AB" Output: AB BA Input: str[] = "AA" Output: AA Input: str[] = "ABC" Output: ABC ACB BAC BCA CBA CAB Input: str[] = "ABA" Output: ABA AAB BAA Input: str[] = "ABCA" Output: AABC AACB ABAC ABCA ACBA ACAB BAAC BACA BCAA CABA CAAB CBAA We have discussed an algorithm to print all permutations in below post. It is strongly recommended to refer below post as a prerequisite of this post.Write a C program to print all permutations of a given stringThe algorithm discussed on above link doesn’t handle duplicates. CPP C // Program to print all permutations of a// string in sorted order.#include <bits/stdc++.h>using namespace std; /* Following function is needed for library function qsort(). */int compare(const void* a, const void* b){ return (*(char*)a - *(char*)b);} // A utility function two swap two characters a and bvoid swap(char* a, char* b){ char t = *a; *a = *b; *b = t;} // This function finds the index of the smallest character// which is greater than 'first' and is present in str[l..h]int findCeil(char str[], char first, int l, int h){ // initialize index of ceiling element int ceilIndex = l; // Now iterate through rest of the elements and find the // smallest character greater than 'first' for (int i = l + 1; i <= h; i++) if (str[i] > first && str[i] < str[ceilIndex]) ceilIndex = i; return ceilIndex;} // Print all permutations of str in sorted ordervoid sortedPermutations(char str[]){ // Get size of string int size = strlen(str); // Sort the string in increasing order qsort(str, size, sizeof(str[0]), compare); // Print permutations one by one bool isFinished = false; while (!isFinished) { // print this permutation static int x = 1; cout << x++ << " " << str << endl; // printf("%d %s \n", x++, str); // Find the rightmost character which is smaller // than its next character. Let us call it 'first // char' int i; for (i = size - 2; i >= 0; --i) if (str[i] < str[i + 1]) break; // If there is no such character, all are sorted in // decreasing order, means we just printed the last // permutation and we are done. if (i == -1) isFinished = true; else { // Find the ceil of 'first char' in right of // first character. Ceil of a character is the // smallest character greater than it int ceilIndex = findCeil(str, str[i], i + 1, size - 1); // Swap first and second characters swap(&str[i], &str[ceilIndex]); // Sort the string on right of 'first char' qsort(str + i + 1, size - i - 1, sizeof(str[0]), compare); } }} // Driver program to test above functionint main(){ char str[] = "ACBC"; sortedPermutations(str); return 0;} // This code is contributed by Aditya Kumar (adityakumar129) // Program to print all permutations of a string in sorted// order.#include <stdbool.h>#include <stdio.h>#include <stdlib.h>#include <string.h> /* Following function is needed for library function qsort(). */int compare(const void* a, const void* b){ return (*(char*)a - *(char*)b);} // A utility function two swap two characters// a and bvoid swap(char* a, char* b){ char t = *a; *a = *b; *b = t;} // This function finds the index of the smallest character// which is greater than 'first' and is present in str[l..h]int findCeil(char str[], char first, int l, int h){ // initialize index of ceiling element int ceilIndex = l; // Now iterate through rest of the elements and find the // smallest character greater than 'first' for (int i = l + 1; i <= h; i++) if (str[i] > first && str[i] < str[ceilIndex]) ceilIndex = i; return ceilIndex;} // Print all permutations of str in sorted ordervoid sortedPermutations(char str[]){ // Get size of string int size = strlen(str); // Sort the string in increasing order qsort(str, size, sizeof(str[0]), compare); // Print permutations one by one bool isFinished = false; while (!isFinished) { // print this permutation static int x = 1; printf("%d %s \n", x++, str); // Find the rightmost character which is smaller // than its next character. Let us call it 'first // char' int i; for (i = size - 2; i >= 0; --i) if (str[i] < str[i + 1]) break; // If there is no such character, all are sorted in // decreasing order, means we just printed the last // permutation and we are done. if (i == -1) isFinished = true; else { // Find the ceil of 'first char' in right of // first character. Ceil of a character is the // smallest character greater than it int ceilIndex = findCeil(str, str[i], i + 1, size - 1); // Swap first and second characters swap(&str[i], &str[ceilIndex]); // Sort the string on right of 'first char' qsort(str + i + 1, size - i - 1, sizeof(str[0]), compare); } }} // Driver program to test above functionint main(){ char str[] = "ACBC"; sortedPermutations(str); return 0;} // This code is contributed by Aditya Kumar (adityakumar129) 1 ABCC 2 ACBC 3 ACCB 4 BACC 5 BCAC 6 BCCA 7 CABC 8 CACB 9 CBAC 10 CBCA 11 CCAB 12 CCBA The above code is taken from a comment below by Mr. Lazy.Time Complexity: O(n2 * n!) Auxiliary Space: O(1) The above algorithm is in the time complexity of O(n2 * n!) but we can achieve a better time complexity of O(n!*n) which was there in the case of all distinct characters in the input by some modification in that algorithm. The distinct characters algorithm can be found here – https://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/ Efficient Approach: In our recursive function to find all permutations, we can use unordered_set for taking care of duplicate element remaining in the active string. While iterating over the elements of the string, we will check for that element in the unordered_set and if it found then we will skip that iteration or otherwise we will insert that element into unordered_set. As on an average all the unordered_set operations like insert() and find() are in O(1) time then the algorithm time complexity will not change by using unordered_set. The algorithm implementation is as follows – C++ Javascript #include <bits/stdc++.h>using namespace std; void printAllPermutationsFast(string s, string l){ if (s.length() < 1) cout << l + s << endl; unordered_set<char> uset; for (int i = 0; i < s.length(); i++) { if (uset.find(s[i]) != uset.end()) continue; else uset.insert(s[i]); string temp = ""; if (i < s.length() - 1) temp = s.substr(0, i) + s.substr(i + 1); else temp = s.substr(0, i); printAllPermutationsFast(temp, l + s[i]); }} int main(){ string s = "ACBC"; sort(s.begin(), s.end()); printAllPermutationsFast(s, ""); return 0;} // This code is contributed by Aditya Kumar (adityakumar129) <script> // JavaScript code for the same approach function printAllPermutationsFast(s, l){ if (s.length < 1) { document.write(l + s,"</br>"); } let uset = new Set(); for (let i = 0; i < s.length; i++) { if (uset.has(s[i]) == true) { continue; } else { uset.add(s[i]); } let temp = ""; if (i < s.length - 1) { temp = s.substring(0, i) + s.substring(i + 1); } else { temp = s.substring(0, i); } printAllPermutationsFast(temp, l + s[i]); }} // driver codelet s = "ACBC";s = s.split("").sort().join("");printAllPermutationsFast(s, ""); // This code is contributed by shinjanpatra.</script> ABCC ACBC ACCB BACC BCAC BCCA CABC CACB CBAC CBCA CCAB CCBA Time Complexity – O(n*n!)Auxiliary Space – O(n) Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above jatinrao361 shinjanpatra adityakumar129 permutation Combinatorial Mathematical Mathematical permutation Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python program to get all subsets of given size of a set Distinct permutations of the string | Set 2 Make all combinations of size k Count Derangements (Permutation such that no element appears in its original position) Print all subsets of given size of a set Program for Fibonacci numbers C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7 Merge two sorted arrays
[ { "code": null, "e": 26299, "s": 26271, "text": "\n18 Apr, 2022" }, { "code": null, "e": 26460, "s": 26299, "text": "Given a string that may contain duplicates, write a function to print all permutations of given string such that no permutation is repeated in output.Examples: " }, { "code": null, "e": 26727, "s": 26460, "text": "Input: str[] = \"AB\"\nOutput: AB BA\n\nInput: str[] = \"AA\"\nOutput: AA\n\nInput: str[] = \"ABC\"\nOutput: ABC ACB BAC BCA CBA CAB\n\nInput: str[] = \"ABA\"\nOutput: ABA AAB BAA\n\nInput: str[] = \"ABCA\"\nOutput: AABC AACB ABAC ABCA ACBA ACAB BAAC BACA \n BCAA CABA CAAB CBAA" }, { "code": null, "e": 27004, "s": 26727, "text": "We have discussed an algorithm to print all permutations in below post. It is strongly recommended to refer below post as a prerequisite of this post.Write a C program to print all permutations of a given stringThe algorithm discussed on above link doesn’t handle duplicates. " }, { "code": null, "e": 27008, "s": 27004, "text": "CPP" }, { "code": null, "e": 27010, "s": 27008, "text": "C" }, { "code": "// Program to print all permutations of a// string in sorted order.#include <bits/stdc++.h>using namespace std; /* Following function is needed for library function qsort(). */int compare(const void* a, const void* b){ return (*(char*)a - *(char*)b);} // A utility function two swap two characters a and bvoid swap(char* a, char* b){ char t = *a; *a = *b; *b = t;} // This function finds the index of the smallest character// which is greater than 'first' and is present in str[l..h]int findCeil(char str[], char first, int l, int h){ // initialize index of ceiling element int ceilIndex = l; // Now iterate through rest of the elements and find the // smallest character greater than 'first' for (int i = l + 1; i <= h; i++) if (str[i] > first && str[i] < str[ceilIndex]) ceilIndex = i; return ceilIndex;} // Print all permutations of str in sorted ordervoid sortedPermutations(char str[]){ // Get size of string int size = strlen(str); // Sort the string in increasing order qsort(str, size, sizeof(str[0]), compare); // Print permutations one by one bool isFinished = false; while (!isFinished) { // print this permutation static int x = 1; cout << x++ << \" \" << str << endl; // printf(\"%d %s \\n\", x++, str); // Find the rightmost character which is smaller // than its next character. Let us call it 'first // char' int i; for (i = size - 2; i >= 0; --i) if (str[i] < str[i + 1]) break; // If there is no such character, all are sorted in // decreasing order, means we just printed the last // permutation and we are done. if (i == -1) isFinished = true; else { // Find the ceil of 'first char' in right of // first character. Ceil of a character is the // smallest character greater than it int ceilIndex = findCeil(str, str[i], i + 1, size - 1); // Swap first and second characters swap(&str[i], &str[ceilIndex]); // Sort the string on right of 'first char' qsort(str + i + 1, size - i - 1, sizeof(str[0]), compare); } }} // Driver program to test above functionint main(){ char str[] = \"ACBC\"; sortedPermutations(str); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 29423, "s": 27010, "text": null }, { "code": "// Program to print all permutations of a string in sorted// order.#include <stdbool.h>#include <stdio.h>#include <stdlib.h>#include <string.h> /* Following function is needed for library function qsort(). */int compare(const void* a, const void* b){ return (*(char*)a - *(char*)b);} // A utility function two swap two characters// a and bvoid swap(char* a, char* b){ char t = *a; *a = *b; *b = t;} // This function finds the index of the smallest character// which is greater than 'first' and is present in str[l..h]int findCeil(char str[], char first, int l, int h){ // initialize index of ceiling element int ceilIndex = l; // Now iterate through rest of the elements and find the // smallest character greater than 'first' for (int i = l + 1; i <= h; i++) if (str[i] > first && str[i] < str[ceilIndex]) ceilIndex = i; return ceilIndex;} // Print all permutations of str in sorted ordervoid sortedPermutations(char str[]){ // Get size of string int size = strlen(str); // Sort the string in increasing order qsort(str, size, sizeof(str[0]), compare); // Print permutations one by one bool isFinished = false; while (!isFinished) { // print this permutation static int x = 1; printf(\"%d %s \\n\", x++, str); // Find the rightmost character which is smaller // than its next character. Let us call it 'first // char' int i; for (i = size - 2; i >= 0; --i) if (str[i] < str[i + 1]) break; // If there is no such character, all are sorted in // decreasing order, means we just printed the last // permutation and we are done. if (i == -1) isFinished = true; else { // Find the ceil of 'first char' in right of // first character. Ceil of a character is the // smallest character greater than it int ceilIndex = findCeil(str, str[i], i + 1, size - 1); // Swap first and second characters swap(&str[i], &str[ceilIndex]); // Sort the string on right of 'first char' qsort(str + i + 1, size - i - 1, sizeof(str[0]), compare); } }} // Driver program to test above functionint main(){ char str[] = \"ACBC\"; sortedPermutations(str); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 31823, "s": 29423, "text": null }, { "code": null, "e": 31934, "s": 31823, "text": "1 ABCC \n2 ACBC \n3 ACCB \n4 BACC \n5 BCAC \n6 BCCA \n7 CABC \n8 CACB \n9 CBAC \n10 CBCA \n11 CCAB \n12 CCBA " }, { "code": null, "e": 32041, "s": 31934, "text": "The above code is taken from a comment below by Mr. Lazy.Time Complexity: O(n2 * n!) Auxiliary Space: O(1)" }, { "code": null, "e": 32413, "s": 32041, "text": "The above algorithm is in the time complexity of O(n2 * n!) but we can achieve a better time complexity of O(n!*n) which was there in the case of all distinct characters in the input by some modification in that algorithm. The distinct characters algorithm can be found here – https://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/ " }, { "code": null, "e": 32957, "s": 32413, "text": "Efficient Approach: In our recursive function to find all permutations, we can use unordered_set for taking care of duplicate element remaining in the active string. While iterating over the elements of the string, we will check for that element in the unordered_set and if it found then we will skip that iteration or otherwise we will insert that element into unordered_set. As on an average all the unordered_set operations like insert() and find() are in O(1) time then the algorithm time complexity will not change by using unordered_set." }, { "code": null, "e": 33003, "s": 32957, "text": "The algorithm implementation is as follows – " }, { "code": null, "e": 33007, "s": 33003, "text": "C++" }, { "code": null, "e": 33018, "s": 33007, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; void printAllPermutationsFast(string s, string l){ if (s.length() < 1) cout << l + s << endl; unordered_set<char> uset; for (int i = 0; i < s.length(); i++) { if (uset.find(s[i]) != uset.end()) continue; else uset.insert(s[i]); string temp = \"\"; if (i < s.length() - 1) temp = s.substr(0, i) + s.substr(i + 1); else temp = s.substr(0, i); printAllPermutationsFast(temp, l + s[i]); }} int main(){ string s = \"ACBC\"; sort(s.begin(), s.end()); printAllPermutationsFast(s, \"\"); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 33729, "s": 33018, "text": null }, { "code": "<script> // JavaScript code for the same approach function printAllPermutationsFast(s, l){ if (s.length < 1) { document.write(l + s,\"</br>\"); } let uset = new Set(); for (let i = 0; i < s.length; i++) { if (uset.has(s[i]) == true) { continue; } else { uset.add(s[i]); } let temp = \"\"; if (i < s.length - 1) { temp = s.substring(0, i) + s.substring(i + 1); } else { temp = s.substring(0, i); } printAllPermutationsFast(temp, l + s[i]); }} // driver codelet s = \"ACBC\";s = s.split(\"\").sort().join(\"\");printAllPermutationsFast(s, \"\"); // This code is contributed by shinjanpatra.</script>", "e": 34451, "s": 33729, "text": null }, { "code": null, "e": 34511, "s": 34451, "text": "ABCC\nACBC\nACCB\nBACC\nBCAC\nBCCA\nCABC\nCACB\nCBAC\nCBCA\nCCAB\nCCBA" }, { "code": null, "e": 34560, "s": 34511, "text": "Time Complexity – O(n*n!)Auxiliary Space – O(n) " }, { "code": null, "e": 34685, "s": 34560, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 34697, "s": 34685, "text": "jatinrao361" }, { "code": null, "e": 34710, "s": 34697, "text": "shinjanpatra" }, { "code": null, "e": 34725, "s": 34710, "text": "adityakumar129" }, { "code": null, "e": 34737, "s": 34725, "text": "permutation" }, { "code": null, "e": 34751, "s": 34737, "text": "Combinatorial" }, { "code": null, "e": 34764, "s": 34751, "text": "Mathematical" }, { "code": null, "e": 34777, "s": 34764, "text": "Mathematical" }, { "code": null, "e": 34789, "s": 34777, "text": "permutation" }, { "code": null, "e": 34803, "s": 34789, "text": "Combinatorial" }, { "code": null, "e": 34901, "s": 34803, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34958, "s": 34901, "text": "Python program to get all subsets of given size of a set" }, { "code": null, "e": 35002, "s": 34958, "text": "Distinct permutations of the string | Set 2" }, { "code": null, "e": 35034, "s": 35002, "text": "Make all combinations of size k" }, { "code": null, "e": 35121, "s": 35034, "text": "Count Derangements (Permutation such that no element appears in its original position)" }, { "code": null, "e": 35162, "s": 35121, "text": "Print all subsets of given size of a set" }, { "code": null, "e": 35192, "s": 35162, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 35207, "s": 35192, "text": "C++ Data Types" }, { "code": null, "e": 35250, "s": 35207, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 35269, "s": 35250, "text": "Coin Change | DP-7" } ]
How to Set Git Username and Password in GitBash? - GeeksforGeeks
03 Jan, 2022 Git is an open-source version control system. Git is software that helps to track updates in any folder. It is a DevOps resource used mostly for source code planning. It’s typically used to promote collaboration between coders who are relying on source code together during software development. Speed, the integrity of data, including support for dispersed, non-linear workflows are among the aims. A terminal Git environment is handled by Git Bash (Bash, an acronym for Borne Again Shell). Git Bash replicates a bash terminal on Windows. It allows you to use all git tools or most other typical Unix commands from the command line. If you’re used to Linux and want to preserve your routines, this is a great alternative. Git is usually bundled as one of the elevated GUI applications in Windows settings. Bash is a popular Linux and Mac OS default shell. On a Windows operating system, Git Bash is a package that installs Bash, some standard bash utilities, and Git. The fundamental version control system primitives may be abstracted and hidden by Git GUI s. Git Bash is a Microsoft Windows software that functions as an abstraction shell for the Git command-line experience. A shell is a console application that allows you to interact with your operating system by command prompt. Now let us discuss how to set Git Username and Password in Git Bash Step 1: After the successful installation of Git on your system, you have to right-click wherever you want to open the Git tab. Click on the Git Bash Here icon. Now here we will see the location of where the program is opened when the window opens. Git Bash opened on Desktop. Step 2: In the Git Bash window, type the below command and press enter. This will configure your Username in Git Bash. $ git config --global user.name "GeeksforGeeks" Step 3: After that, you will have to configure your email. For that, type $git config --global user.email "GFGexample@gmail.orgg" Step 4: To set your password, type the below command as depicted: $git config --global user.password "1234321" Step 5: To save the credentials forever, type the below command as depicted: $ git config --global credential.helper store This is how you set git username and password in git bash. To check the inputs, type the below command as depicted: git config --list --show-origin Picked Git How To Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference Between Git Push Origin and Git Push Origin Master Git - Difference Between Git Fetch and Git Pull How to Push Git Branch to Remote? How to Export Eclipse projects to GitHub? Merge Conflicts and How to handle them How to Install PIP on Windows ? How to Find the Wi-Fi Password Using CMD in Windows? How to Align Text in HTML? How to install Jupyter Notebook on Windows? How to filter object array based on attributes?
[ { "code": null, "e": 25795, "s": 25767, "text": "\n03 Jan, 2022" }, { "code": null, "e": 26195, "s": 25795, "text": "Git is an open-source version control system. Git is software that helps to track updates in any folder. It is a DevOps resource used mostly for source code planning. It’s typically used to promote collaboration between coders who are relying on source code together during software development. Speed, the integrity of data, including support for dispersed, non-linear workflows are among the aims." }, { "code": null, "e": 26519, "s": 26195, "text": "A terminal Git environment is handled by Git Bash (Bash, an acronym for Borne Again Shell). Git Bash replicates a bash terminal on Windows. It allows you to use all git tools or most other typical Unix commands from the command line. If you’re used to Linux and want to preserve your routines, this is a great alternative." }, { "code": null, "e": 27083, "s": 26519, "text": "Git is usually bundled as one of the elevated GUI applications in Windows settings. Bash is a popular Linux and Mac OS default shell. On a Windows operating system, Git Bash is a package that installs Bash, some standard bash utilities, and Git. The fundamental version control system primitives may be abstracted and hidden by Git GUI s. Git Bash is a Microsoft Windows software that functions as an abstraction shell for the Git command-line experience. A shell is a console application that allows you to interact with your operating system by command prompt." }, { "code": null, "e": 27151, "s": 27083, "text": "Now let us discuss how to set Git Username and Password in Git Bash" }, { "code": null, "e": 27400, "s": 27151, "text": "Step 1: After the successful installation of Git on your system, you have to right-click wherever you want to open the Git tab. Click on the Git Bash Here icon. Now here we will see the location of where the program is opened when the window opens." }, { "code": null, "e": 27428, "s": 27400, "text": "Git Bash opened on Desktop." }, { "code": null, "e": 27547, "s": 27428, "text": "Step 2: In the Git Bash window, type the below command and press enter. This will configure your Username in Git Bash." }, { "code": null, "e": 27595, "s": 27547, "text": "$ git config --global user.name \"GeeksforGeeks\"" }, { "code": null, "e": 27669, "s": 27595, "text": "Step 3: After that, you will have to configure your email. For that, type" }, { "code": null, "e": 27725, "s": 27669, "text": "$git config --global user.email \"GFGexample@gmail.orgg\"" }, { "code": null, "e": 27791, "s": 27725, "text": "Step 4: To set your password, type the below command as depicted:" }, { "code": null, "e": 27836, "s": 27791, "text": "$git config --global user.password \"1234321\"" }, { "code": null, "e": 27913, "s": 27836, "text": "Step 5: To save the credentials forever, type the below command as depicted:" }, { "code": null, "e": 27959, "s": 27913, "text": "$ git config --global credential.helper store" }, { "code": null, "e": 28018, "s": 27959, "text": "This is how you set git username and password in git bash." }, { "code": null, "e": 28075, "s": 28018, "text": "To check the inputs, type the below command as depicted:" }, { "code": null, "e": 28107, "s": 28075, "text": "git config --list --show-origin" }, { "code": null, "e": 28114, "s": 28107, "text": "Picked" }, { "code": null, "e": 28118, "s": 28114, "text": "Git" }, { "code": null, "e": 28125, "s": 28118, "text": "How To" }, { "code": null, "e": 28223, "s": 28125, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28285, "s": 28223, "text": "Difference Between Git Push Origin and Git Push Origin Master" }, { "code": null, "e": 28333, "s": 28285, "text": "Git - Difference Between Git Fetch and Git Pull" }, { "code": null, "e": 28367, "s": 28333, "text": "How to Push Git Branch to Remote?" }, { "code": null, "e": 28409, "s": 28367, "text": "How to Export Eclipse projects to GitHub?" }, { "code": null, "e": 28448, "s": 28409, "text": "Merge Conflicts and How to handle them" }, { "code": null, "e": 28480, "s": 28448, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28533, "s": 28480, "text": "How to Find the Wi-Fi Password Using CMD in Windows?" }, { "code": null, "e": 28560, "s": 28533, "text": "How to Align Text in HTML?" }, { "code": null, "e": 28604, "s": 28560, "text": "How to install Jupyter Notebook on Windows?" } ]
TypeScript Numbers - GeeksforGeeks
03 Jun, 2020 TypeScript is like JavaScript which supports numerical values as Number objects. The numbers in typescript are used as both integers as well as floating-point values. The number class acts as wrapper and manipulates the numeric literals as they were objects. Syntax: var var_name = new Number(value) Property: MAX_VALUE: It has the largest possible value 1.7976931348623157E+308 in JavaScript. MIN_VALUE: It has the smallest possible value 5E-324 in JavaScript. NaN: This property has Equal to a value that is not a number. NEGATIVE_INFINITY: This has a value that is less than MIN_VALUE. POSITIVE_INFINITY: This has a value that is greater than MAX_VALUE. prototype: This property is used to assign new properties and methods to the Number object. constructor: This property will return the function that created this object’s instance Example: console.log(" Number Properties in TypeScript: "); console.log("Maximum value of a number variable has : " + Number.MAX_VALUE); console.log("The least value of a number variable has: " + Number.MIN_VALUE); console.log("Value of Negative Infinity: " + Number.NEGATIVE_INFINITY); console.log("Value of Negative Infinity:" + Number.POSITIVE_INFINITY); Output: Number Properties in TypeScript: Maximum value of a number variable has: 1.7976931348623157e+308 The least value of a number variable has: 5e-324 Value of Negative Infinity: -Infinity Value of Negative Infinity:Infinity Example of NaN: var day = 0 if( day<=0 || v >7) { day = Number.NaN console.log("Day is "+ day) } else { console.log("Value Accepted..") } Output: Month is NaN Methods: toExponential(): This method will return a number to display in exponential notation. toFixed(): This method will stable the number to the right of the decimal with a specific number of digits. toLocaleString(): This method is used to convert the number into a local specific representation of the number. toPrecision(): It will define total digits to the left and right of the decimal to display of a number. It will also show an error when there is negative precision. toString(): Used to return the string representation of the number in the specified base. valueOf(): This method will return number’s primitive value. Example 1: // The toExponential() var num1 = 2525.30 var val = num1.toExponential(); console.log(val) Output: 2.5253e+3 Example 2: // The toFixed()var num3 = 237.134 console.log("num3.toFixed() is "+num3.toFixed()) console.log("num3.toFixed(2) is "+num3.toFixed(3)) console.log("num3.toFixed(6) is "+num3.toFixed(5)) Output: num3.toFixed() is 237 num3.toFixed(2) is 237.134 num3.toFixed(6) is 237.13400 Example 3: // The toLocaleString()var num = new Number( 237.1346); console.log( num.toLocaleString()); Output: 237.1346 Example 4: // The toPrecision()var num = new Number(5.7645326); console.log(num.toPrecision()); console.log(num.toPrecision(1)); console.log(num.toPrecision(2)); Output: 5.7645326 5 5.7 Example 5: // The toString()var num = new Number(10); console.log(num.toString()); console.log(num.toString(2)); console.log(num.toString(8)); Output: 10 1010 12 Example 6: // The valueOf()var num = new Number(20); console.log(num.valueOf()); Output: 20 TypeScript JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? Remove elements from a JavaScript Array Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26545, "s": 26517, "text": "\n03 Jun, 2020" }, { "code": null, "e": 26804, "s": 26545, "text": "TypeScript is like JavaScript which supports numerical values as Number objects. The numbers in typescript are used as both integers as well as floating-point values. The number class acts as wrapper and manipulates the numeric literals as they were objects." }, { "code": null, "e": 26812, "s": 26804, "text": "Syntax:" }, { "code": null, "e": 26845, "s": 26812, "text": "var var_name = new Number(value)" }, { "code": null, "e": 26855, "s": 26845, "text": "Property:" }, { "code": null, "e": 26939, "s": 26855, "text": "MAX_VALUE: It has the largest possible value 1.7976931348623157E+308 in JavaScript." }, { "code": null, "e": 27007, "s": 26939, "text": "MIN_VALUE: It has the smallest possible value 5E-324 in JavaScript." }, { "code": null, "e": 27069, "s": 27007, "text": "NaN: This property has Equal to a value that is not a number." }, { "code": null, "e": 27134, "s": 27069, "text": "NEGATIVE_INFINITY: This has a value that is less than MIN_VALUE." }, { "code": null, "e": 27202, "s": 27134, "text": "POSITIVE_INFINITY: This has a value that is greater than MAX_VALUE." }, { "code": null, "e": 27294, "s": 27202, "text": "prototype: This property is used to assign new properties and methods to the Number object." }, { "code": null, "e": 27382, "s": 27294, "text": "constructor: This property will return the function that created this object’s instance" }, { "code": null, "e": 27391, "s": 27382, "text": "Example:" }, { "code": "console.log(\" Number Properties in TypeScript: \"); console.log(\"Maximum value of a number variable has : \" + Number.MAX_VALUE); console.log(\"The least value of a number variable has: \" + Number.MIN_VALUE); console.log(\"Value of Negative Infinity: \" + Number.NEGATIVE_INFINITY); console.log(\"Value of Negative Infinity:\" + Number.POSITIVE_INFINITY);", "e": 27869, "s": 27391, "text": null }, { "code": null, "e": 27877, "s": 27869, "text": "Output:" }, { "code": null, "e": 28102, "s": 27877, "text": "Number Properties in TypeScript: \nMaximum value of a number variable has: 1.7976931348623157e+308 \nThe least value of a number variable has: 5e-324 \nValue of Negative Infinity: -Infinity \nValue of Negative Infinity:Infinity" }, { "code": null, "e": 28118, "s": 28102, "text": "Example of NaN:" }, { "code": "var day = 0 if( day<=0 || v >7) { day = Number.NaN console.log(\"Day is \"+ day) } else { console.log(\"Value Accepted..\") }", "e": 28249, "s": 28118, "text": null }, { "code": null, "e": 28257, "s": 28249, "text": "Output:" }, { "code": null, "e": 28270, "s": 28257, "text": "Month is NaN" }, { "code": null, "e": 28279, "s": 28270, "text": "Methods:" }, { "code": null, "e": 28365, "s": 28279, "text": "toExponential(): This method will return a number to display in exponential notation." }, { "code": null, "e": 28473, "s": 28365, "text": "toFixed(): This method will stable the number to the right of the decimal with a specific number of digits." }, { "code": null, "e": 28585, "s": 28473, "text": "toLocaleString(): This method is used to convert the number into a local specific representation of the number." }, { "code": null, "e": 28750, "s": 28585, "text": "toPrecision(): It will define total digits to the left and right of the decimal to display of a number. It will also show an error when there is negative precision." }, { "code": null, "e": 28840, "s": 28750, "text": "toString(): Used to return the string representation of the number in the specified base." }, { "code": null, "e": 28901, "s": 28840, "text": "valueOf(): This method will return number’s primitive value." }, { "code": null, "e": 28912, "s": 28901, "text": "Example 1:" }, { "code": "// The toExponential() var num1 = 2525.30 var val = num1.toExponential(); console.log(val)", "e": 29003, "s": 28912, "text": null }, { "code": null, "e": 29011, "s": 29003, "text": "Output:" }, { "code": null, "e": 29021, "s": 29011, "text": "2.5253e+3" }, { "code": null, "e": 29032, "s": 29021, "text": "Example 2:" }, { "code": "// The toFixed()var num3 = 237.134 console.log(\"num3.toFixed() is \"+num3.toFixed()) console.log(\"num3.toFixed(2) is \"+num3.toFixed(3)) console.log(\"num3.toFixed(6) is \"+num3.toFixed(5))", "e": 29218, "s": 29032, "text": null }, { "code": null, "e": 29226, "s": 29218, "text": "Output:" }, { "code": null, "e": 29306, "s": 29226, "text": "num3.toFixed() is 237 \nnum3.toFixed(2) is 237.134 \nnum3.toFixed(6) is 237.13400" }, { "code": null, "e": 29317, "s": 29306, "text": "Example 3:" }, { "code": "// The toLocaleString()var num = new Number( 237.1346); console.log( num.toLocaleString());", "e": 29409, "s": 29317, "text": null }, { "code": null, "e": 29417, "s": 29409, "text": "Output:" }, { "code": null, "e": 29426, "s": 29417, "text": "237.1346" }, { "code": null, "e": 29437, "s": 29426, "text": "Example 4:" }, { "code": "// The toPrecision()var num = new Number(5.7645326); console.log(num.toPrecision()); console.log(num.toPrecision(1)); console.log(num.toPrecision(2));", "e": 29588, "s": 29437, "text": null }, { "code": null, "e": 29596, "s": 29588, "text": "Output:" }, { "code": null, "e": 29614, "s": 29596, "text": "5.7645326 \n5 \n5.7" }, { "code": null, "e": 29625, "s": 29614, "text": "Example 5:" }, { "code": "// The toString()var num = new Number(10); console.log(num.toString()); console.log(num.toString(2)); console.log(num.toString(8));", "e": 29757, "s": 29625, "text": null }, { "code": null, "e": 29765, "s": 29757, "text": "Output:" }, { "code": null, "e": 29778, "s": 29765, "text": "10 \n1010 \n12" }, { "code": null, "e": 29789, "s": 29778, "text": "Example 6:" }, { "code": "// The valueOf()var num = new Number(20); console.log(num.valueOf());", "e": 29859, "s": 29789, "text": null }, { "code": null, "e": 29867, "s": 29859, "text": "Output:" }, { "code": null, "e": 29870, "s": 29867, "text": "20" }, { "code": null, "e": 29881, "s": 29870, "text": "TypeScript" }, { "code": null, "e": 29892, "s": 29881, "text": "JavaScript" }, { "code": null, "e": 29909, "s": 29892, "text": "Web Technologies" }, { "code": null, "e": 30007, "s": 29909, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30047, "s": 30007, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30108, "s": 30047, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 30149, "s": 30108, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 30171, "s": 30149, "text": "JavaScript | Promises" }, { "code": null, "e": 30225, "s": 30171, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 30265, "s": 30225, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30298, "s": 30265, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30341, "s": 30298, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 30403, "s": 30341, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
React Native View Component - GeeksforGeeks
28 Apr, 2021 In this article, We are going to see how to create a view component in react-native. For this, we are going to use React Native View component. It’s basically a small container that supports layout with flexbox, style, some touch handling, and accessibility controls. View maps directly to the native view equivalent on whatever platform React Native is running on, whether that is a UIView, <div>, android.view, etc. This component is designed to be nested inside other views and can have 0 to many children of any type. Syntax: <view props="value"/> Props for View Component: onStartShouldSetResponder: This prop is a function type it is used to start the view when the user touches the component. accessible: This prop is used to indicate that the view is an accessibility element and the default value is true. accessibilityLabel: This prop used to override the text that’s read by the screen reader when the user interacts with the element. accessibilityHint: This prop helps users understand what will happen when they perform an action on the accessibility element when that result is not clear from the accessibility label. accessibilityRole: This prop is used for communicates the purpose of a component to the user of assistive technology. accessibilityState: It is used to describe the current state of a component to the user of assistive technology. accessibilityValue: This prop is used to represent the current value of a component accessibilityActions: This prop allows assistive technology to programmatically invoke the actions of a component. onAccessibilityAction: This prop is used to invoke when the user performs the accessibility actions. onAccessibilityTap: This prop is used if the system will invoke this function when the user performs the accessibility tap gesture, the accessible prop should be te true. onMagicTap: This prop is used if the system will invoke this function when the user performs the magic tap gesture, the accessible prop should be te true. onAccessibilityEscape: This prop is used if the system will invoke this function when the user performs the escape gesture, the accessible prop should be te true. accessibilityViewIsModal: This prop indicating whether VoiceOver should ignore the elements within views that are siblings of the receiver. accessibilityElementsHidden: This prop indicating whether the accessibility elements contained within this accessibility element are hidden. accessibilityIgnoresInvertColors: This prop indicating this view should or should not be inverted when color inversion is turned on. accessibilityLiveRegion: This prop indicates to accessibility services whether the user should be notified when this view changes. importantForAccessibility: This prop controls how the view is important for accessibility, if it fires accessibility events and if it is reported to accessibility services that query the screen, it works only on Android. hitSlop: This prop defines how far a touch event can start away from the view nativeID: This prop is used to locate this view from native classes. onLayout: This prop is used to activate a View on the mount and on layout changes. onMoveShouldSetResponder: This prop is called for every touch move on the View when it is not the responder. onMoveShouldSetResponderCapture: If a parent View wants to prevent a child View from becoming a responder on a move, then it should have this handler which returns true. onResponderGrant: The prop makes the View responding for touch events. onResponderMove: This prop is to activate the user’s finger moved responder View. onResponderReject: If a responder is already active then this property will block the other one’s request. onResponderRelease: This prop is used to fire the View at the end of the touch. onResponderTerminate: This prop is used to take the responder from the View. onResponderTerminationRequest: If any View wants to be a responder and that time any other View is the responder then this prop will be asking this active View to release its responder. onStartShouldSetResponderCapture: If a parent View wants to prevent a child View from becoming responder on a touch start only then this prop will be used. pointerEvents: This prop is used to control whether the View can be the target of touch events. removeClippedSubviews: This prop is for scrolling content when there are many subviews, most of which are offscreen. style: This prop is used to style the view components. testID: This prop is used to locate this view in end-to-end tests. collapsable: This prop used in Views, which are only used to layout their children or otherwise don’t draw anything may be automatically removed from the native hierarchy as an optimization. needsOffscreenAlphaCompositing: This prop defines that the view needs to rendered off-screen and composited with the alpha in order to preserve correct colors and blending behavior. renderToHardwareTextureAndroid: shouldRasterizeIOS: This prop defines that the View should be rendered as a bitmap before compositing, it is useful on ios devices. nextFocusDown: This prop is to set that the next view to receive focus when the user navigates down. nextFocusForward: This prop is to set that the next view to receive focus when the user navigates forward. nextFocusLeft: This prop is to set that the next view to receive focus when the user navigates left. nextFocusRight: This prop is to set that the next view to receive focus when the user navigates right. nextFocusUp: This prop is to set that the next view to receive focus when the user navigates up. focusable: This prop is used to define the View as should be focusable with a non-touch input device. Now let’s start with the implementation: Step 1: Open your terminal and install expo-cli by the following command.npm install -g expo-cli Step 1: Open your terminal and install expo-cli by the following command. npm install -g expo-cli Step 2: Now create a project by the following command.expo init myapp Step 2: Now create a project by the following command. expo init myapp Step 3: Now go into your project folder i.e. myappcd myapp Step 3: Now go into your project folder i.e. myapp cd myapp Project Structure: Example: Now let’s implement the view component. Here we created a view component inside that component we can put any API but here we will put an alert button and when someone clicks on that button an alert will pop up. App.js import React from 'react';import { StyleSheet, Text, View, Button, Alert } from 'react-native'; export default function App() { // Alert functionconst alert = ()=>{ Alert.alert( "GeeksforGeeks", "A Computer Science Portal", [ { text: "Cancel", }, { text: "Agree", } ] );} return ( <View style={styles.container}> <Button title={"Register"} onPress={alert}/> </View>);} const styles = StyleSheet.create({container: { flex: 1, backgroundColor: 'green', alignItems: 'center', justifyContent: 'center',},}); Start the server by using the following command. npm run android Output: If your emulator did not open automatically then you need to do it manually. First, go to your android studio and run the emulator. Now start the server again. Reference: https://reactnative.dev/docs/view Picked React-Native Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to apply style to parent if it has child with CSS? How to execute PHP code using command line ? Difference Between PUT and PATCH Request REST API (Introduction) How to redirect to another page in ReactJS ?
[ { "code": null, "e": 26169, "s": 26141, "text": "\n28 Apr, 2021" }, { "code": null, "e": 26587, "s": 26169, "text": "In this article, We are going to see how to create a view component in react-native. For this, we are going to use React Native View component. It’s basically a small container that supports layout with flexbox, style, some touch handling, and accessibility controls. View maps directly to the native view equivalent on whatever platform React Native is running on, whether that is a UIView, <div>, android.view, etc." }, { "code": null, "e": 26691, "s": 26587, "text": "This component is designed to be nested inside other views and can have 0 to many children of any type." }, { "code": null, "e": 26699, "s": 26691, "text": "Syntax:" }, { "code": null, "e": 26721, "s": 26699, "text": "<view props=\"value\"/>" }, { "code": null, "e": 26747, "s": 26721, "text": "Props for View Component:" }, { "code": null, "e": 26869, "s": 26747, "text": "onStartShouldSetResponder: This prop is a function type it is used to start the view when the user touches the component." }, { "code": null, "e": 26984, "s": 26869, "text": "accessible: This prop is used to indicate that the view is an accessibility element and the default value is true." }, { "code": null, "e": 27115, "s": 26984, "text": "accessibilityLabel: This prop used to override the text that’s read by the screen reader when the user interacts with the element." }, { "code": null, "e": 27301, "s": 27115, "text": "accessibilityHint: This prop helps users understand what will happen when they perform an action on the accessibility element when that result is not clear from the accessibility label." }, { "code": null, "e": 27419, "s": 27301, "text": "accessibilityRole: This prop is used for communicates the purpose of a component to the user of assistive technology." }, { "code": null, "e": 27532, "s": 27419, "text": "accessibilityState: It is used to describe the current state of a component to the user of assistive technology." }, { "code": null, "e": 27616, "s": 27532, "text": "accessibilityValue: This prop is used to represent the current value of a component" }, { "code": null, "e": 27731, "s": 27616, "text": "accessibilityActions: This prop allows assistive technology to programmatically invoke the actions of a component." }, { "code": null, "e": 27832, "s": 27731, "text": "onAccessibilityAction: This prop is used to invoke when the user performs the accessibility actions." }, { "code": null, "e": 28003, "s": 27832, "text": "onAccessibilityTap: This prop is used if the system will invoke this function when the user performs the accessibility tap gesture, the accessible prop should be te true." }, { "code": null, "e": 28158, "s": 28003, "text": "onMagicTap: This prop is used if the system will invoke this function when the user performs the magic tap gesture, the accessible prop should be te true." }, { "code": null, "e": 28321, "s": 28158, "text": "onAccessibilityEscape: This prop is used if the system will invoke this function when the user performs the escape gesture, the accessible prop should be te true." }, { "code": null, "e": 28461, "s": 28321, "text": "accessibilityViewIsModal: This prop indicating whether VoiceOver should ignore the elements within views that are siblings of the receiver." }, { "code": null, "e": 28602, "s": 28461, "text": "accessibilityElementsHidden: This prop indicating whether the accessibility elements contained within this accessibility element are hidden." }, { "code": null, "e": 28735, "s": 28602, "text": "accessibilityIgnoresInvertColors: This prop indicating this view should or should not be inverted when color inversion is turned on." }, { "code": null, "e": 28866, "s": 28735, "text": "accessibilityLiveRegion: This prop indicates to accessibility services whether the user should be notified when this view changes." }, { "code": null, "e": 29087, "s": 28866, "text": "importantForAccessibility: This prop controls how the view is important for accessibility, if it fires accessibility events and if it is reported to accessibility services that query the screen, it works only on Android." }, { "code": null, "e": 29165, "s": 29087, "text": "hitSlop: This prop defines how far a touch event can start away from the view" }, { "code": null, "e": 29234, "s": 29165, "text": "nativeID: This prop is used to locate this view from native classes." }, { "code": null, "e": 29317, "s": 29234, "text": "onLayout: This prop is used to activate a View on the mount and on layout changes." }, { "code": null, "e": 29426, "s": 29317, "text": "onMoveShouldSetResponder: This prop is called for every touch move on the View when it is not the responder." }, { "code": null, "e": 29596, "s": 29426, "text": "onMoveShouldSetResponderCapture: If a parent View wants to prevent a child View from becoming a responder on a move, then it should have this handler which returns true." }, { "code": null, "e": 29667, "s": 29596, "text": "onResponderGrant: The prop makes the View responding for touch events." }, { "code": null, "e": 29749, "s": 29667, "text": "onResponderMove: This prop is to activate the user’s finger moved responder View." }, { "code": null, "e": 29856, "s": 29749, "text": "onResponderReject: If a responder is already active then this property will block the other one’s request." }, { "code": null, "e": 29936, "s": 29856, "text": "onResponderRelease: This prop is used to fire the View at the end of the touch." }, { "code": null, "e": 30013, "s": 29936, "text": "onResponderTerminate: This prop is used to take the responder from the View." }, { "code": null, "e": 30199, "s": 30013, "text": "onResponderTerminationRequest: If any View wants to be a responder and that time any other View is the responder then this prop will be asking this active View to release its responder." }, { "code": null, "e": 30355, "s": 30199, "text": "onStartShouldSetResponderCapture: If a parent View wants to prevent a child View from becoming responder on a touch start only then this prop will be used." }, { "code": null, "e": 30451, "s": 30355, "text": "pointerEvents: This prop is used to control whether the View can be the target of touch events." }, { "code": null, "e": 30568, "s": 30451, "text": "removeClippedSubviews: This prop is for scrolling content when there are many subviews, most of which are offscreen." }, { "code": null, "e": 30623, "s": 30568, "text": "style: This prop is used to style the view components." }, { "code": null, "e": 30690, "s": 30623, "text": "testID: This prop is used to locate this view in end-to-end tests." }, { "code": null, "e": 30881, "s": 30690, "text": "collapsable: This prop used in Views, which are only used to layout their children or otherwise don’t draw anything may be automatically removed from the native hierarchy as an optimization." }, { "code": null, "e": 31063, "s": 30881, "text": "needsOffscreenAlphaCompositing: This prop defines that the view needs to rendered off-screen and composited with the alpha in order to preserve correct colors and blending behavior." }, { "code": null, "e": 31095, "s": 31063, "text": "renderToHardwareTextureAndroid:" }, { "code": null, "e": 31227, "s": 31095, "text": "shouldRasterizeIOS: This prop defines that the View should be rendered as a bitmap before compositing, it is useful on ios devices." }, { "code": null, "e": 31328, "s": 31227, "text": "nextFocusDown: This prop is to set that the next view to receive focus when the user navigates down." }, { "code": null, "e": 31435, "s": 31328, "text": "nextFocusForward: This prop is to set that the next view to receive focus when the user navigates forward." }, { "code": null, "e": 31536, "s": 31435, "text": "nextFocusLeft: This prop is to set that the next view to receive focus when the user navigates left." }, { "code": null, "e": 31639, "s": 31536, "text": "nextFocusRight: This prop is to set that the next view to receive focus when the user navigates right." }, { "code": null, "e": 31736, "s": 31639, "text": "nextFocusUp: This prop is to set that the next view to receive focus when the user navigates up." }, { "code": null, "e": 31838, "s": 31736, "text": "focusable: This prop is used to define the View as should be focusable with a non-touch input device." }, { "code": null, "e": 31879, "s": 31838, "text": "Now let’s start with the implementation:" }, { "code": null, "e": 31976, "s": 31879, "text": "Step 1: Open your terminal and install expo-cli by the following command.npm install -g expo-cli" }, { "code": null, "e": 32050, "s": 31976, "text": "Step 1: Open your terminal and install expo-cli by the following command." }, { "code": null, "e": 32074, "s": 32050, "text": "npm install -g expo-cli" }, { "code": null, "e": 32144, "s": 32074, "text": "Step 2: Now create a project by the following command.expo init myapp" }, { "code": null, "e": 32199, "s": 32144, "text": "Step 2: Now create a project by the following command." }, { "code": null, "e": 32215, "s": 32199, "text": "expo init myapp" }, { "code": null, "e": 32274, "s": 32215, "text": "Step 3: Now go into your project folder i.e. myappcd myapp" }, { "code": null, "e": 32325, "s": 32274, "text": "Step 3: Now go into your project folder i.e. myapp" }, { "code": null, "e": 32334, "s": 32325, "text": "cd myapp" }, { "code": null, "e": 32353, "s": 32334, "text": "Project Structure:" }, { "code": null, "e": 32574, "s": 32353, "text": "Example: Now let’s implement the view component. Here we created a view component inside that component we can put any API but here we will put an alert button and when someone clicks on that button an alert will pop up." }, { "code": null, "e": 32581, "s": 32574, "text": "App.js" }, { "code": "import React from 'react';import { StyleSheet, Text, View, Button, Alert } from 'react-native'; export default function App() { // Alert functionconst alert = ()=>{ Alert.alert( \"GeeksforGeeks\", \"A Computer Science Portal\", [ { text: \"Cancel\", }, { text: \"Agree\", } ] );} return ( <View style={styles.container}> <Button title={\"Register\"} onPress={alert}/> </View>);} const styles = StyleSheet.create({container: { flex: 1, backgroundColor: 'green', alignItems: 'center', justifyContent: 'center',},});", "e": 33207, "s": 32581, "text": null }, { "code": null, "e": 33256, "s": 33207, "text": "Start the server by using the following command." }, { "code": null, "e": 33272, "s": 33256, "text": "npm run android" }, { "code": null, "e": 33441, "s": 33272, "text": "Output: If your emulator did not open automatically then you need to do it manually. First, go to your android studio and run the emulator. Now start the server again. " }, { "code": null, "e": 33486, "s": 33441, "text": "Reference: https://reactnative.dev/docs/view" }, { "code": null, "e": 33493, "s": 33486, "text": "Picked" }, { "code": null, "e": 33506, "s": 33493, "text": "React-Native" }, { "code": null, "e": 33523, "s": 33506, "text": "Web Technologies" }, { "code": null, "e": 33621, "s": 33523, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33661, "s": 33621, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 33706, "s": 33661, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 33749, "s": 33706, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 33810, "s": 33749, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 33882, "s": 33810, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 33937, "s": 33882, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 33982, "s": 33937, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 34023, "s": 33982, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 34047, "s": 34023, "text": "REST API (Introduction)" } ]
Uninitialized primitive data types in C/C++ - GeeksforGeeks
10 Feb, 2022 What do you think happens when you use an uninitialized primitive data type? Well you may assume that the compiler should assign your primitive type variable with meaningful values like 0 for int, 0.0 for float. What about char data type?Let’s find the answer to that by running the code in the IDE. CPP #include <iostream> using namespace std; int main(){ // The following primitive data type variables will not // be initialized with any default values char ch; float f; int i; double d; long l; cout << ch << endl; cout << f << endl; cout << i << endl; cout << d << endl; cout << l << endl; return 0;} Output in GFGs IDE: 5.88052e-39 0 6.9529e-310 0 Output in Codechef IDE: 0 0 0 0 Output on my machine: 1.4013e-045 0 2.96439e-323 0 Why C/C++ compiler does not initialize variables with default values? “One of the things that has kept C++ viable is the zero-overhead rule: What you don’t use, you don’t pay for.” -Stroustrup. The overhead of initializing a stack variable is costly as it hampers the speed of execution, therefore these variables can contain indeterminate values or garbage values as memory space is provided when we define a data type. It is considered a best practice to initialize a primitive data type variable before using it in code. abhijeetsinhasmith C-Data Types cpp-data-types cpp-puzzle C Language C++ C++ Programs CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C Exception Handling in C++ Multithreading in C 'this' pointer in C++ Arrow operator -> in C/C++ with Examples Vector in C++ STL Initialize a vector in C++ (6 different ways) Inheritance in C++ Map in C++ Standard Template Library (STL) C++ Classes and Objects
[ { "code": null, "e": 25479, "s": 25451, "text": "\n10 Feb, 2022" }, { "code": null, "e": 25780, "s": 25479, "text": "What do you think happens when you use an uninitialized primitive data type? Well you may assume that the compiler should assign your primitive type variable with meaningful values like 0 for int, 0.0 for float. What about char data type?Let’s find the answer to that by running the code in the IDE. " }, { "code": null, "e": 25784, "s": 25780, "text": "CPP" }, { "code": "#include <iostream> using namespace std; int main(){ // The following primitive data type variables will not // be initialized with any default values char ch; float f; int i; double d; long l; cout << ch << endl; cout << f << endl; cout << i << endl; cout << d << endl; cout << l << endl; return 0;}", "e": 26126, "s": 25784, "text": null }, { "code": null, "e": 26148, "s": 26126, "text": "Output in GFGs IDE: " }, { "code": null, "e": 26176, "s": 26148, "text": "5.88052e-39\n0\n6.9529e-310\n0" }, { "code": null, "e": 26202, "s": 26176, "text": "Output in Codechef IDE: " }, { "code": null, "e": 26210, "s": 26202, "text": "0\n0\n0\n0" }, { "code": null, "e": 26234, "s": 26210, "text": "Output on my machine: " }, { "code": null, "e": 26263, "s": 26234, "text": "1.4013e-045\n0\n2.96439e-323\n0" }, { "code": null, "e": 26788, "s": 26263, "text": "Why C/C++ compiler does not initialize variables with default values? “One of the things that has kept C++ viable is the zero-overhead rule: What you don’t use, you don’t pay for.” -Stroustrup. The overhead of initializing a stack variable is costly as it hampers the speed of execution, therefore these variables can contain indeterminate values or garbage values as memory space is provided when we define a data type. It is considered a best practice to initialize a primitive data type variable before using it in code. " }, { "code": null, "e": 26807, "s": 26788, "text": "abhijeetsinhasmith" }, { "code": null, "e": 26820, "s": 26807, "text": "C-Data Types" }, { "code": null, "e": 26835, "s": 26820, "text": "cpp-data-types" }, { "code": null, "e": 26846, "s": 26835, "text": "cpp-puzzle" }, { "code": null, "e": 26857, "s": 26846, "text": "C Language" }, { "code": null, "e": 26861, "s": 26857, "text": "C++" }, { "code": null, "e": 26874, "s": 26861, "text": "C++ Programs" }, { "code": null, "e": 26878, "s": 26874, "text": "CPP" }, { "code": null, "e": 26976, "s": 26878, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27014, "s": 26976, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 27040, "s": 27014, "text": "Exception Handling in C++" }, { "code": null, "e": 27060, "s": 27040, "text": "Multithreading in C" }, { "code": null, "e": 27082, "s": 27060, "text": "'this' pointer in C++" }, { "code": null, "e": 27123, "s": 27082, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 27141, "s": 27123, "text": "Vector in C++ STL" }, { "code": null, "e": 27187, "s": 27141, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 27206, "s": 27187, "text": "Inheritance in C++" }, { "code": null, "e": 27249, "s": 27206, "text": "Map in C++ Standard Template Library (STL)" } ]
How to add float numbers using JavaScript ? - GeeksforGeeks
11 Dec, 2019 Given two or more numbers and the task is to get the float addition in the desired format with the help of JavaScript. There are two methods to solve this problem which are discussed below: Approach 1: Given two or more numbers to sum up the float numbers. Use parseFloat() and toFixed() method to format the output accordingly. Example: This example implements the above approach. <!DOCTYPE HTML> <html> <head> <title> Float sum with JavaScript. </title></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "gfg_Run()"> Click Here </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); el_up.innerHTML = "Click on the button to get the" + " sum in desired format."; var val = parseFloat('2.3')+parseFloat('2.4'); el_down.innerHTML = "2.3 + 2.4 = " + val; function gfg_Run() { el_down.innerHTML = "2.3 + 2.4 = " + (parseFloat('2.3') + parseFloat('2.4')).toFixed(2); } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: Approach 2: Given two or more numbers to sum up the float numbers. Use parseFloat() and Math.round() method to get the desired output. Example: This example implements the above approach. <!DOCTYPE HTML> <html> <head> <title> Float sum with javascript. </title></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "gfg_Run()"> Click Here </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); el_up.innerHTML = "Click on the button to get the" + " sum in desired format."; var val = parseFloat('2.3')+parseFloat('2.4'); el_down.innerHTML = "2.3 + 2.4 = " + val; function gfg_Run() { el_down.innerHTML = "2.3 + 2.4 = " + Math.round((parseFloat('2.3') + parseFloat('2.4'))*100)/100; } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: javascript-math JavaScript-Misc JavaScript-Numbers JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 39215, "s": 39187, "text": "\n11 Dec, 2019" }, { "code": null, "e": 39405, "s": 39215, "text": "Given two or more numbers and the task is to get the float addition in the desired format with the help of JavaScript. There are two methods to solve this problem which are discussed below:" }, { "code": null, "e": 39417, "s": 39405, "text": "Approach 1:" }, { "code": null, "e": 39472, "s": 39417, "text": "Given two or more numbers to sum up the float numbers." }, { "code": null, "e": 39544, "s": 39472, "text": "Use parseFloat() and toFixed() method to format the output accordingly." }, { "code": null, "e": 39597, "s": 39544, "text": "Example: This example implements the above approach." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> Float sum with JavaScript. </title></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button onclick = \"gfg_Run()\"> Click Here </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); el_up.innerHTML = \"Click on the button to get the\" + \" sum in desired format.\"; var val = parseFloat('2.3')+parseFloat('2.4'); el_down.innerHTML = \"2.3 + 2.4 = \" + val; function gfg_Run() { el_down.innerHTML = \"2.3 + 2.4 = \" + (parseFloat('2.3') + parseFloat('2.4')).toFixed(2); } </script> </body> </html>", "e": 40659, "s": 39597, "text": null }, { "code": null, "e": 40667, "s": 40659, "text": "Output:" }, { "code": null, "e": 40698, "s": 40667, "text": "Before clicking on the button:" }, { "code": null, "e": 40728, "s": 40698, "text": "After clicking on the button:" }, { "code": null, "e": 40740, "s": 40728, "text": "Approach 2:" }, { "code": null, "e": 40795, "s": 40740, "text": "Given two or more numbers to sum up the float numbers." }, { "code": null, "e": 40863, "s": 40795, "text": "Use parseFloat() and Math.round() method to get the desired output." }, { "code": null, "e": 40916, "s": 40863, "text": "Example: This example implements the above approach." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> Float sum with javascript. </title></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button onclick = \"gfg_Run()\"> Click Here </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); el_up.innerHTML = \"Click on the button to get the\" + \" sum in desired format.\"; var val = parseFloat('2.3')+parseFloat('2.4'); el_down.innerHTML = \"2.3 + 2.4 = \" + val; function gfg_Run() { el_down.innerHTML = \"2.3 + 2.4 = \" + Math.round((parseFloat('2.3') + parseFloat('2.4'))*100)/100; } </script> </body> </html>", "e": 41978, "s": 40916, "text": null }, { "code": null, "e": 41986, "s": 41978, "text": "Output:" }, { "code": null, "e": 42017, "s": 41986, "text": "Before clicking on the button:" }, { "code": null, "e": 42047, "s": 42017, "text": "After clicking on the button:" }, { "code": null, "e": 42063, "s": 42047, "text": "javascript-math" }, { "code": null, "e": 42079, "s": 42063, "text": "JavaScript-Misc" }, { "code": null, "e": 42098, "s": 42079, "text": "JavaScript-Numbers" }, { "code": null, "e": 42109, "s": 42098, "text": "JavaScript" }, { "code": null, "e": 42126, "s": 42109, "text": "Web Technologies" }, { "code": null, "e": 42153, "s": 42126, "text": "Web technologies Questions" }, { "code": null, "e": 42251, "s": 42153, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42291, "s": 42251, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 42336, "s": 42291, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 42397, "s": 42336, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 42469, "s": 42397, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 42538, "s": 42469, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 42578, "s": 42538, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 42611, "s": 42578, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 42656, "s": 42611, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 42699, "s": 42656, "text": "How to fetch data from an API in ReactJS ?" } ]
Java.util.ArrayList.addall() method in Java - GeeksforGeeks
26 Nov, 2018 Below are the addAll() methods of ArrayList in Java: boolean addAll(Collection c) : This method appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection’s Iterator. The behavior of this operation is undefined if the specified collection is modified while the operation is in progress(implies that the behavior of this call is undefined if the specified collection is this list, and this list is nonempty).Parameters: c : This is the collection containing elements to be added to this list. Exception: NullPointerException : If the specified collection is null// Java program to illustrate// boolean addAll(Collection c)import java.io.*;import java.util.ArrayList; public class ArrayListDemo { public static void main(String args[]) { // create an empty array list1 with initial // capacity as 5 ArrayList<Integer> arrlist1 = new ArrayList<Integer>(5); // use add() method to add elements in the list arrlist1.add(12); arrlist1.add(20); arrlist1.add(45); // prints all the elements available in list1 System.out.println("Printing list1:"); for (Integer number : arrlist1) System.out.println("Number = " + number); // create an empty array list2 with an initial // capacity ArrayList<Integer> arrlist2 = new ArrayList<Integer>(5); // use add() method to add elements in list2 arrlist2.add(25); arrlist2.add(30); arrlist2.add(31); arrlist2.add(35); // let us print all the elements available in // list2 System.out.println("Printing list2:"); for (Integer number : arrlist2) System.out.println("Number = " + number); // inserting all elements, list2 will get printed // after list1 arrlist1.addAll(arrlist2); System.out.println("Printing all the elements"); // let us print all the elements available in // list1 for (Integer number : arrlist1) System.out.println("Number = " + number); }}Output:Printing list1: Number = 12 Number = 20 Number = 45 Printing list2: Number = 25 Number = 30 Number = 31 Number = 35 Printing all the elements Number = 12 Number = 20 Number = 45 Number = 25 Number = 30 Number = 31 Number = 35 boolean addAll(int index, Collection c):This method inserts all of the elements in the specified collection into this list, starting at the specified position. It shifts the element currently at that position (if any) and any subsequent elements to the right (increases their indices). The new elements will appear in the list in the order that they are returned by the specified collection’s iterator.Parameters: index : The index at which to insert the first element from the specified collection. c : This is the collection containing elements to be added to this list. Exception: IndexOutOfBoundsException : If the index is out of range NullPointerException : If the specified collection is null// Java program to illustrate// boolean addAll(int index, Collection c)import java.io.*;import java.util.ArrayList; public class ArrayListDemo { public static void main(String args[]) { // create an empty array list1 with initial // capacity 5 ArrayList<Integer> arrlist = new ArrayList<Integer>(5); // using add() method to add elements in the // list arrlist.add(12); arrlist.add(20); arrlist.add(45); // prints all the elements available in list1 System.out.println("Printing list1:"); for (Integer number : arrlist) System.out.println("Number = " + number); // create an empty array list2 with an initial // capacity ArrayList<Integer> arrlist2 = new ArrayList<Integer>(5); // use add() method to add elements in list2 arrlist2.add(25); arrlist2.add(30); arrlist2.add(31); arrlist2.add(35); // prints all the elements available in list2 System.out.println("Printing list2:"); for (Integer number : arrlist2) System.out.println("Number = " + number); // inserting all elements of list2 at third // position arrlist.addAll(2, arrlist2); System.out.println("Printing all the elements"); // prints all the elements available in list1 for (Integer number : arrlist) System.out.println("Number = " + number); }}Output:Printing list1: Number = 12 Number = 20 Number = 45 Printing list2: Number = 25 Number = 30 Number = 31 Number = 35 Printing all the elements Number = 12 Number = 20 Number = 25 Number = 30 Number = 31 Number = 35 Number = 45 boolean addAll(Collection c) : This method appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection’s Iterator. The behavior of this operation is undefined if the specified collection is modified while the operation is in progress(implies that the behavior of this call is undefined if the specified collection is this list, and this list is nonempty).Parameters: c : This is the collection containing elements to be added to this list. Exception: NullPointerException : If the specified collection is null// Java program to illustrate// boolean addAll(Collection c)import java.io.*;import java.util.ArrayList; public class ArrayListDemo { public static void main(String args[]) { // create an empty array list1 with initial // capacity as 5 ArrayList<Integer> arrlist1 = new ArrayList<Integer>(5); // use add() method to add elements in the list arrlist1.add(12); arrlist1.add(20); arrlist1.add(45); // prints all the elements available in list1 System.out.println("Printing list1:"); for (Integer number : arrlist1) System.out.println("Number = " + number); // create an empty array list2 with an initial // capacity ArrayList<Integer> arrlist2 = new ArrayList<Integer>(5); // use add() method to add elements in list2 arrlist2.add(25); arrlist2.add(30); arrlist2.add(31); arrlist2.add(35); // let us print all the elements available in // list2 System.out.println("Printing list2:"); for (Integer number : arrlist2) System.out.println("Number = " + number); // inserting all elements, list2 will get printed // after list1 arrlist1.addAll(arrlist2); System.out.println("Printing all the elements"); // let us print all the elements available in // list1 for (Integer number : arrlist1) System.out.println("Number = " + number); }}Output:Printing list1: Number = 12 Number = 20 Number = 45 Printing list2: Number = 25 Number = 30 Number = 31 Number = 35 Printing all the elements Number = 12 Number = 20 Number = 45 Number = 25 Number = 30 Number = 31 Number = 35 boolean addAll(int index, Collection c):This method inserts all of the elements in the specified collection into this list, starting at the specified position. It shifts the element currently at that position (if any) and any subsequent elements to the right (increases their indices). The new elements will appear in the list in the order that they are returned by the specified collection’s iterator.Parameters: index : The index at which to insert the first element from the specified collection. c : This is the collection containing elements to be added to this list. Exception: IndexOutOfBoundsException : If the index is out of range NullPointerException : If the specified collection is null// Java program to illustrate// boolean addAll(int index, Collection c)import java.io.*;import java.util.ArrayList; public class ArrayListDemo { public static void main(String args[]) { // create an empty array list1 with initial // capacity 5 ArrayList<Integer> arrlist = new ArrayList<Integer>(5); // using add() method to add elements in the // list arrlist.add(12); arrlist.add(20); arrlist.add(45); // prints all the elements available in list1 System.out.println("Printing list1:"); for (Integer number : arrlist) System.out.println("Number = " + number); // create an empty array list2 with an initial // capacity ArrayList<Integer> arrlist2 = new ArrayList<Integer>(5); // use add() method to add elements in list2 arrlist2.add(25); arrlist2.add(30); arrlist2.add(31); arrlist2.add(35); // prints all the elements available in list2 System.out.println("Printing list2:"); for (Integer number : arrlist2) System.out.println("Number = " + number); // inserting all elements of list2 at third // position arrlist.addAll(2, arrlist2); System.out.println("Printing all the elements"); // prints all the elements available in list1 for (Integer number : arrlist) System.out.println("Number = " + number); }}Output:Printing list1: Number = 12 Number = 20 Number = 45 Printing list2: Number = 25 Number = 30 Number = 31 Number = 35 Printing all the elements Number = 12 Number = 20 Number = 25 Number = 30 Number = 31 Number = 35 Number = 45 Parameters: c : This is the collection containing elements to be added to this list. Exception: NullPointerException : If the specified collection is null // Java program to illustrate// boolean addAll(Collection c)import java.io.*;import java.util.ArrayList; public class ArrayListDemo { public static void main(String args[]) { // create an empty array list1 with initial // capacity as 5 ArrayList<Integer> arrlist1 = new ArrayList<Integer>(5); // use add() method to add elements in the list arrlist1.add(12); arrlist1.add(20); arrlist1.add(45); // prints all the elements available in list1 System.out.println("Printing list1:"); for (Integer number : arrlist1) System.out.println("Number = " + number); // create an empty array list2 with an initial // capacity ArrayList<Integer> arrlist2 = new ArrayList<Integer>(5); // use add() method to add elements in list2 arrlist2.add(25); arrlist2.add(30); arrlist2.add(31); arrlist2.add(35); // let us print all the elements available in // list2 System.out.println("Printing list2:"); for (Integer number : arrlist2) System.out.println("Number = " + number); // inserting all elements, list2 will get printed // after list1 arrlist1.addAll(arrlist2); System.out.println("Printing all the elements"); // let us print all the elements available in // list1 for (Integer number : arrlist1) System.out.println("Number = " + number); }} Output:Printing list1: Number = 12 Number = 20 Number = 45 Printing list2: Number = 25 Number = 30 Number = 31 Number = 35 Printing all the elements Number = 12 Number = 20 Number = 45 Number = 25 Number = 30 Number = 31 Number = 35 boolean addAll(int index, Collection c):This method inserts all of the elements in the specified collection into this list, starting at the specified position. It shifts the element currently at that position (if any) and any subsequent elements to the right (increases their indices). The new elements will appear in the list in the order that they are returned by the specified collection’s iterator. Parameters: index : The index at which to insert the first element from the specified collection. c : This is the collection containing elements to be added to this list. Exception: IndexOutOfBoundsException : If the index is out of range NullPointerException : If the specified collection is null // Java program to illustrate// boolean addAll(int index, Collection c)import java.io.*;import java.util.ArrayList; public class ArrayListDemo { public static void main(String args[]) { // create an empty array list1 with initial // capacity 5 ArrayList<Integer> arrlist = new ArrayList<Integer>(5); // using add() method to add elements in the // list arrlist.add(12); arrlist.add(20); arrlist.add(45); // prints all the elements available in list1 System.out.println("Printing list1:"); for (Integer number : arrlist) System.out.println("Number = " + number); // create an empty array list2 with an initial // capacity ArrayList<Integer> arrlist2 = new ArrayList<Integer>(5); // use add() method to add elements in list2 arrlist2.add(25); arrlist2.add(30); arrlist2.add(31); arrlist2.add(35); // prints all the elements available in list2 System.out.println("Printing list2:"); for (Integer number : arrlist2) System.out.println("Number = " + number); // inserting all elements of list2 at third // position arrlist.addAll(2, arrlist2); System.out.println("Printing all the elements"); // prints all the elements available in list1 for (Integer number : arrlist) System.out.println("Number = " + number); }} Output:Printing list1: Number = 12 Number = 20 Number = 45 Printing list2: Number = 25 Number = 30 Number = 31 Number = 35 Printing all the elements Number = 12 Number = 20 Number = 25 Number = 30 Number = 31 Number = 35 Number = 45 This article is contributed by Shambhavi Singh. 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. Java - util package Java-ArrayList Java-Collections Java-Functions Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Interfaces in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Singleton Class in Java Multidimensional Arrays in Java Multithreading in Java Collections in Java Initializing a List in Java
[ { "code": null, "e": 25683, "s": 25655, "text": "\n26 Nov, 2018" }, { "code": null, "e": 25736, "s": 25683, "text": "Below are the addAll() methods of ArrayList in Java:" }, { "code": null, "e": 30618, "s": 25736, "text": "boolean addAll(Collection c) : This method appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection’s Iterator. The behavior of this operation is undefined if the specified collection is modified while the operation is in progress(implies that the behavior of this call is undefined if the specified collection is this list, and this list is nonempty).Parameters:\nc : This is the collection containing elements to be added to this list.\nException:\nNullPointerException : If the specified collection is null// Java program to illustrate// boolean addAll(Collection c)import java.io.*;import java.util.ArrayList; public class ArrayListDemo { public static void main(String args[]) { // create an empty array list1 with initial // capacity as 5 ArrayList<Integer> arrlist1 = new ArrayList<Integer>(5); // use add() method to add elements in the list arrlist1.add(12); arrlist1.add(20); arrlist1.add(45); // prints all the elements available in list1 System.out.println(\"Printing list1:\"); for (Integer number : arrlist1) System.out.println(\"Number = \" + number); // create an empty array list2 with an initial // capacity ArrayList<Integer> arrlist2 = new ArrayList<Integer>(5); // use add() method to add elements in list2 arrlist2.add(25); arrlist2.add(30); arrlist2.add(31); arrlist2.add(35); // let us print all the elements available in // list2 System.out.println(\"Printing list2:\"); for (Integer number : arrlist2) System.out.println(\"Number = \" + number); // inserting all elements, list2 will get printed // after list1 arrlist1.addAll(arrlist2); System.out.println(\"Printing all the elements\"); // let us print all the elements available in // list1 for (Integer number : arrlist1) System.out.println(\"Number = \" + number); }}Output:Printing list1:\nNumber = 12\nNumber = 20\nNumber = 45\nPrinting list2:\nNumber = 25\nNumber = 30\nNumber = 31\nNumber = 35\nPrinting all the elements\nNumber = 12\nNumber = 20\nNumber = 45\nNumber = 25\nNumber = 30\nNumber = 31\nNumber = 35\nboolean addAll(int index, Collection c):This method inserts all of the elements in the specified collection into this list, starting at the specified position. It shifts the element currently at that position (if any) and any subsequent elements to the right (increases their indices). The new elements will appear in the list in the order that they are returned by the specified collection’s iterator.Parameters:\nindex : The index at which to insert the first element from the specified collection.\nc : This is the collection containing elements to be added to this list.\nException:\nIndexOutOfBoundsException : If the index is out of range\nNullPointerException : If the specified collection is null// Java program to illustrate// boolean addAll(int index, Collection c)import java.io.*;import java.util.ArrayList; public class ArrayListDemo { public static void main(String args[]) { // create an empty array list1 with initial // capacity 5 ArrayList<Integer> arrlist = new ArrayList<Integer>(5); // using add() method to add elements in the // list arrlist.add(12); arrlist.add(20); arrlist.add(45); // prints all the elements available in list1 System.out.println(\"Printing list1:\"); for (Integer number : arrlist) System.out.println(\"Number = \" + number); // create an empty array list2 with an initial // capacity ArrayList<Integer> arrlist2 = new ArrayList<Integer>(5); // use add() method to add elements in list2 arrlist2.add(25); arrlist2.add(30); arrlist2.add(31); arrlist2.add(35); // prints all the elements available in list2 System.out.println(\"Printing list2:\"); for (Integer number : arrlist2) System.out.println(\"Number = \" + number); // inserting all elements of list2 at third // position arrlist.addAll(2, arrlist2); System.out.println(\"Printing all the elements\"); // prints all the elements available in list1 for (Integer number : arrlist) System.out.println(\"Number = \" + number); }}Output:Printing list1:\nNumber = 12\nNumber = 20\nNumber = 45\nPrinting list2:\nNumber = 25\nNumber = 30\nNumber = 31\nNumber = 35\nPrinting all the elements\nNumber = 12\nNumber = 20\nNumber = 25\nNumber = 30\nNumber = 31\nNumber = 35\nNumber = 45\n" }, { "code": null, "e": 35500, "s": 30618, "text": "boolean addAll(Collection c) : This method appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection’s Iterator. The behavior of this operation is undefined if the specified collection is modified while the operation is in progress(implies that the behavior of this call is undefined if the specified collection is this list, and this list is nonempty).Parameters:\nc : This is the collection containing elements to be added to this list.\nException:\nNullPointerException : If the specified collection is null// Java program to illustrate// boolean addAll(Collection c)import java.io.*;import java.util.ArrayList; public class ArrayListDemo { public static void main(String args[]) { // create an empty array list1 with initial // capacity as 5 ArrayList<Integer> arrlist1 = new ArrayList<Integer>(5); // use add() method to add elements in the list arrlist1.add(12); arrlist1.add(20); arrlist1.add(45); // prints all the elements available in list1 System.out.println(\"Printing list1:\"); for (Integer number : arrlist1) System.out.println(\"Number = \" + number); // create an empty array list2 with an initial // capacity ArrayList<Integer> arrlist2 = new ArrayList<Integer>(5); // use add() method to add elements in list2 arrlist2.add(25); arrlist2.add(30); arrlist2.add(31); arrlist2.add(35); // let us print all the elements available in // list2 System.out.println(\"Printing list2:\"); for (Integer number : arrlist2) System.out.println(\"Number = \" + number); // inserting all elements, list2 will get printed // after list1 arrlist1.addAll(arrlist2); System.out.println(\"Printing all the elements\"); // let us print all the elements available in // list1 for (Integer number : arrlist1) System.out.println(\"Number = \" + number); }}Output:Printing list1:\nNumber = 12\nNumber = 20\nNumber = 45\nPrinting list2:\nNumber = 25\nNumber = 30\nNumber = 31\nNumber = 35\nPrinting all the elements\nNumber = 12\nNumber = 20\nNumber = 45\nNumber = 25\nNumber = 30\nNumber = 31\nNumber = 35\nboolean addAll(int index, Collection c):This method inserts all of the elements in the specified collection into this list, starting at the specified position. It shifts the element currently at that position (if any) and any subsequent elements to the right (increases their indices). The new elements will appear in the list in the order that they are returned by the specified collection’s iterator.Parameters:\nindex : The index at which to insert the first element from the specified collection.\nc : This is the collection containing elements to be added to this list.\nException:\nIndexOutOfBoundsException : If the index is out of range\nNullPointerException : If the specified collection is null// Java program to illustrate// boolean addAll(int index, Collection c)import java.io.*;import java.util.ArrayList; public class ArrayListDemo { public static void main(String args[]) { // create an empty array list1 with initial // capacity 5 ArrayList<Integer> arrlist = new ArrayList<Integer>(5); // using add() method to add elements in the // list arrlist.add(12); arrlist.add(20); arrlist.add(45); // prints all the elements available in list1 System.out.println(\"Printing list1:\"); for (Integer number : arrlist) System.out.println(\"Number = \" + number); // create an empty array list2 with an initial // capacity ArrayList<Integer> arrlist2 = new ArrayList<Integer>(5); // use add() method to add elements in list2 arrlist2.add(25); arrlist2.add(30); arrlist2.add(31); arrlist2.add(35); // prints all the elements available in list2 System.out.println(\"Printing list2:\"); for (Integer number : arrlist2) System.out.println(\"Number = \" + number); // inserting all elements of list2 at third // position arrlist.addAll(2, arrlist2); System.out.println(\"Printing all the elements\"); // prints all the elements available in list1 for (Integer number : arrlist) System.out.println(\"Number = \" + number); }}Output:Printing list1:\nNumber = 12\nNumber = 20\nNumber = 45\nPrinting list2:\nNumber = 25\nNumber = 30\nNumber = 31\nNumber = 35\nPrinting all the elements\nNumber = 12\nNumber = 20\nNumber = 25\nNumber = 30\nNumber = 31\nNumber = 35\nNumber = 45\n" }, { "code": null, "e": 35655, "s": 35500, "text": "Parameters:\nc : This is the collection containing elements to be added to this list.\nException:\nNullPointerException : If the specified collection is null" }, { "code": "// Java program to illustrate// boolean addAll(Collection c)import java.io.*;import java.util.ArrayList; public class ArrayListDemo { public static void main(String args[]) { // create an empty array list1 with initial // capacity as 5 ArrayList<Integer> arrlist1 = new ArrayList<Integer>(5); // use add() method to add elements in the list arrlist1.add(12); arrlist1.add(20); arrlist1.add(45); // prints all the elements available in list1 System.out.println(\"Printing list1:\"); for (Integer number : arrlist1) System.out.println(\"Number = \" + number); // create an empty array list2 with an initial // capacity ArrayList<Integer> arrlist2 = new ArrayList<Integer>(5); // use add() method to add elements in list2 arrlist2.add(25); arrlist2.add(30); arrlist2.add(31); arrlist2.add(35); // let us print all the elements available in // list2 System.out.println(\"Printing list2:\"); for (Integer number : arrlist2) System.out.println(\"Number = \" + number); // inserting all elements, list2 will get printed // after list1 arrlist1.addAll(arrlist2); System.out.println(\"Printing all the elements\"); // let us print all the elements available in // list1 for (Integer number : arrlist1) System.out.println(\"Number = \" + number); }}", "e": 37231, "s": 35655, "text": null }, { "code": null, "e": 37465, "s": 37231, "text": "Output:Printing list1:\nNumber = 12\nNumber = 20\nNumber = 45\nPrinting list2:\nNumber = 25\nNumber = 30\nNumber = 31\nNumber = 35\nPrinting all the elements\nNumber = 12\nNumber = 20\nNumber = 45\nNumber = 25\nNumber = 30\nNumber = 31\nNumber = 35\n" }, { "code": null, "e": 37868, "s": 37465, "text": "boolean addAll(int index, Collection c):This method inserts all of the elements in the specified collection into this list, starting at the specified position. It shifts the element currently at that position (if any) and any subsequent elements to the right (increases their indices). The new elements will appear in the list in the order that they are returned by the specified collection’s iterator." }, { "code": null, "e": 38166, "s": 37868, "text": "Parameters:\nindex : The index at which to insert the first element from the specified collection.\nc : This is the collection containing elements to be added to this list.\nException:\nIndexOutOfBoundsException : If the index is out of range\nNullPointerException : If the specified collection is null" }, { "code": "// Java program to illustrate// boolean addAll(int index, Collection c)import java.io.*;import java.util.ArrayList; public class ArrayListDemo { public static void main(String args[]) { // create an empty array list1 with initial // capacity 5 ArrayList<Integer> arrlist = new ArrayList<Integer>(5); // using add() method to add elements in the // list arrlist.add(12); arrlist.add(20); arrlist.add(45); // prints all the elements available in list1 System.out.println(\"Printing list1:\"); for (Integer number : arrlist) System.out.println(\"Number = \" + number); // create an empty array list2 with an initial // capacity ArrayList<Integer> arrlist2 = new ArrayList<Integer>(5); // use add() method to add elements in list2 arrlist2.add(25); arrlist2.add(30); arrlist2.add(31); arrlist2.add(35); // prints all the elements available in list2 System.out.println(\"Printing list2:\"); for (Integer number : arrlist2) System.out.println(\"Number = \" + number); // inserting all elements of list2 at third // position arrlist.addAll(2, arrlist2); System.out.println(\"Printing all the elements\"); // prints all the elements available in list1 for (Integer number : arrlist) System.out.println(\"Number = \" + number); }}", "e": 39714, "s": 38166, "text": null }, { "code": null, "e": 39948, "s": 39714, "text": "Output:Printing list1:\nNumber = 12\nNumber = 20\nNumber = 45\nPrinting list2:\nNumber = 25\nNumber = 30\nNumber = 31\nNumber = 35\nPrinting all the elements\nNumber = 12\nNumber = 20\nNumber = 25\nNumber = 30\nNumber = 31\nNumber = 35\nNumber = 45\n" }, { "code": null, "e": 40251, "s": 39948, "text": "This article is contributed by Shambhavi Singh. 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." }, { "code": null, "e": 40376, "s": 40251, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 40396, "s": 40376, "text": "Java - util package" }, { "code": null, "e": 40411, "s": 40396, "text": "Java-ArrayList" }, { "code": null, "e": 40428, "s": 40411, "text": "Java-Collections" }, { "code": null, "e": 40443, "s": 40428, "text": "Java-Functions" }, { "code": null, "e": 40448, "s": 40443, "text": "Java" }, { "code": null, "e": 40453, "s": 40448, "text": "Java" }, { "code": null, "e": 40470, "s": 40453, "text": "Java-Collections" }, { "code": null, "e": 40568, "s": 40470, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40583, "s": 40568, "text": "Stream In Java" }, { "code": null, "e": 40602, "s": 40583, "text": "Interfaces in Java" }, { "code": null, "e": 40620, "s": 40602, "text": "ArrayList in Java" }, { "code": null, "e": 40652, "s": 40620, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 40672, "s": 40652, "text": "Stack Class in Java" }, { "code": null, "e": 40696, "s": 40672, "text": "Singleton Class in Java" }, { "code": null, "e": 40728, "s": 40696, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 40751, "s": 40728, "text": "Multithreading in Java" }, { "code": null, "e": 40771, "s": 40751, "text": "Collections in Java" } ]
Hopcroft–Karp Algorithm for Maximum Matching | Set 1 (Introduction) - GeeksforGeeks
02 Oct, 2015 A matching in a Bipartite Graph is a set of the edges chosen in such a way that no two edges share an endpoint. A maximum matching is a matching of maximum size (maximum number of edges). In a maximum matching, if any edge is added to it, it is no longer a matching. There can be more than one maximum matching for a given Bipartite Graph. We have discussed importance of maximum matching and Ford Fulkerson Based approach for maximal Bipartite Matching in previous post. Time complexity of the Ford Fulkerson based algorithm is O(V x E). Hopcroft Karp algorithm is an improvement that runs in O(√V x E) time. Let us define few terms before we discuss the algorithm Free Node or Vertex: Given a matching M, a node that is not part of matching is called free node. Initially all vertices as free (See first graph of below diagram). In second graph, u2 and v2 are free. In third graph, no vertex is free. Matching and Not-Matching edges: Given a matching M, edges that are part of matching are called Matching edges and edges that are not part of M (or connect free nodes) are called Not-Matching edges. In first graph, all edges are non-matching. In second graph, (u0, v1), (u1, v0) and (u3, v3) are matching and others not-matching. Alternating Paths: Given a matching M, an alternating path is a path in which the edges belong alternatively to the matching and not matching. All single edges paths are alternating paths. Examples of alternating paths in middle graph are u0-v1-u2 and u2-v1-u0-v2. Augmenting path: Given a matching M, an augmenting path is an alternating path that starts from and ends on free vertices. All single edge paths that start and end with free vertices are augmenting paths. In below diagram, augmenting paths are highlighted with blue color. Note that the augmenting path always has one extra matching edge. The Hopcroft Karp algorithm is based on below concept. A matching M is not maximum if there exists an augmenting path. It is also true other way, i.e, a matching is maximum if no augmenting path exists So the idea is to one by one look for augmenting paths. And add the found paths to current matching. Hopcroft Karp Algorithm 1) Initialize Maximal Matching M as empty. 2) While there exists an Augmenting Path p Remove matching edges of p from M and add not-matching edges of p to M (This increases size of M by 1 as p starts and ends with a free vertex) 3) Return M. Below diagram shows working of the algorithm. In the initial graph all single edges are augmenting paths and we can pick in any order. In the middle stage, there is only one augmenting path. We remove matching edges of this path from M and add not-matching edges. In final matching, there are no augmenting paths so the matching is maximum. Implementation of Hopcroft Karp algorithm is discussed in set 2. Hopcroft–Karp Algorithm for Maximum Matching | Set 2 (Implementation) References:https://en.wikipedia.org/wiki/Hopcroft%E2%80%93Karp_algorithmhttp://www.dis.uniroma1.it/~leon/tcs/lecture2.pdf Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Graph Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Topological Sorting Bellman–Ford Algorithm | DP-23 Detect Cycle in a Directed Graph Floyd Warshall Algorithm | DP-16 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph) Strongly Connected Components Detect cycle in an undirected graph Traveling Salesman Problem (TSP) Implementation
[ { "code": null, "e": 26151, "s": 26123, "text": "\n02 Oct, 2015" }, { "code": null, "e": 26491, "s": 26151, "text": "A matching in a Bipartite Graph is a set of the edges chosen in such a way that no two edges share an endpoint. A maximum matching is a matching of maximum size (maximum number of edges). In a maximum matching, if any edge is added to it, it is no longer a matching. There can be more than one maximum matching for a given Bipartite Graph." }, { "code": null, "e": 26690, "s": 26491, "text": "We have discussed importance of maximum matching and Ford Fulkerson Based approach for maximal Bipartite Matching in previous post. Time complexity of the Ford Fulkerson based algorithm is O(V x E)." }, { "code": null, "e": 26817, "s": 26690, "text": "Hopcroft Karp algorithm is an improvement that runs in O(√V x E) time. Let us define few terms before we discuss the algorithm" }, { "code": null, "e": 27054, "s": 26817, "text": "Free Node or Vertex: Given a matching M, a node that is not part of matching is called free node. Initially all vertices as free (See first graph of below diagram). In second graph, u2 and v2 are free. In third graph, no vertex is free." }, { "code": null, "e": 27384, "s": 27054, "text": "Matching and Not-Matching edges: Given a matching M, edges that are part of matching are called Matching edges and edges that are not part of M (or connect free nodes) are called Not-Matching edges. In first graph, all edges are non-matching. In second graph, (u0, v1), (u1, v0) and (u3, v3) are matching and others not-matching." }, { "code": null, "e": 27649, "s": 27384, "text": "Alternating Paths: Given a matching M, an alternating path is a path in which the edges belong alternatively to the matching and not matching. All single edges paths are alternating paths. Examples of alternating paths in middle graph are u0-v1-u2 and u2-v1-u0-v2." }, { "code": null, "e": 27988, "s": 27649, "text": "Augmenting path: Given a matching M, an augmenting path is an alternating path that starts from and ends on free vertices. All single edge paths that start and end with free vertices are augmenting paths. In below diagram, augmenting paths are highlighted with blue color. Note that the augmenting path always has one extra matching edge." }, { "code": null, "e": 28043, "s": 27988, "text": "The Hopcroft Karp algorithm is based on below concept." }, { "code": null, "e": 28190, "s": 28043, "text": "A matching M is not maximum if there exists an augmenting path. It is also true other way, i.e, a matching is maximum if no augmenting path exists" }, { "code": null, "e": 28291, "s": 28190, "text": "So the idea is to one by one look for augmenting paths. And add the found paths to current matching." }, { "code": null, "e": 28315, "s": 28291, "text": "Hopcroft Karp Algorithm" }, { "code": null, "e": 28568, "s": 28315, "text": "1) Initialize Maximal Matching M as empty.\n2) While there exists an Augmenting Path p\n Remove matching edges of p from M and add not-matching edges of p to M\n (This increases size of M by 1 as p starts and ends with a free vertex)\n3) Return M. " }, { "code": null, "e": 28614, "s": 28568, "text": "Below diagram shows working of the algorithm." }, { "code": null, "e": 28909, "s": 28614, "text": "In the initial graph all single edges are augmenting paths and we can pick in any order. In the middle stage, there is only one augmenting path. We remove matching edges of this path from M and add not-matching edges. In final matching, there are no augmenting paths so the matching is maximum." }, { "code": null, "e": 28974, "s": 28909, "text": "Implementation of Hopcroft Karp algorithm is discussed in set 2." }, { "code": null, "e": 29044, "s": 28974, "text": "Hopcroft–Karp Algorithm for Maximum Matching | Set 2 (Implementation)" }, { "code": null, "e": 29166, "s": 29044, "text": "References:https://en.wikipedia.org/wiki/Hopcroft%E2%80%93Karp_algorithmhttp://www.dis.uniroma1.it/~leon/tcs/lecture2.pdf" }, { "code": null, "e": 29290, "s": 29166, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 29296, "s": 29290, "text": "Graph" }, { "code": null, "e": 29302, "s": 29296, "text": "Graph" }, { "code": null, "e": 29400, "s": 29302, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29458, "s": 29400, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 29478, "s": 29458, "text": "Topological Sorting" }, { "code": null, "e": 29509, "s": 29478, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 29542, "s": 29509, "text": "Detect Cycle in a Directed Graph" }, { "code": null, "e": 29575, "s": 29542, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 29643, "s": 29575, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 29718, "s": 29643, "text": "Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)" }, { "code": null, "e": 29748, "s": 29718, "text": "Strongly Connected Components" }, { "code": null, "e": 29784, "s": 29748, "text": "Detect cycle in an undirected graph" } ]
LocalDate minusMonths() method in Java with Examples - GeeksforGeeks
24 Jul, 2019 The minusMonths() method of LocalDate class in Java is used to subtract the number of specified months from this LocalDate and return a copy of LocalDate.This method subtracts the months field in the following steps: subtract the months from the month-of-year field. Check if the date after subtracting months is valid or not. If date is invalid then method adjust the day-of-month to the last valid day. For example, 2018-07-31 minus one month gives date 2018-06-31 but this is invalid result, so the last valid day of the month, 2018-06-30, is returned.This instance is immutable and unaffected by this method call. Syntax: public LocalDate minusMonths(long monthsToSubtract) Parameters: This method accepts a single parameter monthsToSubtract which represents the months to subtract, may be negative. Return value: This method returns a LocalDate based on this date with the months subtracted, not null. Exception: This method throws DateTimeException if the result exceeds the supported date range. Below programs illustrate the minusMonths() method:Program 1: // Java program to demonstrate// LocalDate.minusMonths() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalDate object LocalDate date = LocalDate.parse("2018-11-13"); // print instance System.out.println("LocalDate before" + " subtracting months: " + date); // subtract 15 months LocalDate returnvalue = date.minusMonths(15); // print result System.out.println("LocalDate after " + " subtracting months: " + returnvalue); }} LocalDate before subtracting months: 2018-11-13 LocalDate after subtracting months: 2017-08-13 Program 2: // Java program to demonstrate// LocalDate.minusMonths() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalDate object LocalDate date = LocalDate.parse("2018-12-31"); // print instance System.out.println("LocalDate before" + " subtracting months: " + date); // subtract 3 months LocalDate returnvalue = date.minusMonths(3); // print result System.out.println("LocalDate after " + " subtracting months: " + returnvalue); }} LocalDate before subtracting months: 2018-12-31 LocalDate after subtracting months: 2018-09-30 References:https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#minusMonths(long) shubham_singh Java-Functions Java-LocalDate Java-time package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. HashMap in Java with Examples Stream In Java Interfaces in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java Set in Java Multithreading in Java
[ { "code": null, "e": 25473, "s": 25445, "text": "\n24 Jul, 2019" }, { "code": null, "e": 25690, "s": 25473, "text": "The minusMonths() method of LocalDate class in Java is used to subtract the number of specified months from this LocalDate and return a copy of LocalDate.This method subtracts the months field in the following steps:" }, { "code": null, "e": 25740, "s": 25690, "text": "subtract the months from the month-of-year field." }, { "code": null, "e": 25800, "s": 25740, "text": "Check if the date after subtracting months is valid or not." }, { "code": null, "e": 25878, "s": 25800, "text": "If date is invalid then method adjust the day-of-month to the last valid day." }, { "code": null, "e": 26091, "s": 25878, "text": "For example, 2018-07-31 minus one month gives date 2018-06-31 but this is invalid result, so the last valid day of the month, 2018-06-30, is returned.This instance is immutable and unaffected by this method call." }, { "code": null, "e": 26099, "s": 26091, "text": "Syntax:" }, { "code": null, "e": 26152, "s": 26099, "text": "public LocalDate minusMonths(long monthsToSubtract)\n" }, { "code": null, "e": 26278, "s": 26152, "text": "Parameters: This method accepts a single parameter monthsToSubtract which represents the months to subtract, may be negative." }, { "code": null, "e": 26381, "s": 26278, "text": "Return value: This method returns a LocalDate based on this date with the months subtracted, not null." }, { "code": null, "e": 26477, "s": 26381, "text": "Exception: This method throws DateTimeException if the result exceeds the supported date range." }, { "code": null, "e": 26539, "s": 26477, "text": "Below programs illustrate the minusMonths() method:Program 1:" }, { "code": "// Java program to demonstrate// LocalDate.minusMonths() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalDate object LocalDate date = LocalDate.parse(\"2018-11-13\"); // print instance System.out.println(\"LocalDate before\" + \" subtracting months: \" + date); // subtract 15 months LocalDate returnvalue = date.minusMonths(15); // print result System.out.println(\"LocalDate after \" + \" subtracting months: \" + returnvalue); }}", "e": 27167, "s": 26539, "text": null }, { "code": null, "e": 27264, "s": 27167, "text": "LocalDate before subtracting months: 2018-11-13\nLocalDate after subtracting months: 2017-08-13\n" }, { "code": null, "e": 27275, "s": 27264, "text": "Program 2:" }, { "code": "// Java program to demonstrate// LocalDate.minusMonths() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalDate object LocalDate date = LocalDate.parse(\"2018-12-31\"); // print instance System.out.println(\"LocalDate before\" + \" subtracting months: \" + date); // subtract 3 months LocalDate returnvalue = date.minusMonths(3); // print result System.out.println(\"LocalDate after \" + \" subtracting months: \" + returnvalue); }}", "e": 27901, "s": 27275, "text": null }, { "code": null, "e": 27998, "s": 27901, "text": "LocalDate before subtracting months: 2018-12-31\nLocalDate after subtracting months: 2018-09-30\n" }, { "code": null, "e": 28095, "s": 27998, "text": "References:https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#minusMonths(long)" }, { "code": null, "e": 28109, "s": 28095, "text": "shubham_singh" }, { "code": null, "e": 28124, "s": 28109, "text": "Java-Functions" }, { "code": null, "e": 28139, "s": 28124, "text": "Java-LocalDate" }, { "code": null, "e": 28157, "s": 28139, "text": "Java-time package" }, { "code": null, "e": 28162, "s": 28157, "text": "Java" }, { "code": null, "e": 28167, "s": 28162, "text": "Java" }, { "code": null, "e": 28265, "s": 28167, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28295, "s": 28265, "text": "HashMap in Java with Examples" }, { "code": null, "e": 28310, "s": 28295, "text": "Stream In Java" }, { "code": null, "e": 28329, "s": 28310, "text": "Interfaces in Java" }, { "code": null, "e": 28347, "s": 28329, "text": "ArrayList in Java" }, { "code": null, "e": 28379, "s": 28347, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 28399, "s": 28379, "text": "Stack Class in Java" }, { "code": null, "e": 28431, "s": 28399, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 28455, "s": 28431, "text": "Singleton Class in Java" }, { "code": null, "e": 28467, "s": 28455, "text": "Set in Java" } ]
How to Create Pie Chart from Pandas DataFrame? - GeeksforGeeks
19 Dec, 2021 In this article, we will discuss how to create a Pie chart from Pandas dataframe using Python. The data in a circular graph is represented by a pie chart, which is a form of a graph. In research, engineering, and business, it is frequently utilized. The segments of the pie depict the data’s relative strength and are a sort of graphical representation of data. A list of categories and numerical variables is required for a pie chart. The phrase “pie” refers to the entire, whereas “slices” refers to the individual components of the pie. It is divided into segments and sectors, with each segment and sector representing a piece of the whole pie chart (percentage). All of the data adds up to 360 degrees. The pie’s entire worth is always 100 percent. Let us first create a simple Pie chart. For this first, all required modules are imported and a dataframe is initialized. To plot a pie chart plot() function is used and the kind attribute is set to pie. Syntax: plot(kind='pie') Example: A simple pie chart Python3 import pandas as pd # DataFrame of each student and the votes they getdataframe = pd.DataFrame({'Name': ['Aparna', 'Aparna', 'Aparna', 'Aparna', 'Aparna', 'Juhi', 'Juhi', 'Juhi', 'Juhi', 'Juhi', 'Suprabhat', 'Suprabhat', 'Suprabhat', 'Suprabhat', 'Suprabhat'], 'votes_of_each_class': [12, 9, 17, 19, 20, 11, 15, 12, 9, 4, 22, 19, 17, 19, 18]}) # Plotting the pie chart for above dataframedataframe.groupby(['Name']).sum().plot(kind='pie', y='votes_of_each_class') Output: To add percentage autopct attribute is set to an appropriate value, this automatically adds percentages to each section. Syntax: plot(kind='pie', autopct) Example: Adding percentages to pie chart Python3 import pandas as pd # DataFrame of each student and the votes they getdataframe = pd.DataFrame({'Name': ['Aparna', 'Aparna', 'Aparna', 'Aparna', 'Aparna', 'Juhi', 'Juhi', 'Juhi', 'Juhi', 'Juhi', 'Suprabhat', 'Suprabhat', 'Suprabhat', 'Suprabhat', 'Suprabhat'], 'votes_of_each_class': [12, 9, 17, 19, 20, 11, 15, 12, 9, 4, 22, 19, 17, 19, 18]}) # Plotting the pie chart for above dataframedataframe.groupby(['Name']).sum().plot( kind='pie', y='votes_of_each_class', autopct='%1.0f%%') Output: To add colors to a pie chart, the colors attribute is set to an appropriate list of colors. Syntax: plot(kind='pie', colors) Example: Adding colors to pie chart Python3 import pandas as pd # DataFrame of each student and the votes they getdataframe = pd.DataFrame({'Name': ['Aparna', 'Aparna', 'Aparna', 'Aparna', 'Aparna', 'Juhi', 'Juhi', 'Juhi', 'Juhi', 'Juhi', 'Suprabhat', 'Suprabhat', 'Suprabhat', 'Suprabhat', 'Suprabhat'], 'votes_of_each_class': [12, 9, 17, 19, 20, 11, 15, 12, 9, 4, 22, 19, 17, 19, 18]}) # Defining colors for the pie chartcolors = ['pink', 'silver', 'steelblue'] # Plotting the pie chart for above dataframedataframe.groupby(['Name']).sum().plot( kind='pie', y='votes_of_each_class', autopct='%1.0f%%', colors=colors) Output: Exploding a pie chart means breaking it into its segments. For this, we use explode attribute and set it to an appropriate value. Syntax: plot(kind='pie', explode) Example: Exploding a pie chart Python3 import pandas as pd # DataFrame of each student and the votes they getdataframe = pd.DataFrame({'Name': ['Aparna', 'Aparna', 'Aparna', 'Aparna', 'Aparna', 'Juhi', 'Juhi', 'Juhi', 'Juhi', 'Juhi', 'Suprabhat', 'Suprabhat', 'Suprabhat', 'Suprabhat', 'Suprabhat'], 'votes_of_each_class': [12, 9, 17, 19, 20, 11, 15, 12, 9, 4, 22, 19, 17, 19, 18]}) # Defining colors for the pie chartcolors = ['pink', 'silver', 'steelblue'] # Define the ratio of gap of each fragment in a tupleexplode = (0.05, 0.05, 0.05) # Plotting the pie chart for above dataframedataframe.groupby(['Name']).sum().plot( kind='pie', y='votes_of_each_class', autopct='%1.0f%%', colors=colors, explode=explode) Output : Shadow adds an extra dimension to our pie chart, for this just set the shadow attribute to True. Syntax: plot(kind='pie', shadow=True) Example: Shadow effect in pie chart Python3 import pandas as pd # DataFrame of each student and the votes they getdataframe = pd.DataFrame({'Name': ['Aparna', 'Aparna', 'Aparna', 'Aparna', 'Aparna', 'Juhi', 'Juhi', 'Juhi', 'Juhi', 'Juhi', 'Suprabhat', 'Suprabhat', 'Suprabhat', 'Suprabhat', 'Suprabhat'], 'votes_of_each_class': [12, 9, 17, 19, 20, 11, 15, 12, 9, 4, 22, 19, 17, 19, 18]}) # Plotting the pie chart for above dataframe# and implementing shadow effectdataframe.groupby(['Name']).sum().plot( kind='pie', y='votes_of_each_class', autopct='%1.0f%%', shadow=True) Output: The start Angle implies that we can rotate the pie chart according to the degree angle we specified. For this startangle attribute is set to the appropriate value. Syntax: plot(kind='pie', startangle) Example: Setting a start angle in Pie chart Python3 import pandas as pd # DataFrame of each student and the votes they getdataframe = pd.DataFrame({'Name': ['Aparna', 'Aparna', 'Aparna', 'Aparna', 'Aparna', 'Juhi', 'Juhi', 'Juhi', 'Juhi', 'Juhi', 'Suprabhat', 'Suprabhat', 'Suprabhat', 'Suprabhat', 'Suprabhat'], 'votes_of_each_class': [12, 9, 17, 19, 20, 11, 15, 12, 9, 4, 22, 19, 17, 19, 18]}) # Plotting the pie chart for above dataframe# and rotating the pie chart by 60 degreesdataframe.groupby(['Name']).sum().plot( kind='pie', y='votes_of_each_class', autopct='%1.0f%%', startangle=60) Output : Picked Python pandas-plotting Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25555, "s": 25527, "text": "\n19 Dec, 2021" }, { "code": null, "e": 25650, "s": 25555, "text": "In this article, we will discuss how to create a Pie chart from Pandas dataframe using Python." }, { "code": null, "e": 26309, "s": 25650, "text": "The data in a circular graph is represented by a pie chart, which is a form of a graph. In research, engineering, and business, it is frequently utilized. The segments of the pie depict the data’s relative strength and are a sort of graphical representation of data. A list of categories and numerical variables is required for a pie chart. The phrase “pie” refers to the entire, whereas “slices” refers to the individual components of the pie. It is divided into segments and sectors, with each segment and sector representing a piece of the whole pie chart (percentage). All of the data adds up to 360 degrees. The pie’s entire worth is always 100 percent." }, { "code": null, "e": 26349, "s": 26309, "text": "Let us first create a simple Pie chart." }, { "code": null, "e": 26513, "s": 26349, "text": "For this first, all required modules are imported and a dataframe is initialized. To plot a pie chart plot() function is used and the kind attribute is set to pie." }, { "code": null, "e": 26521, "s": 26513, "text": "Syntax:" }, { "code": null, "e": 26538, "s": 26521, "text": "plot(kind='pie')" }, { "code": null, "e": 26566, "s": 26538, "text": "Example: A simple pie chart" }, { "code": null, "e": 26574, "s": 26566, "text": "Python3" }, { "code": "import pandas as pd # DataFrame of each student and the votes they getdataframe = pd.DataFrame({'Name': ['Aparna', 'Aparna', 'Aparna', 'Aparna', 'Aparna', 'Juhi', 'Juhi', 'Juhi', 'Juhi', 'Juhi', 'Suprabhat', 'Suprabhat', 'Suprabhat', 'Suprabhat', 'Suprabhat'], 'votes_of_each_class': [12, 9, 17, 19, 20, 11, 15, 12, 9, 4, 22, 19, 17, 19, 18]}) # Plotting the pie chart for above dataframedataframe.groupby(['Name']).sum().plot(kind='pie', y='votes_of_each_class')", "e": 27302, "s": 26574, "text": null }, { "code": null, "e": 27310, "s": 27302, "text": "Output:" }, { "code": null, "e": 27431, "s": 27310, "text": "To add percentage autopct attribute is set to an appropriate value, this automatically adds percentages to each section." }, { "code": null, "e": 27439, "s": 27431, "text": "Syntax:" }, { "code": null, "e": 27465, "s": 27439, "text": "plot(kind='pie', autopct)" }, { "code": null, "e": 27506, "s": 27465, "text": "Example: Adding percentages to pie chart" }, { "code": null, "e": 27514, "s": 27506, "text": "Python3" }, { "code": "import pandas as pd # DataFrame of each student and the votes they getdataframe = pd.DataFrame({'Name': ['Aparna', 'Aparna', 'Aparna', 'Aparna', 'Aparna', 'Juhi', 'Juhi', 'Juhi', 'Juhi', 'Juhi', 'Suprabhat', 'Suprabhat', 'Suprabhat', 'Suprabhat', 'Suprabhat'], 'votes_of_each_class': [12, 9, 17, 19, 20, 11, 15, 12, 9, 4, 22, 19, 17, 19, 18]}) # Plotting the pie chart for above dataframedataframe.groupby(['Name']).sum().plot( kind='pie', y='votes_of_each_class', autopct='%1.0f%%')", "e": 28352, "s": 27514, "text": null }, { "code": null, "e": 28360, "s": 28352, "text": "Output:" }, { "code": null, "e": 28452, "s": 28360, "text": "To add colors to a pie chart, the colors attribute is set to an appropriate list of colors." }, { "code": null, "e": 28460, "s": 28452, "text": "Syntax:" }, { "code": null, "e": 28485, "s": 28460, "text": "plot(kind='pie', colors)" }, { "code": null, "e": 28522, "s": 28485, "text": "Example: Adding colors to pie chart " }, { "code": null, "e": 28530, "s": 28522, "text": "Python3" }, { "code": "import pandas as pd # DataFrame of each student and the votes they getdataframe = pd.DataFrame({'Name': ['Aparna', 'Aparna', 'Aparna', 'Aparna', 'Aparna', 'Juhi', 'Juhi', 'Juhi', 'Juhi', 'Juhi', 'Suprabhat', 'Suprabhat', 'Suprabhat', 'Suprabhat', 'Suprabhat'], 'votes_of_each_class': [12, 9, 17, 19, 20, 11, 15, 12, 9, 4, 22, 19, 17, 19, 18]}) # Defining colors for the pie chartcolors = ['pink', 'silver', 'steelblue'] # Plotting the pie chart for above dataframedataframe.groupby(['Name']).sum().plot( kind='pie', y='votes_of_each_class', autopct='%1.0f%%', colors=colors)", "e": 29459, "s": 28530, "text": null }, { "code": null, "e": 29467, "s": 29459, "text": "Output:" }, { "code": null, "e": 29597, "s": 29467, "text": "Exploding a pie chart means breaking it into its segments. For this, we use explode attribute and set it to an appropriate value." }, { "code": null, "e": 29605, "s": 29597, "text": "Syntax:" }, { "code": null, "e": 29631, "s": 29605, "text": "plot(kind='pie', explode)" }, { "code": null, "e": 29662, "s": 29631, "text": "Example: Exploding a pie chart" }, { "code": null, "e": 29670, "s": 29662, "text": "Python3" }, { "code": "import pandas as pd # DataFrame of each student and the votes they getdataframe = pd.DataFrame({'Name': ['Aparna', 'Aparna', 'Aparna', 'Aparna', 'Aparna', 'Juhi', 'Juhi', 'Juhi', 'Juhi', 'Juhi', 'Suprabhat', 'Suprabhat', 'Suprabhat', 'Suprabhat', 'Suprabhat'], 'votes_of_each_class': [12, 9, 17, 19, 20, 11, 15, 12, 9, 4, 22, 19, 17, 19, 18]}) # Defining colors for the pie chartcolors = ['pink', 'silver', 'steelblue'] # Define the ratio of gap of each fragment in a tupleexplode = (0.05, 0.05, 0.05) # Plotting the pie chart for above dataframedataframe.groupby(['Name']).sum().plot( kind='pie', y='votes_of_each_class', autopct='%1.0f%%', colors=colors, explode=explode)", "e": 30700, "s": 29670, "text": null }, { "code": null, "e": 30709, "s": 30700, "text": "Output :" }, { "code": null, "e": 30806, "s": 30709, "text": "Shadow adds an extra dimension to our pie chart, for this just set the shadow attribute to True." }, { "code": null, "e": 30814, "s": 30806, "text": "Syntax:" }, { "code": null, "e": 30844, "s": 30814, "text": "plot(kind='pie', shadow=True)" }, { "code": null, "e": 30881, "s": 30844, "text": "Example: Shadow effect in pie chart " }, { "code": null, "e": 30889, "s": 30881, "text": "Python3" }, { "code": "import pandas as pd # DataFrame of each student and the votes they getdataframe = pd.DataFrame({'Name': ['Aparna', 'Aparna', 'Aparna', 'Aparna', 'Aparna', 'Juhi', 'Juhi', 'Juhi', 'Juhi', 'Juhi', 'Suprabhat', 'Suprabhat', 'Suprabhat', 'Suprabhat', 'Suprabhat'], 'votes_of_each_class': [12, 9, 17, 19, 20, 11, 15, 12, 9, 4, 22, 19, 17, 19, 18]}) # Plotting the pie chart for above dataframe# and implementing shadow effectdataframe.groupby(['Name']).sum().plot( kind='pie', y='votes_of_each_class', autopct='%1.0f%%', shadow=True)", "e": 31774, "s": 30889, "text": null }, { "code": null, "e": 31782, "s": 31774, "text": "Output:" }, { "code": null, "e": 31946, "s": 31782, "text": "The start Angle implies that we can rotate the pie chart according to the degree angle we specified. For this startangle attribute is set to the appropriate value." }, { "code": null, "e": 31954, "s": 31946, "text": "Syntax:" }, { "code": null, "e": 31983, "s": 31954, "text": "plot(kind='pie', startangle)" }, { "code": null, "e": 32028, "s": 31983, "text": "Example: Setting a start angle in Pie chart " }, { "code": null, "e": 32036, "s": 32028, "text": "Python3" }, { "code": "import pandas as pd # DataFrame of each student and the votes they getdataframe = pd.DataFrame({'Name': ['Aparna', 'Aparna', 'Aparna', 'Aparna', 'Aparna', 'Juhi', 'Juhi', 'Juhi', 'Juhi', 'Juhi', 'Suprabhat', 'Suprabhat', 'Suprabhat', 'Suprabhat', 'Suprabhat'], 'votes_of_each_class': [12, 9, 17, 19, 20, 11, 15, 12, 9, 4, 22, 19, 17, 19, 18]}) # Plotting the pie chart for above dataframe# and rotating the pie chart by 60 degreesdataframe.groupby(['Name']).sum().plot( kind='pie', y='votes_of_each_class', autopct='%1.0f%%', startangle=60)", "e": 32931, "s": 32036, "text": null }, { "code": null, "e": 32940, "s": 32931, "text": "Output :" }, { "code": null, "e": 32947, "s": 32940, "text": "Picked" }, { "code": null, "e": 32970, "s": 32947, "text": "Python pandas-plotting" }, { "code": null, "e": 32984, "s": 32970, "text": "Python-pandas" }, { "code": null, "e": 32991, "s": 32984, "text": "Python" }, { "code": null, "e": 33089, "s": 32991, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33121, "s": 33089, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 33163, "s": 33121, "text": "Check if element exists in list in Python" }, { "code": null, "e": 33205, "s": 33163, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 33261, "s": 33205, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 33288, "s": 33261, "text": "Python Classes and Objects" }, { "code": null, "e": 33319, "s": 33288, "text": "Python | os.path.join() method" }, { "code": null, "e": 33358, "s": 33319, "text": "Python | Get unique values from a list" }, { "code": null, "e": 33387, "s": 33358, "text": "Create a directory in Python" }, { "code": null, "e": 33409, "s": 33387, "text": "Defaultdict in Python" } ]
numpy.ndarray.copy() in Python - GeeksforGeeks
28 Dec, 2018 numpy.ndarray.copy() returns a copy of the array. Syntax : numpy.ndarray.copy(order=’C’) Parameters:order : Controls the memory layout of the copy. ‘C’ means C-order, ‘F’ means F-order, ‘A’ means ‘F’ if a is Fortran contiguous, ‘C’ otherwise. ‘K’ means match the layout of a as closely as possible. Code #1: # Python program explaining # numpy.ndarray.copy() function import numpy as geek x = geek.array([[0, 1, 2, 3], [4, 5, 6, 7]], order ='F')print("x is: \n", x) # copying x to yy = x.copy()print("y is :\n", y)print("\nx is copied to y") x is: [[0 1 2 3] [4 5 6 7]] y is : [[0 1 2 3] [4 5 6 7]] x is copied to y Code #2: # Python program explaining # numpy.ndarray.copy() function import numpy as geek x = geek.array([[0, 1, ], [2, 3]])print("x is:\n", x) # copying x to yy = x.copy() # filling x with 1'sx.fill(1)print("\n Now x is : \n", x) print("\n y is: \n", y) x is: [[0 1] [2 3]] Now x is : [[1 1] [1 1]] y is: [[0 1] [2 3]] Python numpy-ndarray Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25531, "s": 25503, "text": "\n28 Dec, 2018" }, { "code": null, "e": 25581, "s": 25531, "text": "numpy.ndarray.copy() returns a copy of the array." }, { "code": null, "e": 25620, "s": 25581, "text": "Syntax : numpy.ndarray.copy(order=’C’)" }, { "code": null, "e": 25830, "s": 25620, "text": "Parameters:order : Controls the memory layout of the copy. ‘C’ means C-order, ‘F’ means F-order, ‘A’ means ‘F’ if a is Fortran contiguous, ‘C’ otherwise. ‘K’ means match the layout of a as closely as possible." }, { "code": null, "e": 25839, "s": 25830, "text": "Code #1:" }, { "code": "# Python program explaining # numpy.ndarray.copy() function import numpy as geek x = geek.array([[0, 1, 2, 3], [4, 5, 6, 7]], order ='F')print(\"x is: \\n\", x) # copying x to yy = x.copy()print(\"y is :\\n\", y)print(\"\\nx is copied to y\")", "e": 26111, "s": 25839, "text": null }, { "code": null, "e": 26192, "s": 26111, "text": "x is: \n [[0 1 2 3]\n [4 5 6 7]]\ny is :\n [[0 1 2 3]\n [4 5 6 7]]\n\nx is copied to y\n" }, { "code": null, "e": 26202, "s": 26192, "text": " Code #2:" }, { "code": "# Python program explaining # numpy.ndarray.copy() function import numpy as geek x = geek.array([[0, 1, ], [2, 3]])print(\"x is:\\n\", x) # copying x to yy = x.copy() # filling x with 1'sx.fill(1)print(\"\\n Now x is : \\n\", x) print(\"\\n y is: \\n\", y)", "e": 26456, "s": 26202, "text": null }, { "code": null, "e": 26534, "s": 26456, "text": "x is:\n [[0 1]\n [2 3]]\n\n Now x is : \n [[1 1]\n [1 1]]\n\n y is: \n [[0 1]\n [2 3]]\n" }, { "code": null, "e": 26555, "s": 26534, "text": "Python numpy-ndarray" }, { "code": null, "e": 26568, "s": 26555, "text": "Python-numpy" }, { "code": null, "e": 26575, "s": 26568, "text": "Python" }, { "code": null, "e": 26673, "s": 26575, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26691, "s": 26673, "text": "Python Dictionary" }, { "code": null, "e": 26726, "s": 26691, "text": "Read a file line by line in Python" }, { "code": null, "e": 26758, "s": 26726, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26780, "s": 26758, "text": "Enumerate() in Python" }, { "code": null, "e": 26822, "s": 26780, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26852, "s": 26822, "text": "Iterate over a list in Python" }, { "code": null, "e": 26878, "s": 26852, "text": "Python String | replace()" }, { "code": null, "e": 26907, "s": 26878, "text": "*args and **kwargs in Python" }, { "code": null, "e": 26951, "s": 26907, "text": "Reading and Writing to text files in Python" } ]
Count of anagrams of each string in an array present in another array - GeeksforGeeks
24 May, 2021 Given two arrays arr1[] and arr2[] consisting of strings, the task is to print the count of anagrams of every string in arr2[] that are present in arr1[]. Examples: Input: arr1[] = [“geeks”, “learn”, “for”, “egeks”, “ealrn”], arr2[] = [“kgees”, “rof”, “nrael”] Output: 2 1 2 Explanation: Anagrams of arr2[0] (“kgees”) in arr1 : “geeks” and “egeks”. Anagrams of arr2[1] (“rof”) in arr1 : “for”. Anagrams of arr2[2] (“nrael”) in arr1 : “learn” and “ealrn”. Input: arr1[] = [“code”, “to”, “grow”, “odce”], arr2[] = [“edoc”, “wgor”, “ot”] Output: 2 1 1 Explanation: Anagrams of arr2[0] (“edoc”) in arr1 “code” and “odce”. Anagrams of arr2[1] (“wgor”) in arr1 “grow”. Anagrams of arr2[2] (“ot”) in arr1 “to” Approach: To solve the problem, the idea is to use frequency-counting with the help of HashMap. Store the frequencies of every string in arr1[] in hashmap in their sorted form. Traverse arr2[], sort strings in arr2[], and print their respective frequencies in HashMap. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ Program to count the// number of anagrams of// each string in a given// array present in// another array #include <bits/stdc++.h>using namespace std; // Function to return the// count of anagramsvoid count(string arr1[], string arr2[], int n, int m){ // Store the frequencies // of strings in arr1[] map<string, int> freq; for (int i = 0; i < n; i++) { // Sort the string sort(arr1[i].begin(), arr1[i].end()); // Increase its frequency // in the map freq[arr1[i]]++; } for (int i = 0; i < m; i++) { // Sort the string sort(arr2[i].begin(), arr2[i].end()); // Display its anagrams // in arr1[] cout << freq[arr2[i]] << " "; }} // Driver Codeint main(){ string arr1[] = { "geeks", "learn", "for", "egeks", "ealrn" }; int n = sizeof(arr1) / sizeof(string); string arr2[] = { "kgees", "rof", "nrael" }; int m = sizeof(arr2) / sizeof(string); count(arr1, arr2, n, m);} // Java program to count the number// of anagrams of each String in a// given array present in// another arrayimport java.util.*; class GFG{ static String sortString(String inputString){ // Convert input string to char array char tempArray[] = inputString.toCharArray(); // Sort tempArray Arrays.sort(tempArray); // Return new sorted string return new String(tempArray);} // Function to return the// count of anagramsstatic void count(String arr1[], String arr2[], int n, int m){ // Store the frequencies // of Strings in arr1[] HashMap<String, Integer> freq = new HashMap<>(); for(int i = 0; i < n; i++) { // Sort the String arr1[i] = sortString(arr1[i]); // Increase its frequency // in the map if (freq.containsKey(arr1[i])) { freq.put(arr1[i], freq.get(arr1[i]) + 1); } else { freq.put(arr1[i], 1); } } for(int i = 0; i < m; i++) { // Sort the String arr2[i] = sortString(arr2[i]); // Display its anagrams // in arr1[] System.out.print(freq.get(arr2[i]) + " "); }} // Driver Codepublic static void main(String[] args){ String arr1[] = { "geeks", "learn", "for", "egeks", "ealrn" }; int n = arr1.length; String arr2[] = { "kgees", "rof", "nrael" }; int m = arr2.length; count(arr1, arr2, n, m);}} // This code is contributed by Amit Katiyar # Python3 program to count the number# of anagrams of each string in a# given array present in another array # Function to return the count of anagramsdef count(arr1, arr2, n, m): # Store the frequencies of # strings in arr1 freq = {} for word in arr1: # Sort the string word = ' '.join(sorted(word)) # Increase its frequency if word in freq.keys(): freq[word] = freq[word] + 1 else: freq[word] = 1 for word in arr2: # Sort the string word = ' '.join(sorted(word)) # Display its anagrams # in arr1 if word in freq.keys(): print(freq[word], end = " ") else: print(0, end = " ") print() # Driver Codeif __name__ == '__main__': arr1 = [ "geeks", "learn", "for", "egeks", "ealrn" ] n = len(arr1) arr2 = [ "kgees", "rof", "nrael" ] m = len(arr2) count(arr1, arr2, n, m) # This code is contributed by Pawan_29 // C# program to count the number// of anagrams of each String in a// given array present in// another arrayusing System;using System.Collections.Generic; class GFG{ static String sortString(String inputString){ // Convert input string to char array char []tempArray = inputString.ToCharArray(); // Sort tempArray Array.Sort(tempArray); // Return new sorted string return new String(tempArray);} // Function to return the// count of anagramsstatic void count(String []arr1, String []arr2, int n, int m){ // Store the frequencies // of Strings in arr1[] Dictionary<String, int> freq = new Dictionary<String, int>(); for(int i = 0; i < n; i++) { // Sort the String arr1[i] = sortString(arr1[i]); // Increase its frequency // in the map if (freq.ContainsKey(arr1[i])) { freq[arr1[i]] = freq[arr1[i]] + 1; } else { freq.Add(arr1[i], 1); } } for(int i = 0; i < m; i++) { // Sort the String arr2[i] = sortString(arr2[i]); // Display its anagrams // in arr1[] Console.Write(freq[arr2[i]] + " "); }} // Driver Codepublic static void Main(String[] args){ String []arr1 = { "geeks", "learn", "for", "egeks", "ealrn" }; int n = arr1.Length; String []arr2 = { "kgees", "rof", "nrael" }; int m = arr2.Length; count(arr1, arr2, n, m);}} // This code is contributed by Amit Katiyar <script> // Javascript program to count the number// of anagrams of each String in a// given array present in// another array function sortString(inputString){ // Convert input string to char array let tempArray = inputString.split(''); // Sort tempArray tempArray.sort(); // Return new sorted string return tempArray.join("");} // Function to return the// count of anagramsfunction count(arr1, arr2, n, m){ // Store the frequencies // of Strings in arr1[] let freq = new Map(); for(let i = 0; i < n; i++) { // Sort the String arr1[i] = sortString(arr1[i]); // Increase its frequency // in the map if (freq.has(arr1[i])) { freq.set(arr1[i], freq.get(arr1[i]) + 1); } else { freq.set(arr1[i], 1); } } for(let i = 0; i < m; i++) { // Sort the String arr2[i] = sortString(arr2[i]); // Display its anagrams // in arr1[] document.write(freq.get(arr2[i]) + " "); }} // Driver code let arr1 = [ "geeks", "learn", "for", "egeks", "ealrn" ]; let n = arr1.length; let arr2 = [ "kgees", "rof", "nrael" ]; let m = arr2.length; count(arr1, arr2, n, m); // This code is contributed by souravghosh0416.</script> 2 1 2 Pawan_29 amit143katiyar souravghosh0416 anagram cpp-map frequency-counting Java-HashMap Arrays Hash Sorting Strings Arrays Hash Strings Sorting anagram Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count pairs with given sum Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element Internal Working of HashMap in Java Count pairs with given sum Hashing | Set 1 (Introduction) Hashing | Set 3 (Open Addressing) Hashing | Set 2 (Separate Chaining)
[ { "code": null, "e": 26065, "s": 26037, "text": "\n24 May, 2021" }, { "code": null, "e": 26220, "s": 26065, "text": "Given two arrays arr1[] and arr2[] consisting of strings, the task is to print the count of anagrams of every string in arr2[] that are present in arr1[]." }, { "code": null, "e": 26231, "s": 26220, "text": "Examples: " }, { "code": null, "e": 26521, "s": 26231, "text": "Input: arr1[] = [“geeks”, “learn”, “for”, “egeks”, “ealrn”], arr2[] = [“kgees”, “rof”, “nrael”] Output: 2 1 2 Explanation: Anagrams of arr2[0] (“kgees”) in arr1 : “geeks” and “egeks”. Anagrams of arr2[1] (“rof”) in arr1 : “for”. Anagrams of arr2[2] (“nrael”) in arr1 : “learn” and “ealrn”." }, { "code": null, "e": 26770, "s": 26521, "text": "Input: arr1[] = [“code”, “to”, “grow”, “odce”], arr2[] = [“edoc”, “wgor”, “ot”] Output: 2 1 1 Explanation: Anagrams of arr2[0] (“edoc”) in arr1 “code” and “odce”. Anagrams of arr2[1] (“wgor”) in arr1 “grow”. Anagrams of arr2[2] (“ot”) in arr1 “to” " }, { "code": null, "e": 27039, "s": 26770, "text": "Approach: To solve the problem, the idea is to use frequency-counting with the help of HashMap. Store the frequencies of every string in arr1[] in hashmap in their sorted form. Traverse arr2[], sort strings in arr2[], and print their respective frequencies in HashMap." }, { "code": null, "e": 27092, "s": 27039, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27096, "s": 27092, "text": "C++" }, { "code": null, "e": 27101, "s": 27096, "text": "Java" }, { "code": null, "e": 27109, "s": 27101, "text": "Python3" }, { "code": null, "e": 27112, "s": 27109, "text": "C#" }, { "code": null, "e": 27123, "s": 27112, "text": "Javascript" }, { "code": "// C++ Program to count the// number of anagrams of// each string in a given// array present in// another array #include <bits/stdc++.h>using namespace std; // Function to return the// count of anagramsvoid count(string arr1[], string arr2[], int n, int m){ // Store the frequencies // of strings in arr1[] map<string, int> freq; for (int i = 0; i < n; i++) { // Sort the string sort(arr1[i].begin(), arr1[i].end()); // Increase its frequency // in the map freq[arr1[i]]++; } for (int i = 0; i < m; i++) { // Sort the string sort(arr2[i].begin(), arr2[i].end()); // Display its anagrams // in arr1[] cout << freq[arr2[i]] << \" \"; }} // Driver Codeint main(){ string arr1[] = { \"geeks\", \"learn\", \"for\", \"egeks\", \"ealrn\" }; int n = sizeof(arr1) / sizeof(string); string arr2[] = { \"kgees\", \"rof\", \"nrael\" }; int m = sizeof(arr2) / sizeof(string); count(arr1, arr2, n, m);}", "e": 28250, "s": 27123, "text": null }, { "code": "// Java program to count the number// of anagrams of each String in a// given array present in// another arrayimport java.util.*; class GFG{ static String sortString(String inputString){ // Convert input string to char array char tempArray[] = inputString.toCharArray(); // Sort tempArray Arrays.sort(tempArray); // Return new sorted string return new String(tempArray);} // Function to return the// count of anagramsstatic void count(String arr1[], String arr2[], int n, int m){ // Store the frequencies // of Strings in arr1[] HashMap<String, Integer> freq = new HashMap<>(); for(int i = 0; i < n; i++) { // Sort the String arr1[i] = sortString(arr1[i]); // Increase its frequency // in the map if (freq.containsKey(arr1[i])) { freq.put(arr1[i], freq.get(arr1[i]) + 1); } else { freq.put(arr1[i], 1); } } for(int i = 0; i < m; i++) { // Sort the String arr2[i] = sortString(arr2[i]); // Display its anagrams // in arr1[] System.out.print(freq.get(arr2[i]) + \" \"); }} // Driver Codepublic static void main(String[] args){ String arr1[] = { \"geeks\", \"learn\", \"for\", \"egeks\", \"ealrn\" }; int n = arr1.length; String arr2[] = { \"kgees\", \"rof\", \"nrael\" }; int m = arr2.length; count(arr1, arr2, n, m);}} // This code is contributed by Amit Katiyar", "e": 29845, "s": 28250, "text": null }, { "code": "# Python3 program to count the number# of anagrams of each string in a# given array present in another array # Function to return the count of anagramsdef count(arr1, arr2, n, m): # Store the frequencies of # strings in arr1 freq = {} for word in arr1: # Sort the string word = ' '.join(sorted(word)) # Increase its frequency if word in freq.keys(): freq[word] = freq[word] + 1 else: freq[word] = 1 for word in arr2: # Sort the string word = ' '.join(sorted(word)) # Display its anagrams # in arr1 if word in freq.keys(): print(freq[word], end = \" \") else: print(0, end = \" \") print() # Driver Codeif __name__ == '__main__': arr1 = [ \"geeks\", \"learn\", \"for\", \"egeks\", \"ealrn\" ] n = len(arr1) arr2 = [ \"kgees\", \"rof\", \"nrael\" ] m = len(arr2) count(arr1, arr2, n, m) # This code is contributed by Pawan_29", "e": 30871, "s": 29845, "text": null }, { "code": "// C# program to count the number// of anagrams of each String in a// given array present in// another arrayusing System;using System.Collections.Generic; class GFG{ static String sortString(String inputString){ // Convert input string to char array char []tempArray = inputString.ToCharArray(); // Sort tempArray Array.Sort(tempArray); // Return new sorted string return new String(tempArray);} // Function to return the// count of anagramsstatic void count(String []arr1, String []arr2, int n, int m){ // Store the frequencies // of Strings in arr1[] Dictionary<String, int> freq = new Dictionary<String, int>(); for(int i = 0; i < n; i++) { // Sort the String arr1[i] = sortString(arr1[i]); // Increase its frequency // in the map if (freq.ContainsKey(arr1[i])) { freq[arr1[i]] = freq[arr1[i]] + 1; } else { freq.Add(arr1[i], 1); } } for(int i = 0; i < m; i++) { // Sort the String arr2[i] = sortString(arr2[i]); // Display its anagrams // in arr1[] Console.Write(freq[arr2[i]] + \" \"); }} // Driver Codepublic static void Main(String[] args){ String []arr1 = { \"geeks\", \"learn\", \"for\", \"egeks\", \"ealrn\" }; int n = arr1.Length; String []arr2 = { \"kgees\", \"rof\", \"nrael\" }; int m = arr2.Length; count(arr1, arr2, n, m);}} // This code is contributed by Amit Katiyar", "e": 32544, "s": 30871, "text": null }, { "code": "<script> // Javascript program to count the number// of anagrams of each String in a// given array present in// another array function sortString(inputString){ // Convert input string to char array let tempArray = inputString.split(''); // Sort tempArray tempArray.sort(); // Return new sorted string return tempArray.join(\"\");} // Function to return the// count of anagramsfunction count(arr1, arr2, n, m){ // Store the frequencies // of Strings in arr1[] let freq = new Map(); for(let i = 0; i < n; i++) { // Sort the String arr1[i] = sortString(arr1[i]); // Increase its frequency // in the map if (freq.has(arr1[i])) { freq.set(arr1[i], freq.get(arr1[i]) + 1); } else { freq.set(arr1[i], 1); } } for(let i = 0; i < m; i++) { // Sort the String arr2[i] = sortString(arr2[i]); // Display its anagrams // in arr1[] document.write(freq.get(arr2[i]) + \" \"); }} // Driver code let arr1 = [ \"geeks\", \"learn\", \"for\", \"egeks\", \"ealrn\" ]; let n = arr1.length; let arr2 = [ \"kgees\", \"rof\", \"nrael\" ]; let m = arr2.length; count(arr1, arr2, n, m); // This code is contributed by souravghosh0416.</script>", "e": 33974, "s": 32544, "text": null }, { "code": null, "e": 33980, "s": 33974, "text": "2 1 2" }, { "code": null, "e": 33991, "s": 33982, "text": "Pawan_29" }, { "code": null, "e": 34006, "s": 33991, "text": "amit143katiyar" }, { "code": null, "e": 34022, "s": 34006, "text": "souravghosh0416" }, { "code": null, "e": 34030, "s": 34022, "text": "anagram" }, { "code": null, "e": 34038, "s": 34030, "text": "cpp-map" }, { "code": null, "e": 34057, "s": 34038, "text": "frequency-counting" }, { "code": null, "e": 34070, "s": 34057, "text": "Java-HashMap" }, { "code": null, "e": 34077, "s": 34070, "text": "Arrays" }, { "code": null, "e": 34082, "s": 34077, "text": "Hash" }, { "code": null, "e": 34090, "s": 34082, "text": "Sorting" }, { "code": null, "e": 34098, "s": 34090, "text": "Strings" }, { "code": null, "e": 34105, "s": 34098, "text": "Arrays" }, { "code": null, "e": 34110, "s": 34105, "text": "Hash" }, { "code": null, "e": 34118, "s": 34110, "text": "Strings" }, { "code": null, "e": 34126, "s": 34118, "text": "Sorting" }, { "code": null, "e": 34134, "s": 34126, "text": "anagram" }, { "code": null, "e": 34232, "s": 34134, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34259, "s": 34232, "text": "Count pairs with given sum" }, { "code": null, "e": 34290, "s": 34259, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 34315, "s": 34290, "text": "Window Sliding Technique" }, { "code": null, "e": 34353, "s": 34315, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 34374, "s": 34353, "text": "Next Greater Element" }, { "code": null, "e": 34410, "s": 34374, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 34437, "s": 34410, "text": "Count pairs with given sum" }, { "code": null, "e": 34468, "s": 34437, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 34502, "s": 34468, "text": "Hashing | Set 3 (Open Addressing)" } ]
SQL Query to Copy, Duplicate or Backup Table - GeeksforGeeks
15 May, 2021 In relational databases, we often deal with different tables and perform various operations using this different database software like MYSQL, Oracle, PostgreSQL, etc. Sometimes, while performing these operations many of us want to keep a backup table which is beneficial and can be used as a reference or can be reused if needed. Similarly, many times we need to copy the same table again and create a duplicate version of itself. We can track changes of data using the backup table when we perform various modification operations. So, in this article, we are going to discuss how to copy as well as create a backup table in SQL. Sample Input: Consider a schema “Student Information” which consists of data of Geeks who enrolled in our DSA course as shown below: Syntax: CREATE TABLE Table_Name AS SELECT * FROM Source_Table_Name; Table_Name: The name of the backup table. AS: Aliasing In MYSQL, we can use the following command to check the number of tables created in the database before and after a backup. However, this command is not supported in PostgreSQL and in other versions of SQL. SHOW TABLES; Example 1: We can copy all the columns in the backup table. Backup Table 1 Query Output : Output of Backup Table 1 Example 2: It is not mandatory to copy all the columns. We can take a few columns as well. Syntax: CREATE TABLE Table_Name AS SELECT col_1, col_2, ... FROM Source_Table_Name; Table_Name: The name of the backup table. AS: Aliasing col: Required columns from source table Backup Table 2 Query Output : Output of Backup Table 2 Till now we have seen how to create a clone of the source table. In the above backup table, the data is also copied along with the table. However, we can also create a backup table without copying the data. So, to create a table without any data being copied we can use the help of the WHERE clause which needs to return a FALSE value. For example, we can use WHERE 2<2 or WHERE 1=2. Syntax: CREATE TABLE Table_Name AS SELECT * FROM Source_Table_Name WHERE (RETURN FALSE); Table_Name: The name of the backup table. AS: Aliasing FALSE: Any expression which returns FALSE. For example 4>5 Example 1: All the columns copied without any data. Query For Backup Table Output : Backup Table Output Example 2: It is not mandatory to copy all the columns. We can take a few columns as well. Syntax: CREATE TABLE Table_Name AS SELECT col1,col2,.... Source_Table_Name WHERE (RETURN FALSE); Table_Name: The name of the backup table. AS: Aliasing col: Required columns from source table FALSE: Any expression which returns FALSE. For example 4>5 Query For Backup Table Output : Backup Table Output Picked SQL-Query SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SQL Interview Questions CTE in SQL SQL Trigger | Student Database How to Update Multiple Columns in Single Update Statement in SQL? SQL | Views Difference between DDL and DML in DBMS SQL | GROUP BY Difference between DELETE, DROP and TRUNCATE MySQL | Group_CONCAT() Function Difference between DELETE and TRUNCATE
[ { "code": null, "e": 25357, "s": 25329, "text": "\n15 May, 2021" }, { "code": null, "e": 25790, "s": 25357, "text": "In relational databases, we often deal with different tables and perform various operations using this different database software like MYSQL, Oracle, PostgreSQL, etc. Sometimes, while performing these operations many of us want to keep a backup table which is beneficial and can be used as a reference or can be reused if needed. Similarly, many times we need to copy the same table again and create a duplicate version of itself. " }, { "code": null, "e": 25989, "s": 25790, "text": "We can track changes of data using the backup table when we perform various modification operations. So, in this article, we are going to discuss how to copy as well as create a backup table in SQL." }, { "code": null, "e": 26122, "s": 25989, "text": "Sample Input: Consider a schema “Student Information” which consists of data of Geeks who enrolled in our DSA course as shown below:" }, { "code": null, "e": 26246, "s": 26122, "text": "Syntax:\nCREATE TABLE Table_Name AS SELECT * FROM Source_Table_Name;\n\nTable_Name: The name of the backup table.\nAS: Aliasing" }, { "code": null, "e": 26453, "s": 26246, "text": "In MYSQL, we can use the following command to check the number of tables created in the database before and after a backup. However, this command is not supported in PostgreSQL and in other versions of SQL." }, { "code": null, "e": 26466, "s": 26453, "text": "SHOW TABLES;" }, { "code": null, "e": 26526, "s": 26466, "text": "Example 1: We can copy all the columns in the backup table." }, { "code": null, "e": 26547, "s": 26526, "text": "Backup Table 1 Query" }, { "code": null, "e": 26556, "s": 26547, "text": "Output :" }, { "code": null, "e": 26581, "s": 26556, "text": "Output of Backup Table 1" }, { "code": null, "e": 26672, "s": 26581, "text": "Example 2: It is not mandatory to copy all the columns. We can take a few columns as well." }, { "code": null, "e": 26852, "s": 26672, "text": "Syntax:\nCREATE TABLE Table_Name AS SELECT col_1, col_2, ... FROM Source_Table_Name;\n\nTable_Name: The name of the backup table.\nAS: Aliasing\ncol: Required columns from source table" }, { "code": null, "e": 26873, "s": 26852, "text": "Backup Table 2 Query" }, { "code": null, "e": 26882, "s": 26873, "text": "Output :" }, { "code": null, "e": 26907, "s": 26882, "text": "Output of Backup Table 2" }, { "code": null, "e": 27292, "s": 26907, "text": "Till now we have seen how to create a clone of the source table. In the above backup table, the data is also copied along with the table. However, we can also create a backup table without copying the data. So, to create a table without any data being copied we can use the help of the WHERE clause which needs to return a FALSE value. For example, we can use WHERE 2<2 or WHERE 1=2." }, { "code": null, "e": 27496, "s": 27292, "text": "Syntax:\nCREATE TABLE Table_Name AS SELECT * FROM Source_Table_Name\nWHERE (RETURN FALSE);\n\nTable_Name: The name of the backup table.\nAS: Aliasing\nFALSE: Any expression which returns FALSE. For example 4>5" }, { "code": null, "e": 27548, "s": 27496, "text": "Example 1: All the columns copied without any data." }, { "code": null, "e": 27571, "s": 27548, "text": "Query For Backup Table" }, { "code": null, "e": 27580, "s": 27571, "text": "Output :" }, { "code": null, "e": 27600, "s": 27580, "text": "Backup Table Output" }, { "code": null, "e": 27691, "s": 27600, "text": "Example 2: It is not mandatory to copy all the columns. We can take a few columns as well." }, { "code": null, "e": 27943, "s": 27691, "text": "Syntax:\nCREATE TABLE Table_Name AS SELECT col1,col2,.... Source_Table_Name\nWHERE (RETURN FALSE);\n\nTable_Name: The name of the backup table.\nAS: Aliasing\ncol: Required columns from source table\nFALSE: Any expression which returns FALSE. For example 4>5" }, { "code": null, "e": 27966, "s": 27943, "text": "Query For Backup Table" }, { "code": null, "e": 27975, "s": 27966, "text": "Output :" }, { "code": null, "e": 27995, "s": 27975, "text": "Backup Table Output" }, { "code": null, "e": 28002, "s": 27995, "text": "Picked" }, { "code": null, "e": 28012, "s": 28002, "text": "SQL-Query" }, { "code": null, "e": 28016, "s": 28012, "text": "SQL" }, { "code": null, "e": 28020, "s": 28016, "text": "SQL" }, { "code": null, "e": 28118, "s": 28020, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28142, "s": 28118, "text": "SQL Interview Questions" }, { "code": null, "e": 28153, "s": 28142, "text": "CTE in SQL" }, { "code": null, "e": 28184, "s": 28153, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 28250, "s": 28184, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 28262, "s": 28250, "text": "SQL | Views" }, { "code": null, "e": 28301, "s": 28262, "text": "Difference between DDL and DML in DBMS" }, { "code": null, "e": 28316, "s": 28301, "text": "SQL | GROUP BY" }, { "code": null, "e": 28361, "s": 28316, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 28393, "s": 28361, "text": "MySQL | Group_CONCAT() Function" } ]
D3.js scaleTime() Function - GeeksforGeeks
23 Aug, 2020 The d3.scaleTime() function is used to create and return a new time scale which have the particular domain and range. In this function the clamping is disabled by default. Syntax: d3.scaleTime([[domain, ]range]); Parameter: This function accepts two parameters as mentioned above and described below. Domain: It is an array of integers that defines the extent of domain values. If not specified then the default value is [2000-01-01, 2000-01-02]. Range: It is an array of integers or string. If not specified then the default value is [0, 1]. Return Value: This function returns a function. Example 1: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" path1tent= "width=device-width,initial-scale=1.0"/> <script src="https://d3js.org/d3.v4.min.js"> </script> <script src="https://d3js.org/d3-color.v1.min.js"> </script> <script src= "https://d3js.org/d3-interpolate.v1.min.js"> </script> <script src= "https://d3js.org/d3-scale-chromatic.v1.min.js"> </script></head> <body> <h2 style="color:green">Geeks for geeks</h2> <p>d3.scaleTime() Function</p> <script> var time = d3.scaleTime() .domain([1, 10]) .range([10, 5]); document.write("<h3>Type of d3.scaleTime() is: " + typeof (time) + "</h3>"); document.write("<h3>time(10): " + time(10) + "</h3>"); </script></body> </html> Output: Example 2: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" path1tent= "width=device-width, initial-scale=1.0"/> <script src="https://d3js.org/d3.v4.min.js"> </script> <script src="https://d3js.org/d3-color.v1.min.js"> </script> <script src= "https://d3js.org/d3-interpolate.v1.min.js"> </script> <script src= "https://d3js.org/d3-scale-chromatic.v1.min.js"> </script></head> <body> <h2 style="color:green;">Geeks for geeks</h2> <p>d3.scaleTime() Function </p> <script> var time = d3.scaleTime() .domain([1, 10]) .range([1, 100]) document.write("<h3>time(1): " + time(1) + "</h3>") document.write("<h3>time(2): " + time(2) + "</h3>") document.write("<h3>time(3): " + time(3) + "</h3>") document.write("<h3>time(4): " + time(4) + "</h3>") </script></body> </html> Output: D3.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to Open URL in New Tab using JavaScript ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25467, "s": 25439, "text": "\n23 Aug, 2020" }, { "code": null, "e": 25639, "s": 25467, "text": "The d3.scaleTime() function is used to create and return a new time scale which have the particular domain and range. In this function the clamping is disabled by default." }, { "code": null, "e": 25647, "s": 25639, "text": "Syntax:" }, { "code": null, "e": 25680, "s": 25647, "text": "d3.scaleTime([[domain, ]range]);" }, { "code": null, "e": 25768, "s": 25680, "text": "Parameter: This function accepts two parameters as mentioned above and described below." }, { "code": null, "e": 25914, "s": 25768, "text": "Domain: It is an array of integers that defines the extent of domain values. If not specified then the default value is [2000-01-01, 2000-01-02]." }, { "code": null, "e": 26010, "s": 25914, "text": "Range: It is an array of integers or string. If not specified then the default value is [0, 1]." }, { "code": null, "e": 26058, "s": 26010, "text": "Return Value: This function returns a function." }, { "code": null, "e": 26069, "s": 26058, "text": "Example 1:" }, { "code": null, "e": 26074, "s": 26069, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" path1tent= \"width=device-width,initial-scale=1.0\"/> <script src=\"https://d3js.org/d3.v4.min.js\"> </script> <script src=\"https://d3js.org/d3-color.v1.min.js\"> </script> <script src= \"https://d3js.org/d3-interpolate.v1.min.js\"> </script> <script src= \"https://d3js.org/d3-scale-chromatic.v1.min.js\"> </script></head> <body> <h2 style=\"color:green\">Geeks for geeks</h2> <p>d3.scaleTime() Function</p> <script> var time = d3.scaleTime() .domain([1, 10]) .range([10, 5]); document.write(\"<h3>Type of d3.scaleTime() is: \" + typeof (time) + \"</h3>\"); document.write(\"<h3>time(10): \" + time(10) + \"</h3>\"); </script></body> </html>", "e": 26922, "s": 26074, "text": null }, { "code": null, "e": 26930, "s": 26922, "text": "Output:" }, { "code": null, "e": 26941, "s": 26930, "text": "Example 2:" }, { "code": null, "e": 26946, "s": 26941, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" path1tent= \"width=device-width, initial-scale=1.0\"/> <script src=\"https://d3js.org/d3.v4.min.js\"> </script> <script src=\"https://d3js.org/d3-color.v1.min.js\"> </script> <script src= \"https://d3js.org/d3-interpolate.v1.min.js\"> </script> <script src= \"https://d3js.org/d3-scale-chromatic.v1.min.js\"> </script></head> <body> <h2 style=\"color:green;\">Geeks for geeks</h2> <p>d3.scaleTime() Function </p> <script> var time = d3.scaleTime() .domain([1, 10]) .range([1, 100]) document.write(\"<h3>time(1): \" + time(1) + \"</h3>\") document.write(\"<h3>time(2): \" + time(2) + \"</h3>\") document.write(\"<h3>time(3): \" + time(3) + \"</h3>\") document.write(\"<h3>time(4): \" + time(4) + \"</h3>\") </script></body> </html>", "e": 27850, "s": 26946, "text": null }, { "code": null, "e": 27858, "s": 27850, "text": "Output:" }, { "code": null, "e": 27864, "s": 27858, "text": "D3.js" }, { "code": null, "e": 27875, "s": 27864, "text": "JavaScript" }, { "code": null, "e": 27892, "s": 27875, "text": "Web Technologies" }, { "code": null, "e": 27990, "s": 27892, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28030, "s": 27990, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28075, "s": 28030, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28136, "s": 28075, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28208, "s": 28136, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 28254, "s": 28208, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 28294, "s": 28254, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28327, "s": 28294, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28372, "s": 28327, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28415, "s": 28372, "text": "How to fetch data from an API in ReactJS ?" } ]
Java.lang.Class class in Java | Set 1 - GeeksforGeeks
28 Jun, 2021 Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are constructed automatically by the Java Virtual Machine(JVM). It is a final class, so we cannot extend it. The Class class methods are widely used in Reflection API. Creating a Class object There are three ways to create Class object : Class.forName(“className”) : Since class Class doesn’t contain any constructor, there is static factory method present in class Class, which is Class.forName() , used for creating object of class Class. Below is the syntax :Class c = Class.forName(String className) The above statement creates the Class object for the class passed as a String argument(className). Note that the parameter className must be fully qualified name of the desired class for which Class object is to be created. The methods in any class in java which returns the same class object are also known as factory methods. The class name for which Class object is to be created is determined at run-time.Myclass.class : When we write .class after a class name, it references the Class object that represents the given class. It is mostly used with primitive data types and only when we know the name of class. The class name for which Class object is to be created is determined at compile-time. Below is the syntax :Class c = int.class Please note that this method is used with class name, not with class instances. For exampleA a = new A(); // Any class A Class c = A.class; // No error Class c = a.class; // Error obj.getClass() : This method is present in Object class. It return the run-time class of this(obj) object. Below is the syntax :A a = new A(); // Any class A Class c = a.getClass(); Class.forName(“className”) : Since class Class doesn’t contain any constructor, there is static factory method present in class Class, which is Class.forName() , used for creating object of class Class. Below is the syntax :Class c = Class.forName(String className) The above statement creates the Class object for the class passed as a String argument(className). Note that the parameter className must be fully qualified name of the desired class for which Class object is to be created. The methods in any class in java which returns the same class object are also known as factory methods. The class name for which Class object is to be created is determined at run-time. Class c = Class.forName(String className) The above statement creates the Class object for the class passed as a String argument(className). Note that the parameter className must be fully qualified name of the desired class for which Class object is to be created. The methods in any class in java which returns the same class object are also known as factory methods. The class name for which Class object is to be created is determined at run-time. Myclass.class : When we write .class after a class name, it references the Class object that represents the given class. It is mostly used with primitive data types and only when we know the name of class. The class name for which Class object is to be created is determined at compile-time. Below is the syntax :Class c = int.class Please note that this method is used with class name, not with class instances. For exampleA a = new A(); // Any class A Class c = A.class; // No error Class c = a.class; // Error Class c = int.class Please note that this method is used with class name, not with class instances. For example A a = new A(); // Any class A Class c = A.class; // No error Class c = a.class; // Error obj.getClass() : This method is present in Object class. It return the run-time class of this(obj) object. Below is the syntax :A a = new A(); // Any class A Class c = a.getClass(); A a = new A(); // Any class A Class c = a.getClass(); Methods: String toString() : This method converts the Class object to a string. It returns the string representation which is the string “class” or “interface”, followed by a space, and then by the fully qualified name of the class. If the Class object represents a primitive type, then this method returns the name of the primitive type and if it represents void then it returns “void”.Syntax : public String toString() Parameters : NA Returns : a string representation of this class object. Overrides : toString in class Object // Java program to demonstrate toString() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName("java.lang.String"); Class c2 = int.class; Class c3 = void.class; System.out.print("Class represented by c1: "); // toString method on c1 System.out.println(c1.toString()); System.out.print("Class represented by c2: "); // toString method on c2 System.out.println(c2.toString()); System.out.print("Class represented by c3: "); // toString method on c3 System.out.println(c3.toString()); }}Output:Class represented by c1: class java.lang.String Class represented by c2: int Class represented by c3: void Class<?> forName(String className) : As discussed earlier, this method returns the Class object associated with the class or interface with the given string name. The other variant of this method is discussed next.Syntax : public static Class<?> forName(String className) throws ClassNotFoundException Parameters : className - the fully qualified name of the desired class. Returns : return the Class object for the class with the specified name. Throws : LinkageError : if the linkage fails ExceptionInInitializerError - if the initialization provoked by this method fails ClassNotFoundException - if the class cannot be located // Java program to demonstrate forName() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // forName method // it returns the Class object for the class // with the specified name Class c = Class.forName("java.lang.String"); System.out.print("Class represented by c : " + c.toString()); }}Output:Class represented by c : class java.lang.String Class<?> forName(String className,boolean initialize, ClassLoader loader) : This method also returns the Class object associated with the class or interface with the given string name using the given class loader.The specified class loader is used to load the class or interface. If the parameter loader is null, the class is loaded through the bootstrap class loader in. The class is initialized only if the initialize parameter is true and if it has not been initialized earlier.Syntax : public static Class<?> forName(String className,boolean initialize, ClassLoader loader) throws ClassNotFoundException Parameters : className - the fully qualified name of the desired class initialize - whether the class must be initialized loader - class loader from which the class must be loaded Returns : return the Class object for the class with the specified name. Throws : LinkageError : if the linkage fails ExceptionInInitializerError - if the initialization provoked by this method fails ClassNotFoundException - if the class cannot be located // Java program to demonstrate forName() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName("Test"); ClassLoader loader = myClass.getClassLoader(); // forName method // it returns the Class object for the class // with the specified name using the given class loader Class c = Class.forName("java.lang.String",true,loader); System.out.print("Class represented by c : " + c.toString()); }}Output:Class represented by c : class java.lang.String T newInstance() : This method creates a new instance of the class represented by this Class object. The class is created as if by a new expression with an empty argument list. The class is initialized if it has not already been initialized.Syntax : public T newInstance() throws InstantiationException,IllegalAccessException TypeParameters : T - The class type whose instance is to be returned Parameters : NA Returns : a newly allocated instance of the class represented by this object. Throws : IllegalAccessException - if the class or its nullary constructor is not accessible. InstantiationException - if this Class represents an abstract class, an interface, an array class, a primitive type, or void or if the class has no nullary constructor; or if the instantiation fails for some other reason. ExceptionInInitializerError - if the initialization provoked by this method fails. SecurityException - If a security manager, s, is present // Java program to demonstrate newInstance() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException { // returns the Class object for this class Class myClass = Class.forName("Test"); // creating new instance of this class // newInstance method Object obj = myClass.newInstance(); // returns the runtime class of obj System.out.println("Class of obj : " + obj.getClass()); }}Output:Class of obj : class Test boolean isInstance(Object obj) : This method determines if the specified Object is assignment-compatible with the object represented by this Class. It is equivalent to instanceof operator in java.Syntax : public boolean isInstance(Object obj) Parameters : obj - the object to check Returns : true if obj is an instance of this class else return false // Java program to demonstrate isInstance() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c = Class.forName("java.lang.String"); String s = "GeeksForGeeks"; int i = 10; // checking for Class instance // isInstance method boolean b1 = c.isInstance(s); boolean b2 = c.isInstance(i); System.out.println("is s instance of String : " + b1); System.out.println("is i instance of String : " + b1); }}Output:is s instance of String : true is i instance of String : false boolean isAssignableFrom(Class<?> cls) : This method determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface, of the class or interface represented by the specified Class parameter.Syntax : public boolean isAssignableFrom(Class<?> cls) Parameters : cls - the Class object to be checked Returns : true if objects of the type cls can be assigned to objects of this class Throws: NullPointerException - if the specified Class parameter is null. // Java program to demonstrate isAssignableFrom() methodpublic class Test extends Thread{ public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException { // returns the Class object for this class Class myClass = Class.forName("Test"); // returns the Class object for the class // with the specified name Class c1 = Class.forName("java.lang.Thread"); Class c2 = Class.forName("java.lang.String"); // isAssignableFrom method on c1 // it checks whether Thread class is assignable from Test boolean b1 = c1.isAssignableFrom(myClass); // isAssignableFrom method on c2 // it checks whether String class is assignable from Test boolean b2 = c2.isAssignableFrom(myClass); System.out.println("is Thread class Assignable from Test : " + b1); System.out.println("is String class Assignable from Test : " + b2); }}Output:is Thread class Assignable from Test : true is String class Assignable from Test : false boolean isInterface() : This method determines if the specified Class object represents an interface type.Syntax : public boolean isInterface() Parameters : NA Returns : return true if and only if this class represents an interface type else return false // Java program to demonstrate isInterface() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName("java.lang.String"); Class c2 = Class.forName("java.lang.Runnable"); // checking for interface type // isInterface method on c1 boolean b1 = c1.isInterface(); // is Interface method on c2 boolean b2 = c2.isInterface(); System.out.println("is java.lang.String an interface : " + b1); System.out.println("is java.lang.Runnable an interface : " + b2); }}Output:is java.lang.String an interface : false is java.lang.Runnable an interface : true boolean isPrimitive() : This method determines if the specified Class object represents a primitive type.Syntax : public boolean isPrimitive() Parameters : NA Returns : return true if and only if this class represents a primitive type else return false // Java program to demonstrate isPrimitive methodpublic class Test{ public static void main(String[] args) { // returns the Class object associated with an integer; Class c1 = int.class; // returns the Class object associated with Test class Class c2 = Test.class; // checking for primitive type // isPrimitive method on c1 boolean b1 = c1.isPrimitive(); // isPrimitive method on c2 boolean b2 = c2.isPrimitive(); System.out.println("is "+c1.toString()+" primitive : " + b1); System.out.println("is "+c2.toString()+" primitive : " + b2); }}Output:is int primitive : true is class Test primitive : false boolean isArray() : This method determines if the specified Class object represents an array class.Syntax : public boolean isArray() Parameters : NA Returns : return true if and only if this class represents an array type else return false // Java program to demonstrate isArray methodpublic class Test{ public static void main(String[] args) { int a[] = new int[2]; // returns the Class object for array class Class c1 = a.getClass(); // returns the Class object for Test class Class c2 = Test.class; // checking for array type // isArray method on c1 boolean b1 = c1.isArray(); // is Array method on c2 boolean b2 = c2.isArray(); System.out.println("is "+c1.toString()+" an array : " + b1); System.out.println("is "+c2.toString()+" an array : " + b2); }}Output:is class [I an array : true is class Test an array : false boolean isAnonymousClass() : This method returns true if and only if the this class is an anonymous class. A anonymous class is a like a local classes except that they do not have a name.Syntax : public boolean isAnonymousClass() Parameters : NA Returns : true if and only if this class is an anonymous class. false,otherwise. boolean isLocalClass() : This method returns true if and only if the this class is a local class. A local class is a class that is declared locally within a block of Java code, rather than as a member of a class.Syntax : public boolean isLocalClass() Parameters : NA Returns : true if and only if this class is a local class. false,otherwise. boolean isMemberClass() : This method returns true if and only if the this class is a Member class.A member class is a class that is declared as a non-static member of a containing class.Syntax : public boolean isMemberClass() Parameters : NA Returns : true if and only if this class is a Member class. false,otherwise. Below is the Java program explaining uses of isAnonymousClass() ,isLocalClass and isMemberClass() methods.// Java program to demonstrate isAnonymousClass() ,isLocalClass // and isMemberClass() method public class Test{ // any Member class of Test class A{} public static void main(String[] args) { // declaring an anonymous class Test t1 = new Test() { // class definition of anonymous class }; // returns the Class object associated with t1 object Class c1 = t1.getClass(); // returns the Class object associated with Test class Class c2 = Test.class; // returns the Class object associated with A class Class c3 = A.class; // checking for Anonymous class // isAnonymousClass method boolean b1 = c1.isAnonymousClass(); System.out.println("is "+c1.toString()+" an anonymous class : "+b1); // checking for Local class // isLocalClass method boolean b2 = c2.isLocalClass(); System.out.println("is "+c2.toString()+" a local class : " + b2); // checking for Member class // isMemberClass method boolean b3 = c3.isMemberClass(); System.out.println("is "+c3.toString()+" a member class : " + b3); }}Output:is class Test$1 an anonymous class : true is class Test a local class : false is class Test$A a member class : true boolean isEnum() : This method returns true if and only if this class was declared as an enum in the source code.Syntax : public boolean isEnum() Parameters : NA Returns : true iff this class was declared as an enum in the source code. false,otherwise. // Java program to demonstrate isEnum() method enum Color{ RED, GREEN, BLUE;} public class Test{ public static void main(String[] args) { // returns the Class object associated with Color(an enum class) Class c1 = Color.class; // returns the Class object associated with Test class Class c2 = Test.class; // checking for Enum class // isEnum method boolean b1 = c1.isEnum(); boolean b2 = c2.isEnum(); System.out.println("is "+c1.toString()+" an Enum class : " + b1); System.out.println("is "+c2.toString()+" an Enum class : " + b2); }}Output:is class Color an Enum class : true is class Test an Enum class : false boolean isAnnotation() : This method determines if this Class object represents an annotation type. Note that if this method returns true, isInterface() method will also return true, as all annotation types are also interfaces.Syntax : public boolean isAnnotation() Parameters : NA Returns : return true if and only if this class represents an annotation type else return false // Java program to demonstrate isAnnotation() method // declaring an Annotation Type@interface A{ // Annotation element definitions} public class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object associated with A annotation Class c1 = A.class; // returns the Class object associated with Test class Class c2 = Test.class; // checking for annotation type // isAnnotation method boolean b1 = c1.isAnnotation(); boolean b2 = c2.isAnnotation(); System.out.println("is "+c1.toString()+" an annotation : " + b1); System.out.println("is "+c2.toString()+" an annotation : " + b2); }}Output:is interface A an annotation : true is class Test an annotation : false String getName() : This method returns the name of the entity (class, interface, array class, primitive type, or void) represented by this Class object, as a String.Syntax : public String getName() Parameters : NA Returns : returns the name of the name of the entity represented by this object. // Java program to demonstrate getName() methodpublic class Test{ public static void main(String[] args) { // returns the Class object associated with Test class Class c = Test.class; System.out.print("Class Name associated with c : "); // returns the name of the class // getName method System.out.println(c.getName()); }}Output:Class Name associated with c : Test String getSimpleName() : This method returns the name of the underlying class as given in the source code. It returns an empty string if the underlying class is anonymous class.The simple name of an array is the simple name of the component type with “[]” appended. In particular the simple name of an array whose component type is anonymous is “[]”.Syntax : public String getSimpleName() Parameters : NA Returns : the simple name of the underlying class // Java program to demonstrate getSimpleName() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName("java.lang.String"); System.out.print("Class Name associated with c : "); // returns the name of the class // getName method System.out.println(c1.getName()); System.out.print("Simple class Name associated with c : "); // returns the simple name of the class // getSimpleName method System.out.println(c1.getSimpleName()); }}Output:Class Name associated with c : java.lang.String Simple class Name associated with c : String ClassLoader getClassLoader() : This method returns the class loader for this class. If the class loader is bootstrap classloader then this method returned null, as bootstrap classloader is implemented in native languages like C, C++.If this object represents a primitive type or void,then also null is returned.Syntax : public ClassLoader getClassLoader() Parameters : NA Returns : the class loader that loaded the class or interface represented by this object represented by this object. Throws : SecurityException - If a security manager and its checkPermission method denies access to the class loader for the class. // Java program to demonstrate getClassLoader() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName("Test"); // returns the Class object for the class // with the specified name Class c1 = Class.forName("java.lang.String"); // returns the Class object for primitive int Class c2 = int.class; System.out.print("Test class loader : "); // getting the class loader for Test class // getClassLoader method on myClass System.out.println(myClass.getClassLoader()); System.out.print("String class loader : "); // getting the class loader for String class // we will get null as String class is loaded // by BootStrap class loader // getClassLoader method on c1 System.out.println(c1.getClassLoader()); System.out.print("primitive int loader : "); // getting the class loader for primitive int // getClassLoader method on c2 System.out.println(c2.getClassLoader()); }}Output:Test class loader : sun.misc.Launcher$AppClassLoader@73d16e93 String class loader : null primitive int loader : null TypeVariable<Class<T>>[ ] getTypeParameters() : This method returns an array of TypeVariable objects that represent the type variables declared by the generic declaration represented by this GenericDeclaration object, in declaration orderSyntax : public TypeVariable<Class<T>>[] getTypeParameters() Specified by: getTypeParameters in interface GenericDeclaration Parameters : NA Returns : an array of TypeVariable objects that represent the type variables declared by this generic declaration represented by this object. Throws : GenericSignatureFormatError - if the generic signature of this generic declaration does not conform to the format specified in JVM. // Java program to demonstrate getTypeParameters() method import java.lang.reflect.TypeVariable; public class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c = Class.forName("java.util.Set"); // getting array of TypeVariable for myClass object // getTypeParameters method TypeVariable[] tv = c.getTypeParameters(); System.out.println("TypeVariables in "+c.getName()+" class : "); // iterating through all TypeVariables for (TypeVariable typeVariable : tv) { System.out.println(typeVariable); } }}Output:TypeVariables in java.util.Set class : E Class<? super T> getSuperclass() : This method returns the Class representing the superclass of the entity (class, interface, primitive type or void) represented by this Class.If this Class represents either the Object class, an interface, a primitive type, or void, then null is returned.If this object represents an array class then the Class object representing the Object class is returned.Syntax : public Class<? super T> getSuperclass() Parameters : NA Returns : the superclass of the class represented by this object // Java program to demonstrate getSuperclass() method // base classclass A{ // methods and fields} // derived classclass B extends A{ } // Driver classpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object associated with Test class Class myClass = Test.class; // returns the Class object for the class // with the specified name Class c1 = Class.forName("A"); Class c2 = Class.forName("B"); Class c3 = Class.forName("java.lang.Object"); // getSuperclass method returns the superclass of the class represented // by this class object System.out.print("Test superclass : "); // getSuperclass method on myClass System.out.println(myClass.getSuperclass()); System.out.print("A superclass : "); // getSuperclass method on c1 System.out.println(c1.getSuperclass()); System.out.print("B superclass : "); // getSuperclass method on c2 System.out.println(c2.getSuperclass()); System.out.print("Object superclass : "); // getSuperclass method on c3 System.out.println(c3.getSuperclass()); }}Output:Test superclass : class java.lang.Object A superclass : class java.lang.Object B superclass : class A Object superclass : null Type getGenericSuperclass() : This method returns the Type representing the direct superclass of the entity (class, interface, primitive type or void) represented by this Class.If this Class represents either the Object class, an interface, a primitive type, or void, then null is returned. If this object represents an array class then the Class object representing the Object class is returned.Syntax : public Type getGenericSuperclass() Parameters : NA Returns : the superclass of the class represented by this object Throws: GenericSignatureFormatError - if the generic class signature does not conform to the format specified in JVM TypeNotPresentException - if the generic superclass refers to a non-existent type declaration MalformedParameterizedTypeException - if the generic superclass refers to a parameterized type that cannot be instantiated for any reason // Java program to demonstrate // getGenericSuperclass() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object associated with Test class Class myClass = Test.class; // returns the Class object for the class // with the specified name Class c1 = Class.forName("java.util.ArrayList"); Class c3 = Class.forName("java.lang.Object"); // getGenericSuperclass method returns the generic // superclass of the class represented // by this class object System.out.print("Test superclass : "); // getGenericSuperclass method on myClass System.out.println(myClass.getGenericSuperclass()); System.out.print("ArrayList superclass : "); // getGenericSuperclass method on c1 System.out.println(c1.getGenericSuperclass()); System.out.print("Object superclass : "); // getGenericSuperclass method on c3 System.out.println(c3.getGenericSuperclass()); }}Output:Test superclass : class java.lang.Object Set superclass : java.util.AbstractList<E> Object superclass : null Class<?>[] getInterfaces() : This method returns the interfaces implemented by the class or interface represented by this object.If this object represents a class or interface that implements no interfaces, the method returns an array of length 0.If this object represents a primitive type or void, the method returns an array of length 0.Syntax : public Class<?>[] getInterfaces() Parameters : NA Returns : an array of interfaces implemented by this class. // Java program to demonstrate getInterfaces() method // base interfaceinterface A{ // methods and constant declarations} // derived classclass B implements A{ // methods implementations that were declared in A} // Driver classpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName("B"); Class c2 = Class.forName("java.lang.String"); // getInterface method on c1 // it returns the interfaces implemented by B class Class c1Interfaces[] = c1.getInterfaces(); // getInterface method on c2 // returns the interfaces implemented by String class Class c2Interfaces[] = c2.getInterfaces(); System.out.println("interfaces implemented by B class : "); // iterating through B class interfaces for (Class class1 : c1Interfaces) { System.out.println(class1); } System.out.println("interfaces implemented by String class : "); // iterating through String class interfaces for (Class class1 : c2Interfaces) { System.out.println(class1); } }}Output:interfaces implemented by B class : interface A interfaces implemented by String class : interface java.io.Serializable interface java.lang.Comparable interface java.lang.CharSequence Type[] getGenericInterfaces() : This method returns the Types representing the interfaces directly implemented by the class or interface represented by this object.If this object represents a class or interface that implements no interfaces, the method returns an array of length 0.If this object represents a primitive type or void, the method returns an array of length 0.Syntax : public Type[] getGenericInterfaces() Parameters : NA Returns : an array of interfaces implemented by this class Throws: GenericSignatureFormatError - if the generic class signature does not conform to the format specified in JVM TypeNotPresentException - if the generic superinterfaces refers to a non-existent type declaration MalformedParameterizedTypeException - if the generic superinterfaces refers to a parameterized type that cannot be instantiated for any reason // Java program to demonstrate getGenericInterfaces() method import java.lang.reflect.Type; public class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName("java.util.Set"); // getGenericInterfaces() on c1 // it returns the interfaces implemented by Set interface Type c1GenericInterfaces[] = c1.getGenericInterfaces(); System.out.println("interfaces implemented by Set interface : "); // iterating through Set class interfaces for (Type type : c1GenericInterfaces) { System.out.println(type); } }}Output:interfaces implemented by Set interface : java.util.Collection<E> Package getPackage() : This method returns the package for this class. The classloader subsystem in JVM Architecture used this method to find the package of a class or interface.Syntax : public Package getPackage() Parameters : NA Returns : the package of the class, or null if no package information is available from the archive or codebase. // Java program to demonstrate getPackage() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName("java.lang.String"); Class c2 = Class.forName("java.util.ArrayList"); // getting package of class // getPackage method on c1 System.out.println(c1.getPackage()); // getPackage method on c2 System.out.println(c2.getPackage()); }}Output:package java.lang, Java Platform API Specification, version 1.8 package java.util, Java Platform API Specification, version 1.8 Field[] getFields() : This method returns an array of Field objects reflecting all the accessible public fields of the class(and of all its superclasses) or interface(and of all its superclasses) represented by this Class object.Syntax : public Field[] getFields() throws SecurityException Parameters : NA Returns : the array of Field objects representing the public fields and array of length 0 if the class or interface has no accessible public fields or if this Class object represents a primitive type or void. Throws : SecurityException - If a security manager, s, is present. // Java program to demonstrate getFields() method import java.lang.reflect.Field; public class Test{ public static void main(String[] args) throws SecurityException,ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName("java.lang.Integer"); // getFields method on c1 // it array of fields of Integer class Field F[] = c1.getFields(); System.out.println("Below are the fields of Integer class : "); // iterating through all fields of String class for (Field field : F) { System.out.println(field); } }}Output :Below are the fields of Integer class : public static final int java.lang.Integer.MIN_VALUE public static final int java.lang.Integer.MAX_VALUE public static final java.lang.Class java.lang.Integer.TYPE public static final int java.lang.Integer.SIZE public static final int java.lang.Integer.BYTES Class<?>[ ] getClasses() : This method returns an array containing Class objects representing all the public classes and interfaces that are members of the class represented by this Class object. The array contains public class and interface members inherited from superclasses and public class and interface members declared by the class.This method returns an array of length 0 if this Class object has no public member classes or interfaces.This method also returns an array of length 0 if this Class object represents a primitive type, an array class, or void.Syntax : Class<?>[ ] getClasses() Parameters : NA Returns : the array of Class objects representing the public members of this class Throws : SecurityException - If a security manager, s, is present. // Java program to demonstrate getClasses() method public class Test{ // base interface public interface A { // methods and constant declarations } // derived class public class B implements A { // methods implementations that were declared in A } public static void main(String[] args) throws ClassNotFoundException { // returns the Class object associated with Test class Class c1 = Test.class; // getClasses method on c1 // it returns the array of Class objects containing the all // public classes and interfaces represented by Test class Class[] c1Classes = c1.getClasses(); System.out.println("public members of Test class : "); // iterating through all public members of Test class for (Class class1 : c1Classes) { System.out.println(class1); } }}Output:public members of Test class : interface Test$A class Test$B Method[] getMethods() : This method returns an array of Method objects reflecting all the accessible public methods of the class or interface and those inherited from superclasses and super interfaces represented by this Class object.Syntax : public Method[] getMethods() throws SecurityException Parameters : NA Returns : the array of Method objects representing the public methods and array of length 0 if the class or interface has no accessible public method or if this Class object represents a primitive type or void. Throws : SecurityException - If a security manager, s, is present. // Java program to demonstrate getMethods() method import java.lang.reflect.Method; public class Test{ public static void main(String[] args) throws SecurityException,ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName("java.lang.Object"); // getMethods method on c1 // it returns array of methods of Object class Method M[] = c1.getMethods(); System.out.println("Below are the methods of Object class : "); // iterating through all methods of Object class for (Method method : M) { System.out.println(method); } }}Output:Below are the methods of Object class : public final void java.lang.Object.wait() throws java.lang.InterruptedException public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException public boolean java.lang.Object.equals(java.lang.Object) public java.lang.String java.lang.Object.toString() public native int java.lang.Object.hashCode() public final native java.lang.Class java.lang.Object.getClass() public final native void java.lang.Object.notify() public final native void java.lang.Object.notifyAll() Constructor<?>[] getConstructors() : This method returns an array of Constructor objects reflecting all the public constructors of the class represented by this Class object.Syntax : public Constructor<?>[] getConstructors() throws SecurityException Parameters : NA Returns : the array of Constructor objects representing the public constructors of this class and array of length 0 if the class or interface has no accessible public constructor or if this Class object represents a primitive type or void. Throws : SecurityException - If a security manager, s, is present. // Java program to demonstrate getConstructors() method import java.lang.reflect.Constructor; public class Test{ public static void main(String[] args) throws SecurityException,ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName("java.lang.Boolean"); // getConstructor method on c1 // it returns an array of constructors of Boolean class Constructor C[] = c1.getConstructors(); System.out.println("Below are the constructors of Boolean class :"); // iterating through all constructors for (Constructor constructor : C) { System.out.println(constructor); } }}Output:Below are the constructors of Boolean class : public java.lang.Boolean(boolean) public java.lang.Boolean(java.lang.String) Field getField(String fieldName) : This method returns a Field object that reflects the specified public member field of the class or interface represented by this Class object.Syntax : public Field getField(String fieldName) throws NoSuchFieldException,SecurityException Parameters : fieldName - the field name Returns : the Field object of this class specified by name Throws : NoSuchFieldException - if a field with the specified name is not found. NullPointerException - if fieldName is null SecurityException - If a security manager, s, is present. // Java program to demonstrate getField() method import java.lang.reflect.Field; public class Test{ public static void main(String[] args) throws SecurityException,ClassNotFoundException, NoSuchFieldException { // returns the Class object for the class // with the specified name Class c1 = Class.forName("java.lang.Integer"); // getField method on c1 // it checks a public field in Integer class with specified parameter Field f = c1.getField("MIN_VALUE"); System.out.println("public field in Integer class with MIN_VALUE name :"); System.out.println(f); }}Output:public field in Integer class with MIN_VALUE name : public static final int java.lang.Integer.MIN_VALUE Method getMethod(String methodName,Class... parameterTypes) : This method returns a Method object that reflects the specified public member method of the class or interface represented by this Class object.Syntax : public Method getMethod(String methodName,Class... parameterTypes) throws NoSuchFieldException,SecurityException Parameters : methodName - the method name parameterTypes - the list of parameters Returns : the method object of this class specified by name Throws : NoSuchMethodException - if a method with the specified name is not found. NullPointerException - if methodName is null SecurityException - If a security manager, s, is present. // Java program to demonstrate getMethod() method import java.lang.reflect.Method; public class Test{ public static void main(String[] args) throws SecurityException,ClassNotFoundException, NoSuchMethodException { // returns the Class object for the class // with the specified name Class c1 = Class.forName("java.lang.Integer"); Class c2 = Class.forName("java.lang.String"); // getMethod method on c1 // it checks for a public Method in Integer class Method m = c1.getMethod("parseInt",c2); System.out.println("method in Integer class specified by parseInt : "); System.out.println(m); }}Output:public method in Integer class specified by parseInt : public static int java.lang.Integer.parseInt(java.lang.String) throws java.lang.NumberFormatException Constructor<?> getConstructor(Class<?>... parameterTypes) : This method returns a Constructor object that reflects the specified public constructor of the class represented by this Class object.The parameterTypes parameter is an array of Class objects that identify the constructor’s formal parameter types, in declared order.Syntax : public Constructor<?> getConstructor(Class<?>... parameterTypes) throws NoSuchMethodException,SecurityException Parameters : parameterTypes - the list of parameters Returns : the Constructor object of the public constructor that matches the specified parameterTypes Throws : NoSuchMethodException - if a Constructor with the specified parameterTypes is not found. SecurityException - If a security manager, s, is present. // Java program to demonstrate // getConstructor() Constructor import java.lang.reflect.Constructor; public class Test{ public static void main(String[] args) throws SecurityException,ClassNotFoundException, NoSuchMethodException { // returns the Class object for the class // with the specified name Class c1 = Class.forName("java.lang.Integer"); Class c2 = Class.forName("java.lang.String"); // getConstructor method on c1 // it checks a public Constructor in Integer class // with specified parameterTypes Constructor c = c1.getConstructor(c2); System.out.println("Constructor in Integer class & String parameterType:"); System.out.println(c); }}Output:public Constructor in Integer class with String parameterType : public java.lang.Integer(java.lang.String) throws java.lang.NumberFormatException Note : The methods getFields(), getMethods(),getConstructors(), getField(), getMethod(), getConstructor() are widely used in Reflection(Refer this for example)T cast(Object obj) : This method is used to casts an object to the class or interface represented by this Class object.Syntax : public T cast(Object obj) TypeParameters : T - The class type whose object is to be cast Parameters : obj - the object to be cast Returns : the object after casting, or null if obj is null Throws : ClassCastException - if the object is not null and is not assignable to the type T. // Java program to demonstrate cast() methodclass A{ // methods and fields} class B extends A { // methods and fields} // Driver Classpublic class Test{ public static void main(String[] args) { A a = new A(); System.out.println(a.getClass()); B b = new B(); // casting b to a // cast method a = A.class.cast(b); System.out.println(a.getClass()); }}Output:class A class B <U> Class<? extends U> asSubclass(Class<U> clazz) : This method is used to cast this Class object to represent a subclass of the class represented by the specified class object.It always returns a reference to this class object.Syntax : public <U> Class<? extends U> asSubclass(Class<U> class) TypeParameters : U - The superclass type whose object is to be cast Parameters : clazz - the superclass object to be cast Returns : this Class object, cast to represent a subclass of the specified class object. Throws : ClassCastException - if this Class object does not represent a subclass of the specified class (here "subclass" includes the class itself). // Java program to demonstrate asSubclass() methodclass A{ // methods and fields} class B extends A { // methods and fields} // Driver Classpublic class Test{ public static void main(String[] args) { A a = new A(); // returns the Class object for super class(A) Class superClass = a.getClass(); B b = new B(); // returns the Class object for subclass(B) Class subClass = b.getClass(); // asSubclass method // it represent a subclass of the specified class object Class cast = subClass.asSubclass(superClass); System.out.println(cast); }}Output:class B This article is contributed by Gaurav Miglani. 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 String toString() : This method converts the Class object to a string. It returns the string representation which is the string “class” or “interface”, followed by a space, and then by the fully qualified name of the class. If the Class object represents a primitive type, then this method returns the name of the primitive type and if it represents void then it returns “void”.Syntax : public String toString() Parameters : NA Returns : a string representation of this class object. Overrides : toString in class Object // Java program to demonstrate toString() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName("java.lang.String"); Class c2 = int.class; Class c3 = void.class; System.out.print("Class represented by c1: "); // toString method on c1 System.out.println(c1.toString()); System.out.print("Class represented by c2: "); // toString method on c2 System.out.println(c2.toString()); System.out.print("Class represented by c3: "); // toString method on c3 System.out.println(c3.toString()); }}Output:Class represented by c1: class java.lang.String Class represented by c2: int Class represented by c3: void Syntax : public String toString() Parameters : NA Returns : a string representation of this class object. Overrides : toString in class Object // Java program to demonstrate toString() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName("java.lang.String"); Class c2 = int.class; Class c3 = void.class; System.out.print("Class represented by c1: "); // toString method on c1 System.out.println(c1.toString()); System.out.print("Class represented by c2: "); // toString method on c2 System.out.println(c2.toString()); System.out.print("Class represented by c3: "); // toString method on c3 System.out.println(c3.toString()); }} Output: Class represented by c1: class java.lang.String Class represented by c2: int Class represented by c3: void Class<?> forName(String className) : As discussed earlier, this method returns the Class object associated with the class or interface with the given string name. The other variant of this method is discussed next.Syntax : public static Class<?> forName(String className) throws ClassNotFoundException Parameters : className - the fully qualified name of the desired class. Returns : return the Class object for the class with the specified name. Throws : LinkageError : if the linkage fails ExceptionInInitializerError - if the initialization provoked by this method fails ClassNotFoundException - if the class cannot be located // Java program to demonstrate forName() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // forName method // it returns the Class object for the class // with the specified name Class c = Class.forName("java.lang.String"); System.out.print("Class represented by c : " + c.toString()); }}Output:Class represented by c : class java.lang.String Syntax : public static Class<?> forName(String className) throws ClassNotFoundException Parameters : className - the fully qualified name of the desired class. Returns : return the Class object for the class with the specified name. Throws : LinkageError : if the linkage fails ExceptionInInitializerError - if the initialization provoked by this method fails ClassNotFoundException - if the class cannot be located // Java program to demonstrate forName() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // forName method // it returns the Class object for the class // with the specified name Class c = Class.forName("java.lang.String"); System.out.print("Class represented by c : " + c.toString()); }} Output: Class represented by c : class java.lang.String Class<?> forName(String className,boolean initialize, ClassLoader loader) : This method also returns the Class object associated with the class or interface with the given string name using the given class loader.The specified class loader is used to load the class or interface. If the parameter loader is null, the class is loaded through the bootstrap class loader in. The class is initialized only if the initialize parameter is true and if it has not been initialized earlier.Syntax : public static Class<?> forName(String className,boolean initialize, ClassLoader loader) throws ClassNotFoundException Parameters : className - the fully qualified name of the desired class initialize - whether the class must be initialized loader - class loader from which the class must be loaded Returns : return the Class object for the class with the specified name. Throws : LinkageError : if the linkage fails ExceptionInInitializerError - if the initialization provoked by this method fails ClassNotFoundException - if the class cannot be located // Java program to demonstrate forName() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName("Test"); ClassLoader loader = myClass.getClassLoader(); // forName method // it returns the Class object for the class // with the specified name using the given class loader Class c = Class.forName("java.lang.String",true,loader); System.out.print("Class represented by c : " + c.toString()); }}Output:Class represented by c : class java.lang.String The specified class loader is used to load the class or interface. If the parameter loader is null, the class is loaded through the bootstrap class loader in. The class is initialized only if the initialize parameter is true and if it has not been initialized earlier. Syntax : public static Class<?> forName(String className,boolean initialize, ClassLoader loader) throws ClassNotFoundException Parameters : className - the fully qualified name of the desired class initialize - whether the class must be initialized loader - class loader from which the class must be loaded Returns : return the Class object for the class with the specified name. Throws : LinkageError : if the linkage fails ExceptionInInitializerError - if the initialization provoked by this method fails ClassNotFoundException - if the class cannot be located // Java program to demonstrate forName() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName("Test"); ClassLoader loader = myClass.getClassLoader(); // forName method // it returns the Class object for the class // with the specified name using the given class loader Class c = Class.forName("java.lang.String",true,loader); System.out.print("Class represented by c : " + c.toString()); }} Output: Class represented by c : class java.lang.String T newInstance() : This method creates a new instance of the class represented by this Class object. The class is created as if by a new expression with an empty argument list. The class is initialized if it has not already been initialized.Syntax : public T newInstance() throws InstantiationException,IllegalAccessException TypeParameters : T - The class type whose instance is to be returned Parameters : NA Returns : a newly allocated instance of the class represented by this object. Throws : IllegalAccessException - if the class or its nullary constructor is not accessible. InstantiationException - if this Class represents an abstract class, an interface, an array class, a primitive type, or void or if the class has no nullary constructor; or if the instantiation fails for some other reason. ExceptionInInitializerError - if the initialization provoked by this method fails. SecurityException - If a security manager, s, is present // Java program to demonstrate newInstance() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException { // returns the Class object for this class Class myClass = Class.forName("Test"); // creating new instance of this class // newInstance method Object obj = myClass.newInstance(); // returns the runtime class of obj System.out.println("Class of obj : " + obj.getClass()); }}Output:Class of obj : class Test Syntax : public T newInstance() throws InstantiationException,IllegalAccessException TypeParameters : T - The class type whose instance is to be returned Parameters : NA Returns : a newly allocated instance of the class represented by this object. Throws : IllegalAccessException - if the class or its nullary constructor is not accessible. InstantiationException - if this Class represents an abstract class, an interface, an array class, a primitive type, or void or if the class has no nullary constructor; or if the instantiation fails for some other reason. ExceptionInInitializerError - if the initialization provoked by this method fails. SecurityException - If a security manager, s, is present // Java program to demonstrate newInstance() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException { // returns the Class object for this class Class myClass = Class.forName("Test"); // creating new instance of this class // newInstance method Object obj = myClass.newInstance(); // returns the runtime class of obj System.out.println("Class of obj : " + obj.getClass()); }} Output: Class of obj : class Test boolean isInstance(Object obj) : This method determines if the specified Object is assignment-compatible with the object represented by this Class. It is equivalent to instanceof operator in java.Syntax : public boolean isInstance(Object obj) Parameters : obj - the object to check Returns : true if obj is an instance of this class else return false // Java program to demonstrate isInstance() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c = Class.forName("java.lang.String"); String s = "GeeksForGeeks"; int i = 10; // checking for Class instance // isInstance method boolean b1 = c.isInstance(s); boolean b2 = c.isInstance(i); System.out.println("is s instance of String : " + b1); System.out.println("is i instance of String : " + b1); }}Output:is s instance of String : true is i instance of String : false Syntax : public boolean isInstance(Object obj) Parameters : obj - the object to check Returns : true if obj is an instance of this class else return false // Java program to demonstrate isInstance() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c = Class.forName("java.lang.String"); String s = "GeeksForGeeks"; int i = 10; // checking for Class instance // isInstance method boolean b1 = c.isInstance(s); boolean b2 = c.isInstance(i); System.out.println("is s instance of String : " + b1); System.out.println("is i instance of String : " + b1); }} Output: is s instance of String : true is i instance of String : false boolean isAssignableFrom(Class<?> cls) : This method determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface, of the class or interface represented by the specified Class parameter.Syntax : public boolean isAssignableFrom(Class<?> cls) Parameters : cls - the Class object to be checked Returns : true if objects of the type cls can be assigned to objects of this class Throws: NullPointerException - if the specified Class parameter is null. // Java program to demonstrate isAssignableFrom() methodpublic class Test extends Thread{ public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException { // returns the Class object for this class Class myClass = Class.forName("Test"); // returns the Class object for the class // with the specified name Class c1 = Class.forName("java.lang.Thread"); Class c2 = Class.forName("java.lang.String"); // isAssignableFrom method on c1 // it checks whether Thread class is assignable from Test boolean b1 = c1.isAssignableFrom(myClass); // isAssignableFrom method on c2 // it checks whether String class is assignable from Test boolean b2 = c2.isAssignableFrom(myClass); System.out.println("is Thread class Assignable from Test : " + b1); System.out.println("is String class Assignable from Test : " + b2); }}Output:is Thread class Assignable from Test : true is String class Assignable from Test : false Syntax : public boolean isAssignableFrom(Class<?> cls) Parameters : cls - the Class object to be checked Returns : true if objects of the type cls can be assigned to objects of this class Throws: NullPointerException - if the specified Class parameter is null. // Java program to demonstrate isAssignableFrom() methodpublic class Test extends Thread{ public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException { // returns the Class object for this class Class myClass = Class.forName("Test"); // returns the Class object for the class // with the specified name Class c1 = Class.forName("java.lang.Thread"); Class c2 = Class.forName("java.lang.String"); // isAssignableFrom method on c1 // it checks whether Thread class is assignable from Test boolean b1 = c1.isAssignableFrom(myClass); // isAssignableFrom method on c2 // it checks whether String class is assignable from Test boolean b2 = c2.isAssignableFrom(myClass); System.out.println("is Thread class Assignable from Test : " + b1); System.out.println("is String class Assignable from Test : " + b2); }} Output: is Thread class Assignable from Test : true is String class Assignable from Test : false boolean isInterface() : This method determines if the specified Class object represents an interface type.Syntax : public boolean isInterface() Parameters : NA Returns : return true if and only if this class represents an interface type else return false // Java program to demonstrate isInterface() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName("java.lang.String"); Class c2 = Class.forName("java.lang.Runnable"); // checking for interface type // isInterface method on c1 boolean b1 = c1.isInterface(); // is Interface method on c2 boolean b2 = c2.isInterface(); System.out.println("is java.lang.String an interface : " + b1); System.out.println("is java.lang.Runnable an interface : " + b2); }}Output:is java.lang.String an interface : false is java.lang.Runnable an interface : true Syntax : public boolean isInterface() Parameters : NA Returns : return true if and only if this class represents an interface type else return false // Java program to demonstrate isInterface() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName("java.lang.String"); Class c2 = Class.forName("java.lang.Runnable"); // checking for interface type // isInterface method on c1 boolean b1 = c1.isInterface(); // is Interface method on c2 boolean b2 = c2.isInterface(); System.out.println("is java.lang.String an interface : " + b1); System.out.println("is java.lang.Runnable an interface : " + b2); }} Output: is java.lang.String an interface : false is java.lang.Runnable an interface : true boolean isPrimitive() : This method determines if the specified Class object represents a primitive type.Syntax : public boolean isPrimitive() Parameters : NA Returns : return true if and only if this class represents a primitive type else return false // Java program to demonstrate isPrimitive methodpublic class Test{ public static void main(String[] args) { // returns the Class object associated with an integer; Class c1 = int.class; // returns the Class object associated with Test class Class c2 = Test.class; // checking for primitive type // isPrimitive method on c1 boolean b1 = c1.isPrimitive(); // isPrimitive method on c2 boolean b2 = c2.isPrimitive(); System.out.println("is "+c1.toString()+" primitive : " + b1); System.out.println("is "+c2.toString()+" primitive : " + b2); }}Output:is int primitive : true is class Test primitive : false Syntax : public boolean isPrimitive() Parameters : NA Returns : return true if and only if this class represents a primitive type else return false // Java program to demonstrate isPrimitive methodpublic class Test{ public static void main(String[] args) { // returns the Class object associated with an integer; Class c1 = int.class; // returns the Class object associated with Test class Class c2 = Test.class; // checking for primitive type // isPrimitive method on c1 boolean b1 = c1.isPrimitive(); // isPrimitive method on c2 boolean b2 = c2.isPrimitive(); System.out.println("is "+c1.toString()+" primitive : " + b1); System.out.println("is "+c2.toString()+" primitive : " + b2); }} Output: is int primitive : true is class Test primitive : false boolean isArray() : This method determines if the specified Class object represents an array class.Syntax : public boolean isArray() Parameters : NA Returns : return true if and only if this class represents an array type else return false // Java program to demonstrate isArray methodpublic class Test{ public static void main(String[] args) { int a[] = new int[2]; // returns the Class object for array class Class c1 = a.getClass(); // returns the Class object for Test class Class c2 = Test.class; // checking for array type // isArray method on c1 boolean b1 = c1.isArray(); // is Array method on c2 boolean b2 = c2.isArray(); System.out.println("is "+c1.toString()+" an array : " + b1); System.out.println("is "+c2.toString()+" an array : " + b2); }}Output:is class [I an array : true is class Test an array : false Syntax : public boolean isArray() Parameters : NA Returns : return true if and only if this class represents an array type else return false // Java program to demonstrate isArray methodpublic class Test{ public static void main(String[] args) { int a[] = new int[2]; // returns the Class object for array class Class c1 = a.getClass(); // returns the Class object for Test class Class c2 = Test.class; // checking for array type // isArray method on c1 boolean b1 = c1.isArray(); // is Array method on c2 boolean b2 = c2.isArray(); System.out.println("is "+c1.toString()+" an array : " + b1); System.out.println("is "+c2.toString()+" an array : " + b2); }} Output: is class [I an array : true is class Test an array : false boolean isAnonymousClass() : This method returns true if and only if the this class is an anonymous class. A anonymous class is a like a local classes except that they do not have a name.Syntax : public boolean isAnonymousClass() Parameters : NA Returns : true if and only if this class is an anonymous class. false,otherwise. Syntax : public boolean isAnonymousClass() Parameters : NA Returns : true if and only if this class is an anonymous class. false,otherwise. boolean isLocalClass() : This method returns true if and only if the this class is a local class. A local class is a class that is declared locally within a block of Java code, rather than as a member of a class.Syntax : public boolean isLocalClass() Parameters : NA Returns : true if and only if this class is a local class. false,otherwise. Syntax : public boolean isLocalClass() Parameters : NA Returns : true if and only if this class is a local class. false,otherwise. boolean isMemberClass() : This method returns true if and only if the this class is a Member class.A member class is a class that is declared as a non-static member of a containing class.Syntax : public boolean isMemberClass() Parameters : NA Returns : true if and only if this class is a Member class. false,otherwise. Below is the Java program explaining uses of isAnonymousClass() ,isLocalClass and isMemberClass() methods.// Java program to demonstrate isAnonymousClass() ,isLocalClass // and isMemberClass() method public class Test{ // any Member class of Test class A{} public static void main(String[] args) { // declaring an anonymous class Test t1 = new Test() { // class definition of anonymous class }; // returns the Class object associated with t1 object Class c1 = t1.getClass(); // returns the Class object associated with Test class Class c2 = Test.class; // returns the Class object associated with A class Class c3 = A.class; // checking for Anonymous class // isAnonymousClass method boolean b1 = c1.isAnonymousClass(); System.out.println("is "+c1.toString()+" an anonymous class : "+b1); // checking for Local class // isLocalClass method boolean b2 = c2.isLocalClass(); System.out.println("is "+c2.toString()+" a local class : " + b2); // checking for Member class // isMemberClass method boolean b3 = c3.isMemberClass(); System.out.println("is "+c3.toString()+" a member class : " + b3); }}Output:is class Test$1 an anonymous class : true is class Test a local class : false is class Test$A a member class : true Syntax : public boolean isMemberClass() Parameters : NA Returns : true if and only if this class is a Member class. false,otherwise. Below is the Java program explaining uses of isAnonymousClass() ,isLocalClass and isMemberClass() methods. // Java program to demonstrate isAnonymousClass() ,isLocalClass // and isMemberClass() method public class Test{ // any Member class of Test class A{} public static void main(String[] args) { // declaring an anonymous class Test t1 = new Test() { // class definition of anonymous class }; // returns the Class object associated with t1 object Class c1 = t1.getClass(); // returns the Class object associated with Test class Class c2 = Test.class; // returns the Class object associated with A class Class c3 = A.class; // checking for Anonymous class // isAnonymousClass method boolean b1 = c1.isAnonymousClass(); System.out.println("is "+c1.toString()+" an anonymous class : "+b1); // checking for Local class // isLocalClass method boolean b2 = c2.isLocalClass(); System.out.println("is "+c2.toString()+" a local class : " + b2); // checking for Member class // isMemberClass method boolean b3 = c3.isMemberClass(); System.out.println("is "+c3.toString()+" a member class : " + b3); }} Output: is class Test$1 an anonymous class : true is class Test a local class : false is class Test$A a member class : true boolean isEnum() : This method returns true if and only if this class was declared as an enum in the source code.Syntax : public boolean isEnum() Parameters : NA Returns : true iff this class was declared as an enum in the source code. false,otherwise. // Java program to demonstrate isEnum() method enum Color{ RED, GREEN, BLUE;} public class Test{ public static void main(String[] args) { // returns the Class object associated with Color(an enum class) Class c1 = Color.class; // returns the Class object associated with Test class Class c2 = Test.class; // checking for Enum class // isEnum method boolean b1 = c1.isEnum(); boolean b2 = c2.isEnum(); System.out.println("is "+c1.toString()+" an Enum class : " + b1); System.out.println("is "+c2.toString()+" an Enum class : " + b2); }}Output:is class Color an Enum class : true is class Test an Enum class : false Syntax : public boolean isEnum() Parameters : NA Returns : true iff this class was declared as an enum in the source code. false,otherwise. // Java program to demonstrate isEnum() method enum Color{ RED, GREEN, BLUE;} public class Test{ public static void main(String[] args) { // returns the Class object associated with Color(an enum class) Class c1 = Color.class; // returns the Class object associated with Test class Class c2 = Test.class; // checking for Enum class // isEnum method boolean b1 = c1.isEnum(); boolean b2 = c2.isEnum(); System.out.println("is "+c1.toString()+" an Enum class : " + b1); System.out.println("is "+c2.toString()+" an Enum class : " + b2); }} Output: is class Color an Enum class : true is class Test an Enum class : false boolean isAnnotation() : This method determines if this Class object represents an annotation type. Note that if this method returns true, isInterface() method will also return true, as all annotation types are also interfaces.Syntax : public boolean isAnnotation() Parameters : NA Returns : return true if and only if this class represents an annotation type else return false // Java program to demonstrate isAnnotation() method // declaring an Annotation Type@interface A{ // Annotation element definitions} public class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object associated with A annotation Class c1 = A.class; // returns the Class object associated with Test class Class c2 = Test.class; // checking for annotation type // isAnnotation method boolean b1 = c1.isAnnotation(); boolean b2 = c2.isAnnotation(); System.out.println("is "+c1.toString()+" an annotation : " + b1); System.out.println("is "+c2.toString()+" an annotation : " + b2); }}Output:is interface A an annotation : true is class Test an annotation : false Syntax : public boolean isAnnotation() Parameters : NA Returns : return true if and only if this class represents an annotation type else return false // Java program to demonstrate isAnnotation() method // declaring an Annotation Type@interface A{ // Annotation element definitions} public class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object associated with A annotation Class c1 = A.class; // returns the Class object associated with Test class Class c2 = Test.class; // checking for annotation type // isAnnotation method boolean b1 = c1.isAnnotation(); boolean b2 = c2.isAnnotation(); System.out.println("is "+c1.toString()+" an annotation : " + b1); System.out.println("is "+c2.toString()+" an annotation : " + b2); }} Output: is interface A an annotation : true is class Test an annotation : false String getName() : This method returns the name of the entity (class, interface, array class, primitive type, or void) represented by this Class object, as a String.Syntax : public String getName() Parameters : NA Returns : returns the name of the name of the entity represented by this object. // Java program to demonstrate getName() methodpublic class Test{ public static void main(String[] args) { // returns the Class object associated with Test class Class c = Test.class; System.out.print("Class Name associated with c : "); // returns the name of the class // getName method System.out.println(c.getName()); }}Output:Class Name associated with c : Test Syntax : public String getName() Parameters : NA Returns : returns the name of the name of the entity represented by this object. // Java program to demonstrate getName() methodpublic class Test{ public static void main(String[] args) { // returns the Class object associated with Test class Class c = Test.class; System.out.print("Class Name associated with c : "); // returns the name of the class // getName method System.out.println(c.getName()); }} Output: Class Name associated with c : Test String getSimpleName() : This method returns the name of the underlying class as given in the source code. It returns an empty string if the underlying class is anonymous class.The simple name of an array is the simple name of the component type with “[]” appended. In particular the simple name of an array whose component type is anonymous is “[]”.Syntax : public String getSimpleName() Parameters : NA Returns : the simple name of the underlying class // Java program to demonstrate getSimpleName() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName("java.lang.String"); System.out.print("Class Name associated with c : "); // returns the name of the class // getName method System.out.println(c1.getName()); System.out.print("Simple class Name associated with c : "); // returns the simple name of the class // getSimpleName method System.out.println(c1.getSimpleName()); }}Output:Class Name associated with c : java.lang.String Simple class Name associated with c : String The simple name of an array is the simple name of the component type with “[]” appended. In particular the simple name of an array whose component type is anonymous is “[]”. Syntax : public String getSimpleName() Parameters : NA Returns : the simple name of the underlying class // Java program to demonstrate getSimpleName() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName("java.lang.String"); System.out.print("Class Name associated with c : "); // returns the name of the class // getName method System.out.println(c1.getName()); System.out.print("Simple class Name associated with c : "); // returns the simple name of the class // getSimpleName method System.out.println(c1.getSimpleName()); }} Output: Class Name associated with c : java.lang.String Simple class Name associated with c : String ClassLoader getClassLoader() : This method returns the class loader for this class. If the class loader is bootstrap classloader then this method returned null, as bootstrap classloader is implemented in native languages like C, C++.If this object represents a primitive type or void,then also null is returned.Syntax : public ClassLoader getClassLoader() Parameters : NA Returns : the class loader that loaded the class or interface represented by this object represented by this object. Throws : SecurityException - If a security manager and its checkPermission method denies access to the class loader for the class. // Java program to demonstrate getClassLoader() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName("Test"); // returns the Class object for the class // with the specified name Class c1 = Class.forName("java.lang.String"); // returns the Class object for primitive int Class c2 = int.class; System.out.print("Test class loader : "); // getting the class loader for Test class // getClassLoader method on myClass System.out.println(myClass.getClassLoader()); System.out.print("String class loader : "); // getting the class loader for String class // we will get null as String class is loaded // by BootStrap class loader // getClassLoader method on c1 System.out.println(c1.getClassLoader()); System.out.print("primitive int loader : "); // getting the class loader for primitive int // getClassLoader method on c2 System.out.println(c2.getClassLoader()); }}Output:Test class loader : sun.misc.Launcher$AppClassLoader@73d16e93 String class loader : null primitive int loader : null Syntax : public ClassLoader getClassLoader() Parameters : NA Returns : the class loader that loaded the class or interface represented by this object represented by this object. Throws : SecurityException - If a security manager and its checkPermission method denies access to the class loader for the class. // Java program to demonstrate getClassLoader() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName("Test"); // returns the Class object for the class // with the specified name Class c1 = Class.forName("java.lang.String"); // returns the Class object for primitive int Class c2 = int.class; System.out.print("Test class loader : "); // getting the class loader for Test class // getClassLoader method on myClass System.out.println(myClass.getClassLoader()); System.out.print("String class loader : "); // getting the class loader for String class // we will get null as String class is loaded // by BootStrap class loader // getClassLoader method on c1 System.out.println(c1.getClassLoader()); System.out.print("primitive int loader : "); // getting the class loader for primitive int // getClassLoader method on c2 System.out.println(c2.getClassLoader()); }} Output: Test class loader : sun.misc.Launcher$AppClassLoader@73d16e93 String class loader : null primitive int loader : null TypeVariable<Class<T>>[ ] getTypeParameters() : This method returns an array of TypeVariable objects that represent the type variables declared by the generic declaration represented by this GenericDeclaration object, in declaration orderSyntax : public TypeVariable<Class<T>>[] getTypeParameters() Specified by: getTypeParameters in interface GenericDeclaration Parameters : NA Returns : an array of TypeVariable objects that represent the type variables declared by this generic declaration represented by this object. Throws : GenericSignatureFormatError - if the generic signature of this generic declaration does not conform to the format specified in JVM. // Java program to demonstrate getTypeParameters() method import java.lang.reflect.TypeVariable; public class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c = Class.forName("java.util.Set"); // getting array of TypeVariable for myClass object // getTypeParameters method TypeVariable[] tv = c.getTypeParameters(); System.out.println("TypeVariables in "+c.getName()+" class : "); // iterating through all TypeVariables for (TypeVariable typeVariable : tv) { System.out.println(typeVariable); } }}Output:TypeVariables in java.util.Set class : E Syntax : public TypeVariable<Class<T>>[] getTypeParameters() Specified by: getTypeParameters in interface GenericDeclaration Parameters : NA Returns : an array of TypeVariable objects that represent the type variables declared by this generic declaration represented by this object. Throws : GenericSignatureFormatError - if the generic signature of this generic declaration does not conform to the format specified in JVM. // Java program to demonstrate getTypeParameters() method import java.lang.reflect.TypeVariable; public class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c = Class.forName("java.util.Set"); // getting array of TypeVariable for myClass object // getTypeParameters method TypeVariable[] tv = c.getTypeParameters(); System.out.println("TypeVariables in "+c.getName()+" class : "); // iterating through all TypeVariables for (TypeVariable typeVariable : tv) { System.out.println(typeVariable); } }} Output: TypeVariables in java.util.Set class : E Class<? super T> getSuperclass() : This method returns the Class representing the superclass of the entity (class, interface, primitive type or void) represented by this Class.If this Class represents either the Object class, an interface, a primitive type, or void, then null is returned.If this object represents an array class then the Class object representing the Object class is returned.Syntax : public Class<? super T> getSuperclass() Parameters : NA Returns : the superclass of the class represented by this object // Java program to demonstrate getSuperclass() method // base classclass A{ // methods and fields} // derived classclass B extends A{ } // Driver classpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object associated with Test class Class myClass = Test.class; // returns the Class object for the class // with the specified name Class c1 = Class.forName("A"); Class c2 = Class.forName("B"); Class c3 = Class.forName("java.lang.Object"); // getSuperclass method returns the superclass of the class represented // by this class object System.out.print("Test superclass : "); // getSuperclass method on myClass System.out.println(myClass.getSuperclass()); System.out.print("A superclass : "); // getSuperclass method on c1 System.out.println(c1.getSuperclass()); System.out.print("B superclass : "); // getSuperclass method on c2 System.out.println(c2.getSuperclass()); System.out.print("Object superclass : "); // getSuperclass method on c3 System.out.println(c3.getSuperclass()); }}Output:Test superclass : class java.lang.Object A superclass : class java.lang.Object B superclass : class A Object superclass : null Syntax : public Class<? super T> getSuperclass() Parameters : NA Returns : the superclass of the class represented by this object // Java program to demonstrate getSuperclass() method // base classclass A{ // methods and fields} // derived classclass B extends A{ } // Driver classpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object associated with Test class Class myClass = Test.class; // returns the Class object for the class // with the specified name Class c1 = Class.forName("A"); Class c2 = Class.forName("B"); Class c3 = Class.forName("java.lang.Object"); // getSuperclass method returns the superclass of the class represented // by this class object System.out.print("Test superclass : "); // getSuperclass method on myClass System.out.println(myClass.getSuperclass()); System.out.print("A superclass : "); // getSuperclass method on c1 System.out.println(c1.getSuperclass()); System.out.print("B superclass : "); // getSuperclass method on c2 System.out.println(c2.getSuperclass()); System.out.print("Object superclass : "); // getSuperclass method on c3 System.out.println(c3.getSuperclass()); }} Output: Test superclass : class java.lang.Object A superclass : class java.lang.Object B superclass : class A Object superclass : null Type getGenericSuperclass() : This method returns the Type representing the direct superclass of the entity (class, interface, primitive type or void) represented by this Class.If this Class represents either the Object class, an interface, a primitive type, or void, then null is returned. If this object represents an array class then the Class object representing the Object class is returned.Syntax : public Type getGenericSuperclass() Parameters : NA Returns : the superclass of the class represented by this object Throws: GenericSignatureFormatError - if the generic class signature does not conform to the format specified in JVM TypeNotPresentException - if the generic superclass refers to a non-existent type declaration MalformedParameterizedTypeException - if the generic superclass refers to a parameterized type that cannot be instantiated for any reason // Java program to demonstrate // getGenericSuperclass() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object associated with Test class Class myClass = Test.class; // returns the Class object for the class // with the specified name Class c1 = Class.forName("java.util.ArrayList"); Class c3 = Class.forName("java.lang.Object"); // getGenericSuperclass method returns the generic // superclass of the class represented // by this class object System.out.print("Test superclass : "); // getGenericSuperclass method on myClass System.out.println(myClass.getGenericSuperclass()); System.out.print("ArrayList superclass : "); // getGenericSuperclass method on c1 System.out.println(c1.getGenericSuperclass()); System.out.print("Object superclass : "); // getGenericSuperclass method on c3 System.out.println(c3.getGenericSuperclass()); }}Output:Test superclass : class java.lang.Object Set superclass : java.util.AbstractList<E> Object superclass : null If this Class represents either the Object class, an interface, a primitive type, or void, then null is returned. If this object represents an array class then the Class object representing the Object class is returned. Syntax : public Type getGenericSuperclass() Parameters : NA Returns : the superclass of the class represented by this object Throws: GenericSignatureFormatError - if the generic class signature does not conform to the format specified in JVM TypeNotPresentException - if the generic superclass refers to a non-existent type declaration MalformedParameterizedTypeException - if the generic superclass refers to a parameterized type that cannot be instantiated for any reason // Java program to demonstrate // getGenericSuperclass() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object associated with Test class Class myClass = Test.class; // returns the Class object for the class // with the specified name Class c1 = Class.forName("java.util.ArrayList"); Class c3 = Class.forName("java.lang.Object"); // getGenericSuperclass method returns the generic // superclass of the class represented // by this class object System.out.print("Test superclass : "); // getGenericSuperclass method on myClass System.out.println(myClass.getGenericSuperclass()); System.out.print("ArrayList superclass : "); // getGenericSuperclass method on c1 System.out.println(c1.getGenericSuperclass()); System.out.print("Object superclass : "); // getGenericSuperclass method on c3 System.out.println(c3.getGenericSuperclass()); }} Output: Test superclass : class java.lang.Object Set superclass : java.util.AbstractList<E> Object superclass : null Class<?>[] getInterfaces() : This method returns the interfaces implemented by the class or interface represented by this object.If this object represents a class or interface that implements no interfaces, the method returns an array of length 0.If this object represents a primitive type or void, the method returns an array of length 0.Syntax : public Class<?>[] getInterfaces() Parameters : NA Returns : an array of interfaces implemented by this class. // Java program to demonstrate getInterfaces() method // base interfaceinterface A{ // methods and constant declarations} // derived classclass B implements A{ // methods implementations that were declared in A} // Driver classpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName("B"); Class c2 = Class.forName("java.lang.String"); // getInterface method on c1 // it returns the interfaces implemented by B class Class c1Interfaces[] = c1.getInterfaces(); // getInterface method on c2 // returns the interfaces implemented by String class Class c2Interfaces[] = c2.getInterfaces(); System.out.println("interfaces implemented by B class : "); // iterating through B class interfaces for (Class class1 : c1Interfaces) { System.out.println(class1); } System.out.println("interfaces implemented by String class : "); // iterating through String class interfaces for (Class class1 : c2Interfaces) { System.out.println(class1); } }}Output:interfaces implemented by B class : interface A interfaces implemented by String class : interface java.io.Serializable interface java.lang.Comparable interface java.lang.CharSequence If this object represents a class or interface that implements no interfaces, the method returns an array of length 0.If this object represents a primitive type or void, the method returns an array of length 0. Syntax : public Class<?>[] getInterfaces() Parameters : NA Returns : an array of interfaces implemented by this class. // Java program to demonstrate getInterfaces() method // base interfaceinterface A{ // methods and constant declarations} // derived classclass B implements A{ // methods implementations that were declared in A} // Driver classpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName("B"); Class c2 = Class.forName("java.lang.String"); // getInterface method on c1 // it returns the interfaces implemented by B class Class c1Interfaces[] = c1.getInterfaces(); // getInterface method on c2 // returns the interfaces implemented by String class Class c2Interfaces[] = c2.getInterfaces(); System.out.println("interfaces implemented by B class : "); // iterating through B class interfaces for (Class class1 : c1Interfaces) { System.out.println(class1); } System.out.println("interfaces implemented by String class : "); // iterating through String class interfaces for (Class class1 : c2Interfaces) { System.out.println(class1); } }} Output: interfaces implemented by B class : interface A interfaces implemented by String class : interface java.io.Serializable interface java.lang.Comparable interface java.lang.CharSequence Type[] getGenericInterfaces() : This method returns the Types representing the interfaces directly implemented by the class or interface represented by this object.If this object represents a class or interface that implements no interfaces, the method returns an array of length 0.If this object represents a primitive type or void, the method returns an array of length 0.Syntax : public Type[] getGenericInterfaces() Parameters : NA Returns : an array of interfaces implemented by this class Throws: GenericSignatureFormatError - if the generic class signature does not conform to the format specified in JVM TypeNotPresentException - if the generic superinterfaces refers to a non-existent type declaration MalformedParameterizedTypeException - if the generic superinterfaces refers to a parameterized type that cannot be instantiated for any reason // Java program to demonstrate getGenericInterfaces() method import java.lang.reflect.Type; public class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName("java.util.Set"); // getGenericInterfaces() on c1 // it returns the interfaces implemented by Set interface Type c1GenericInterfaces[] = c1.getGenericInterfaces(); System.out.println("interfaces implemented by Set interface : "); // iterating through Set class interfaces for (Type type : c1GenericInterfaces) { System.out.println(type); } }}Output:interfaces implemented by Set interface : java.util.Collection<E> If this object represents a class or interface that implements no interfaces, the method returns an array of length 0.If this object represents a primitive type or void, the method returns an array of length 0. Syntax : public Type[] getGenericInterfaces() Parameters : NA Returns : an array of interfaces implemented by this class Throws: GenericSignatureFormatError - if the generic class signature does not conform to the format specified in JVM TypeNotPresentException - if the generic superinterfaces refers to a non-existent type declaration MalformedParameterizedTypeException - if the generic superinterfaces refers to a parameterized type that cannot be instantiated for any reason // Java program to demonstrate getGenericInterfaces() method import java.lang.reflect.Type; public class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName("java.util.Set"); // getGenericInterfaces() on c1 // it returns the interfaces implemented by Set interface Type c1GenericInterfaces[] = c1.getGenericInterfaces(); System.out.println("interfaces implemented by Set interface : "); // iterating through Set class interfaces for (Type type : c1GenericInterfaces) { System.out.println(type); } }} Output: interfaces implemented by Set interface : java.util.Collection<E> Package getPackage() : This method returns the package for this class. The classloader subsystem in JVM Architecture used this method to find the package of a class or interface.Syntax : public Package getPackage() Parameters : NA Returns : the package of the class, or null if no package information is available from the archive or codebase. // Java program to demonstrate getPackage() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName("java.lang.String"); Class c2 = Class.forName("java.util.ArrayList"); // getting package of class // getPackage method on c1 System.out.println(c1.getPackage()); // getPackage method on c2 System.out.println(c2.getPackage()); }}Output:package java.lang, Java Platform API Specification, version 1.8 package java.util, Java Platform API Specification, version 1.8 Syntax : public Package getPackage() Parameters : NA Returns : the package of the class, or null if no package information is available from the archive or codebase. // Java program to demonstrate getPackage() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName("java.lang.String"); Class c2 = Class.forName("java.util.ArrayList"); // getting package of class // getPackage method on c1 System.out.println(c1.getPackage()); // getPackage method on c2 System.out.println(c2.getPackage()); }} Output: package java.lang, Java Platform API Specification, version 1.8 package java.util, Java Platform API Specification, version 1.8 Field[] getFields() : This method returns an array of Field objects reflecting all the accessible public fields of the class(and of all its superclasses) or interface(and of all its superclasses) represented by this Class object.Syntax : public Field[] getFields() throws SecurityException Parameters : NA Returns : the array of Field objects representing the public fields and array of length 0 if the class or interface has no accessible public fields or if this Class object represents a primitive type or void. Throws : SecurityException - If a security manager, s, is present. // Java program to demonstrate getFields() method import java.lang.reflect.Field; public class Test{ public static void main(String[] args) throws SecurityException,ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName("java.lang.Integer"); // getFields method on c1 // it array of fields of Integer class Field F[] = c1.getFields(); System.out.println("Below are the fields of Integer class : "); // iterating through all fields of String class for (Field field : F) { System.out.println(field); } }}Output :Below are the fields of Integer class : public static final int java.lang.Integer.MIN_VALUE public static final int java.lang.Integer.MAX_VALUE public static final java.lang.Class java.lang.Integer.TYPE public static final int java.lang.Integer.SIZE public static final int java.lang.Integer.BYTES Syntax : public Field[] getFields() throws SecurityException Parameters : NA Returns : the array of Field objects representing the public fields and array of length 0 if the class or interface has no accessible public fields or if this Class object represents a primitive type or void. Throws : SecurityException - If a security manager, s, is present. // Java program to demonstrate getFields() method import java.lang.reflect.Field; public class Test{ public static void main(String[] args) throws SecurityException,ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName("java.lang.Integer"); // getFields method on c1 // it array of fields of Integer class Field F[] = c1.getFields(); System.out.println("Below are the fields of Integer class : "); // iterating through all fields of String class for (Field field : F) { System.out.println(field); } }} Output : Below are the fields of Integer class : public static final int java.lang.Integer.MIN_VALUE public static final int java.lang.Integer.MAX_VALUE public static final java.lang.Class java.lang.Integer.TYPE public static final int java.lang.Integer.SIZE public static final int java.lang.Integer.BYTES Class<?>[ ] getClasses() : This method returns an array containing Class objects representing all the public classes and interfaces that are members of the class represented by this Class object. The array contains public class and interface members inherited from superclasses and public class and interface members declared by the class.This method returns an array of length 0 if this Class object has no public member classes or interfaces.This method also returns an array of length 0 if this Class object represents a primitive type, an array class, or void.Syntax : Class<?>[ ] getClasses() Parameters : NA Returns : the array of Class objects representing the public members of this class Throws : SecurityException - If a security manager, s, is present. // Java program to demonstrate getClasses() method public class Test{ // base interface public interface A { // methods and constant declarations } // derived class public class B implements A { // methods implementations that were declared in A } public static void main(String[] args) throws ClassNotFoundException { // returns the Class object associated with Test class Class c1 = Test.class; // getClasses method on c1 // it returns the array of Class objects containing the all // public classes and interfaces represented by Test class Class[] c1Classes = c1.getClasses(); System.out.println("public members of Test class : "); // iterating through all public members of Test class for (Class class1 : c1Classes) { System.out.println(class1); } }}Output:public members of Test class : interface Test$A class Test$B This method returns an array of length 0 if this Class object has no public member classes or interfaces.This method also returns an array of length 0 if this Class object represents a primitive type, an array class, or void. Syntax : Class<?>[ ] getClasses() Parameters : NA Returns : the array of Class objects representing the public members of this class Throws : SecurityException - If a security manager, s, is present. // Java program to demonstrate getClasses() method public class Test{ // base interface public interface A { // methods and constant declarations } // derived class public class B implements A { // methods implementations that were declared in A } public static void main(String[] args) throws ClassNotFoundException { // returns the Class object associated with Test class Class c1 = Test.class; // getClasses method on c1 // it returns the array of Class objects containing the all // public classes and interfaces represented by Test class Class[] c1Classes = c1.getClasses(); System.out.println("public members of Test class : "); // iterating through all public members of Test class for (Class class1 : c1Classes) { System.out.println(class1); } }} Output: public members of Test class : interface Test$A class Test$B Method[] getMethods() : This method returns an array of Method objects reflecting all the accessible public methods of the class or interface and those inherited from superclasses and super interfaces represented by this Class object.Syntax : public Method[] getMethods() throws SecurityException Parameters : NA Returns : the array of Method objects representing the public methods and array of length 0 if the class or interface has no accessible public method or if this Class object represents a primitive type or void. Throws : SecurityException - If a security manager, s, is present. // Java program to demonstrate getMethods() method import java.lang.reflect.Method; public class Test{ public static void main(String[] args) throws SecurityException,ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName("java.lang.Object"); // getMethods method on c1 // it returns array of methods of Object class Method M[] = c1.getMethods(); System.out.println("Below are the methods of Object class : "); // iterating through all methods of Object class for (Method method : M) { System.out.println(method); } }}Output:Below are the methods of Object class : public final void java.lang.Object.wait() throws java.lang.InterruptedException public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException public boolean java.lang.Object.equals(java.lang.Object) public java.lang.String java.lang.Object.toString() public native int java.lang.Object.hashCode() public final native java.lang.Class java.lang.Object.getClass() public final native void java.lang.Object.notify() public final native void java.lang.Object.notifyAll() Syntax : public Method[] getMethods() throws SecurityException Parameters : NA Returns : the array of Method objects representing the public methods and array of length 0 if the class or interface has no accessible public method or if this Class object represents a primitive type or void. Throws : SecurityException - If a security manager, s, is present. // Java program to demonstrate getMethods() method import java.lang.reflect.Method; public class Test{ public static void main(String[] args) throws SecurityException,ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName("java.lang.Object"); // getMethods method on c1 // it returns array of methods of Object class Method M[] = c1.getMethods(); System.out.println("Below are the methods of Object class : "); // iterating through all methods of Object class for (Method method : M) { System.out.println(method); } }} Output: Below are the methods of Object class : public final void java.lang.Object.wait() throws java.lang.InterruptedException public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException public boolean java.lang.Object.equals(java.lang.Object) public java.lang.String java.lang.Object.toString() public native int java.lang.Object.hashCode() public final native java.lang.Class java.lang.Object.getClass() public final native void java.lang.Object.notify() public final native void java.lang.Object.notifyAll() Constructor<?>[] getConstructors() : This method returns an array of Constructor objects reflecting all the public constructors of the class represented by this Class object.Syntax : public Constructor<?>[] getConstructors() throws SecurityException Parameters : NA Returns : the array of Constructor objects representing the public constructors of this class and array of length 0 if the class or interface has no accessible public constructor or if this Class object represents a primitive type or void. Throws : SecurityException - If a security manager, s, is present. // Java program to demonstrate getConstructors() method import java.lang.reflect.Constructor; public class Test{ public static void main(String[] args) throws SecurityException,ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName("java.lang.Boolean"); // getConstructor method on c1 // it returns an array of constructors of Boolean class Constructor C[] = c1.getConstructors(); System.out.println("Below are the constructors of Boolean class :"); // iterating through all constructors for (Constructor constructor : C) { System.out.println(constructor); } }}Output:Below are the constructors of Boolean class : public java.lang.Boolean(boolean) public java.lang.Boolean(java.lang.String) Syntax : public Constructor<?>[] getConstructors() throws SecurityException Parameters : NA Returns : the array of Constructor objects representing the public constructors of this class and array of length 0 if the class or interface has no accessible public constructor or if this Class object represents a primitive type or void. Throws : SecurityException - If a security manager, s, is present. // Java program to demonstrate getConstructors() method import java.lang.reflect.Constructor; public class Test{ public static void main(String[] args) throws SecurityException,ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName("java.lang.Boolean"); // getConstructor method on c1 // it returns an array of constructors of Boolean class Constructor C[] = c1.getConstructors(); System.out.println("Below are the constructors of Boolean class :"); // iterating through all constructors for (Constructor constructor : C) { System.out.println(constructor); } }} Output: Below are the constructors of Boolean class : public java.lang.Boolean(boolean) public java.lang.Boolean(java.lang.String) Field getField(String fieldName) : This method returns a Field object that reflects the specified public member field of the class or interface represented by this Class object.Syntax : public Field getField(String fieldName) throws NoSuchFieldException,SecurityException Parameters : fieldName - the field name Returns : the Field object of this class specified by name Throws : NoSuchFieldException - if a field with the specified name is not found. NullPointerException - if fieldName is null SecurityException - If a security manager, s, is present. // Java program to demonstrate getField() method import java.lang.reflect.Field; public class Test{ public static void main(String[] args) throws SecurityException,ClassNotFoundException, NoSuchFieldException { // returns the Class object for the class // with the specified name Class c1 = Class.forName("java.lang.Integer"); // getField method on c1 // it checks a public field in Integer class with specified parameter Field f = c1.getField("MIN_VALUE"); System.out.println("public field in Integer class with MIN_VALUE name :"); System.out.println(f); }}Output:public field in Integer class with MIN_VALUE name : public static final int java.lang.Integer.MIN_VALUE Syntax : public Field getField(String fieldName) throws NoSuchFieldException,SecurityException Parameters : fieldName - the field name Returns : the Field object of this class specified by name Throws : NoSuchFieldException - if a field with the specified name is not found. NullPointerException - if fieldName is null SecurityException - If a security manager, s, is present. // Java program to demonstrate getField() method import java.lang.reflect.Field; public class Test{ public static void main(String[] args) throws SecurityException,ClassNotFoundException, NoSuchFieldException { // returns the Class object for the class // with the specified name Class c1 = Class.forName("java.lang.Integer"); // getField method on c1 // it checks a public field in Integer class with specified parameter Field f = c1.getField("MIN_VALUE"); System.out.println("public field in Integer class with MIN_VALUE name :"); System.out.println(f); }} Output: public field in Integer class with MIN_VALUE name : public static final int java.lang.Integer.MIN_VALUE Method getMethod(String methodName,Class... parameterTypes) : This method returns a Method object that reflects the specified public member method of the class or interface represented by this Class object.Syntax : public Method getMethod(String methodName,Class... parameterTypes) throws NoSuchFieldException,SecurityException Parameters : methodName - the method name parameterTypes - the list of parameters Returns : the method object of this class specified by name Throws : NoSuchMethodException - if a method with the specified name is not found. NullPointerException - if methodName is null SecurityException - If a security manager, s, is present. // Java program to demonstrate getMethod() method import java.lang.reflect.Method; public class Test{ public static void main(String[] args) throws SecurityException,ClassNotFoundException, NoSuchMethodException { // returns the Class object for the class // with the specified name Class c1 = Class.forName("java.lang.Integer"); Class c2 = Class.forName("java.lang.String"); // getMethod method on c1 // it checks for a public Method in Integer class Method m = c1.getMethod("parseInt",c2); System.out.println("method in Integer class specified by parseInt : "); System.out.println(m); }}Output:public method in Integer class specified by parseInt : public static int java.lang.Integer.parseInt(java.lang.String) throws java.lang.NumberFormatException Syntax : public Method getMethod(String methodName,Class... parameterTypes) throws NoSuchFieldException,SecurityException Parameters : methodName - the method name parameterTypes - the list of parameters Returns : the method object of this class specified by name Throws : NoSuchMethodException - if a method with the specified name is not found. NullPointerException - if methodName is null SecurityException - If a security manager, s, is present. // Java program to demonstrate getMethod() method import java.lang.reflect.Method; public class Test{ public static void main(String[] args) throws SecurityException,ClassNotFoundException, NoSuchMethodException { // returns the Class object for the class // with the specified name Class c1 = Class.forName("java.lang.Integer"); Class c2 = Class.forName("java.lang.String"); // getMethod method on c1 // it checks for a public Method in Integer class Method m = c1.getMethod("parseInt",c2); System.out.println("method in Integer class specified by parseInt : "); System.out.println(m); }} Output: public method in Integer class specified by parseInt : public static int java.lang.Integer.parseInt(java.lang.String) throws java.lang.NumberFormatException Constructor<?> getConstructor(Class<?>... parameterTypes) : This method returns a Constructor object that reflects the specified public constructor of the class represented by this Class object.The parameterTypes parameter is an array of Class objects that identify the constructor’s formal parameter types, in declared order.Syntax : public Constructor<?> getConstructor(Class<?>... parameterTypes) throws NoSuchMethodException,SecurityException Parameters : parameterTypes - the list of parameters Returns : the Constructor object of the public constructor that matches the specified parameterTypes Throws : NoSuchMethodException - if a Constructor with the specified parameterTypes is not found. SecurityException - If a security manager, s, is present. // Java program to demonstrate // getConstructor() Constructor import java.lang.reflect.Constructor; public class Test{ public static void main(String[] args) throws SecurityException,ClassNotFoundException, NoSuchMethodException { // returns the Class object for the class // with the specified name Class c1 = Class.forName("java.lang.Integer"); Class c2 = Class.forName("java.lang.String"); // getConstructor method on c1 // it checks a public Constructor in Integer class // with specified parameterTypes Constructor c = c1.getConstructor(c2); System.out.println("Constructor in Integer class & String parameterType:"); System.out.println(c); }}Output:public Constructor in Integer class with String parameterType : public java.lang.Integer(java.lang.String) throws java.lang.NumberFormatException Note : The methods getFields(), getMethods(),getConstructors(), getField(), getMethod(), getConstructor() are widely used in Reflection(Refer this for example) Syntax : public Constructor<?> getConstructor(Class<?>... parameterTypes) throws NoSuchMethodException,SecurityException Parameters : parameterTypes - the list of parameters Returns : the Constructor object of the public constructor that matches the specified parameterTypes Throws : NoSuchMethodException - if a Constructor with the specified parameterTypes is not found. SecurityException - If a security manager, s, is present. // Java program to demonstrate // getConstructor() Constructor import java.lang.reflect.Constructor; public class Test{ public static void main(String[] args) throws SecurityException,ClassNotFoundException, NoSuchMethodException { // returns the Class object for the class // with the specified name Class c1 = Class.forName("java.lang.Integer"); Class c2 = Class.forName("java.lang.String"); // getConstructor method on c1 // it checks a public Constructor in Integer class // with specified parameterTypes Constructor c = c1.getConstructor(c2); System.out.println("Constructor in Integer class & String parameterType:"); System.out.println(c); }} Output: public Constructor in Integer class with String parameterType : public java.lang.Integer(java.lang.String) throws java.lang.NumberFormatException Note : The methods getFields(), getMethods(),getConstructors(), getField(), getMethod(), getConstructor() are widely used in Reflection(Refer this for example) T cast(Object obj) : This method is used to casts an object to the class or interface represented by this Class object.Syntax : public T cast(Object obj) TypeParameters : T - The class type whose object is to be cast Parameters : obj - the object to be cast Returns : the object after casting, or null if obj is null Throws : ClassCastException - if the object is not null and is not assignable to the type T. // Java program to demonstrate cast() methodclass A{ // methods and fields} class B extends A { // methods and fields} // Driver Classpublic class Test{ public static void main(String[] args) { A a = new A(); System.out.println(a.getClass()); B b = new B(); // casting b to a // cast method a = A.class.cast(b); System.out.println(a.getClass()); }}Output:class A class B Syntax : public T cast(Object obj) TypeParameters : T - The class type whose object is to be cast Parameters : obj - the object to be cast Returns : the object after casting, or null if obj is null Throws : ClassCastException - if the object is not null and is not assignable to the type T. // Java program to demonstrate cast() methodclass A{ // methods and fields} class B extends A { // methods and fields} // Driver Classpublic class Test{ public static void main(String[] args) { A a = new A(); System.out.println(a.getClass()); B b = new B(); // casting b to a // cast method a = A.class.cast(b); System.out.println(a.getClass()); }} Output: class A class B <U> Class<? extends U> asSubclass(Class<U> clazz) : This method is used to cast this Class object to represent a subclass of the class represented by the specified class object.It always returns a reference to this class object.Syntax : public <U> Class<? extends U> asSubclass(Class<U> class) TypeParameters : U - The superclass type whose object is to be cast Parameters : clazz - the superclass object to be cast Returns : this Class object, cast to represent a subclass of the specified class object. Throws : ClassCastException - if this Class object does not represent a subclass of the specified class (here "subclass" includes the class itself). // Java program to demonstrate asSubclass() methodclass A{ // methods and fields} class B extends A { // methods and fields} // Driver Classpublic class Test{ public static void main(String[] args) { A a = new A(); // returns the Class object for super class(A) Class superClass = a.getClass(); B b = new B(); // returns the Class object for subclass(B) Class subClass = b.getClass(); // asSubclass method // it represent a subclass of the specified class object Class cast = subClass.asSubclass(superClass); System.out.println(cast); }}Output:class B This article is contributed by Gaurav Miglani. 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 Syntax : public <U> Class<? extends U> asSubclass(Class<U> class) TypeParameters : U - The superclass type whose object is to be cast Parameters : clazz - the superclass object to be cast Returns : this Class object, cast to represent a subclass of the specified class object. Throws : ClassCastException - if this Class object does not represent a subclass of the specified class (here "subclass" includes the class itself). // Java program to demonstrate asSubclass() methodclass A{ // methods and fields} class B extends A { // methods and fields} // Driver Classpublic class Test{ public static void main(String[] args) { A a = new A(); // returns the Class object for super class(A) Class superClass = a.getClass(); B b = new B(); // returns the Class object for subclass(B) Class subClass = b.getClass(); // asSubclass method // it represent a subclass of the specified class object Class cast = subClass.asSubclass(superClass); System.out.println(cast); }} Output: class B This article is contributed by Gaurav Miglani. 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. Java-lang package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Stream In Java Interfaces in Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Singleton Class in Java Multidimensional Arrays in Java
[ { "code": null, "e": 25851, "s": 25823, "text": "\n28 Jun, 2021" }, { "code": null, "e": 26302, "s": 25851, "text": "Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are constructed automatically by the Java Virtual Machine(JVM). It is a final class, so we cannot extend it." }, { "code": null, "e": 26361, "s": 26302, "text": "The Class class methods are widely used in Reflection API." }, { "code": null, "e": 26385, "s": 26361, "text": "Creating a Class object" }, { "code": null, "e": 26431, "s": 26385, "text": "There are three ways to create Class object :" }, { "code": null, "e": 27807, "s": 26431, "text": "Class.forName(“className”) : Since class Class doesn’t contain any constructor, there is static factory method present in class Class, which is Class.forName() , used for creating object of class Class. Below is the syntax :Class c = Class.forName(String className)\nThe above statement creates the Class object for the class passed as a String argument(className). Note that the parameter className must be fully qualified name of the desired class for which Class object is to be created. The methods in any class in java which returns the same class object are also known as factory methods. The class name for which Class object is to be created is determined at run-time.Myclass.class : When we write .class after a class name, it references the Class object that represents the given class. It is mostly used with primitive data types and only when we know the name of class. The class name for which Class object is to be created is determined at compile-time. Below is the syntax :Class c = int.class\nPlease note that this method is used with class name, not with class instances. For exampleA a = new A(); // Any class A\nClass c = A.class; // No error\nClass c = a.class; // Error \nobj.getClass() : This method is present in Object class. It return the run-time class of this(obj) object. Below is the syntax :A a = new A(); // Any class A\nClass c = a.getClass();\n" }, { "code": null, "e": 28483, "s": 27807, "text": "Class.forName(“className”) : Since class Class doesn’t contain any constructor, there is static factory method present in class Class, which is Class.forName() , used for creating object of class Class. Below is the syntax :Class c = Class.forName(String className)\nThe above statement creates the Class object for the class passed as a String argument(className). Note that the parameter className must be fully qualified name of the desired class for which Class object is to be created. The methods in any class in java which returns the same class object are also known as factory methods. The class name for which Class object is to be created is determined at run-time." }, { "code": null, "e": 28526, "s": 28483, "text": "Class c = Class.forName(String className)\n" }, { "code": null, "e": 28936, "s": 28526, "text": "The above statement creates the Class object for the class passed as a String argument(className). Note that the parameter className must be fully qualified name of the desired class for which Class object is to be created. The methods in any class in java which returns the same class object are also known as factory methods. The class name for which Class object is to be created is determined at run-time." }, { "code": null, "e": 29453, "s": 28936, "text": "Myclass.class : When we write .class after a class name, it references the Class object that represents the given class. It is mostly used with primitive data types and only when we know the name of class. The class name for which Class object is to be created is determined at compile-time. Below is the syntax :Class c = int.class\nPlease note that this method is used with class name, not with class instances. For exampleA a = new A(); // Any class A\nClass c = A.class; // No error\nClass c = a.class; // Error \n" }, { "code": null, "e": 29474, "s": 29453, "text": "Class c = int.class\n" }, { "code": null, "e": 29566, "s": 29474, "text": "Please note that this method is used with class name, not with class instances. For example" }, { "code": null, "e": 29659, "s": 29566, "text": "A a = new A(); // Any class A\nClass c = A.class; // No error\nClass c = a.class; // Error \n" }, { "code": null, "e": 29844, "s": 29659, "text": "obj.getClass() : This method is present in Object class. It return the run-time class of this(obj) object. Below is the syntax :A a = new A(); // Any class A\nClass c = a.getClass();\n" }, { "code": null, "e": 29901, "s": 29844, "text": "A a = new A(); // Any class A\nClass c = a.getClass();\n" }, { "code": null, "e": 29910, "s": 29901, "text": "Methods:" }, { "code": null, "e": 74819, "s": 29910, "text": "String toString() : This method converts the Class object to a string. It returns the string representation which is the string “class” or “interface”, followed by a space, and then by the fully qualified name of the class. If the Class object represents a primitive type, then this method returns the name of the primitive type and if it represents void then it returns “void”.Syntax : \npublic String toString()\nParameters : \nNA\nReturns :\na string representation of this class object.\nOverrides :\ntoString in class Object\n// Java program to demonstrate toString() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"java.lang.String\"); Class c2 = int.class; Class c3 = void.class; System.out.print(\"Class represented by c1: \"); // toString method on c1 System.out.println(c1.toString()); System.out.print(\"Class represented by c2: \"); // toString method on c2 System.out.println(c2.toString()); System.out.print(\"Class represented by c3: \"); // toString method on c3 System.out.println(c3.toString()); }}Output:Class represented by c1: class java.lang.String\nClass represented by c2: int\nClass represented by c3: void\nClass<?> forName(String className) : As discussed earlier, this method returns the Class object associated with the class or interface with the given string name. The other variant of this method is discussed next.Syntax : \npublic static Class<?> forName(String className) throws ClassNotFoundException\nParameters : \nclassName - the fully qualified name of the desired class.\nReturns :\nreturn the Class object for the class with the specified name.\nThrows :\nLinkageError : if the linkage fails\nExceptionInInitializerError - if the initialization provoked by this method fails\nClassNotFoundException - if the class cannot be located\n// Java program to demonstrate forName() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // forName method // it returns the Class object for the class // with the specified name Class c = Class.forName(\"java.lang.String\"); System.out.print(\"Class represented by c : \" + c.toString()); }}Output:Class represented by c : class java.lang.String\nClass<?> forName(String className,boolean initialize, ClassLoader loader) : This method also returns the Class object associated with the class or interface with the given string name using the given class loader.The specified class loader is used to load the class or interface. If the parameter loader is null, the class is loaded through the bootstrap class loader in. The class is initialized only if the initialize parameter is true and if it has not been initialized earlier.Syntax : \npublic static Class<?> forName(String className,boolean initialize, ClassLoader loader) \nthrows ClassNotFoundException\nParameters : \nclassName - the fully qualified name of the desired class\ninitialize - whether the class must be initialized\nloader - class loader from which the class must be loaded\nReturns :\nreturn the Class object for the class with the specified name.\nThrows :\nLinkageError : if the linkage fails\nExceptionInInitializerError - if the initialization provoked by this method fails\nClassNotFoundException - if the class cannot be located\n// Java program to demonstrate forName() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName(\"Test\"); ClassLoader loader = myClass.getClassLoader(); // forName method // it returns the Class object for the class // with the specified name using the given class loader Class c = Class.forName(\"java.lang.String\",true,loader); System.out.print(\"Class represented by c : \" + c.toString()); }}Output:Class represented by c : class java.lang.String\nT newInstance() : This method creates a new instance of the class represented by this Class object. The class is created as if by a new expression with an empty argument list. The class is initialized if it has not already been initialized.Syntax : \npublic T newInstance() throws InstantiationException,IllegalAccessException\nTypeParameters : \nT - The class type whose instance is to be returned\nParameters : \nNA\nReturns :\na newly allocated instance of the class represented by this object.\nThrows :\nIllegalAccessException - if the class or its nullary constructor is not accessible.\nInstantiationException - if this Class represents an abstract class, an interface,\nan array class, a primitive type, or void\nor if the class has no nullary constructor; \nor if the instantiation fails for some other reason.\nExceptionInInitializerError - if the initialization provoked by this method fails.\nSecurityException - If a security manager, s, is present\n// Java program to demonstrate newInstance() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException { // returns the Class object for this class Class myClass = Class.forName(\"Test\"); // creating new instance of this class // newInstance method Object obj = myClass.newInstance(); // returns the runtime class of obj System.out.println(\"Class of obj : \" + obj.getClass()); }}Output:Class of obj : class Test\nboolean isInstance(Object obj) : This method determines if the specified Object is assignment-compatible with the object represented by this Class. It is equivalent to instanceof operator in java.Syntax : \npublic boolean isInstance(Object obj)\nParameters : \nobj - the object to check\nReturns :\ntrue if obj is an instance of this class else return false\n// Java program to demonstrate isInstance() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c = Class.forName(\"java.lang.String\"); String s = \"GeeksForGeeks\"; int i = 10; // checking for Class instance // isInstance method boolean b1 = c.isInstance(s); boolean b2 = c.isInstance(i); System.out.println(\"is s instance of String : \" + b1); System.out.println(\"is i instance of String : \" + b1); }}Output:is s instance of String : true\nis i instance of String : false\nboolean isAssignableFrom(Class<?> cls) : This method determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface, of the class or interface represented by the specified Class parameter.Syntax : \npublic boolean isAssignableFrom(Class<?> cls)\nParameters : \ncls - the Class object to be checked\nReturns :\ntrue if objects of the type cls can be assigned to objects of this class\nThrows:\nNullPointerException - if the specified Class parameter is null.\n// Java program to demonstrate isAssignableFrom() methodpublic class Test extends Thread{ public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException { // returns the Class object for this class Class myClass = Class.forName(\"Test\"); // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"java.lang.Thread\"); Class c2 = Class.forName(\"java.lang.String\"); // isAssignableFrom method on c1 // it checks whether Thread class is assignable from Test boolean b1 = c1.isAssignableFrom(myClass); // isAssignableFrom method on c2 // it checks whether String class is assignable from Test boolean b2 = c2.isAssignableFrom(myClass); System.out.println(\"is Thread class Assignable from Test : \" + b1); System.out.println(\"is String class Assignable from Test : \" + b2); }}Output:is Thread class Assignable from Test : true\nis String class Assignable from Test : false\nboolean isInterface() : This method determines if the specified Class object represents an interface type.Syntax : \npublic boolean isInterface()\nParameters : \nNA\nReturns :\nreturn true if and only if this class represents an interface type else return false\n// Java program to demonstrate isInterface() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"java.lang.String\"); Class c2 = Class.forName(\"java.lang.Runnable\"); // checking for interface type // isInterface method on c1 boolean b1 = c1.isInterface(); // is Interface method on c2 boolean b2 = c2.isInterface(); System.out.println(\"is java.lang.String an interface : \" + b1); System.out.println(\"is java.lang.Runnable an interface : \" + b2); }}Output:is java.lang.String an interface : false\nis java.lang.Runnable an interface : true\nboolean isPrimitive() : This method determines if the specified Class object represents a primitive type.Syntax : \npublic boolean isPrimitive() \nParameters : \nNA\nReturns :\nreturn true if and only if this class represents a primitive type else return false\n// Java program to demonstrate isPrimitive methodpublic class Test{ public static void main(String[] args) { // returns the Class object associated with an integer; Class c1 = int.class; // returns the Class object associated with Test class Class c2 = Test.class; // checking for primitive type // isPrimitive method on c1 boolean b1 = c1.isPrimitive(); // isPrimitive method on c2 boolean b2 = c2.isPrimitive(); System.out.println(\"is \"+c1.toString()+\" primitive : \" + b1); System.out.println(\"is \"+c2.toString()+\" primitive : \" + b2); }}Output:is int primitive : true\nis class Test primitive : false\nboolean isArray() : This method determines if the specified Class object represents an array class.Syntax : \npublic boolean isArray() \nParameters : \nNA\nReturns :\nreturn true if and only if this class represents an array type else return false\n// Java program to demonstrate isArray methodpublic class Test{ public static void main(String[] args) { int a[] = new int[2]; // returns the Class object for array class Class c1 = a.getClass(); // returns the Class object for Test class Class c2 = Test.class; // checking for array type // isArray method on c1 boolean b1 = c1.isArray(); // is Array method on c2 boolean b2 = c2.isArray(); System.out.println(\"is \"+c1.toString()+\" an array : \" + b1); System.out.println(\"is \"+c2.toString()+\" an array : \" + b2); }}Output:is class [I an array : true\nis class Test an array : false\nboolean isAnonymousClass() : This method returns true if and only if the this class is an anonymous class. A anonymous class is a like a local classes except that they do not have a name.Syntax : \npublic boolean isAnonymousClass() \nParameters : \nNA\nReturns :\ntrue if and only if this class is an anonymous class.\nfalse,otherwise.\nboolean isLocalClass() : This method returns true if and only if the this class is a local class. A local class is a class that is declared locally within a block of Java code, rather than as a member of a class.Syntax : \npublic boolean isLocalClass()\nParameters : \nNA\nReturns :\ntrue if and only if this class is a local class.\nfalse,otherwise.\nboolean isMemberClass() : This method returns true if and only if the this class is a Member class.A member class is a class that is declared as a non-static member of a containing class.Syntax : \npublic boolean isMemberClass() \nParameters : \nNA\nReturns :\ntrue if and only if this class is a Member class.\nfalse,otherwise.\nBelow is the Java program explaining uses of isAnonymousClass() ,isLocalClass and isMemberClass() methods.// Java program to demonstrate isAnonymousClass() ,isLocalClass // and isMemberClass() method public class Test{ // any Member class of Test class A{} public static void main(String[] args) { // declaring an anonymous class Test t1 = new Test() { // class definition of anonymous class }; // returns the Class object associated with t1 object Class c1 = t1.getClass(); // returns the Class object associated with Test class Class c2 = Test.class; // returns the Class object associated with A class Class c3 = A.class; // checking for Anonymous class // isAnonymousClass method boolean b1 = c1.isAnonymousClass(); System.out.println(\"is \"+c1.toString()+\" an anonymous class : \"+b1); // checking for Local class // isLocalClass method boolean b2 = c2.isLocalClass(); System.out.println(\"is \"+c2.toString()+\" a local class : \" + b2); // checking for Member class // isMemberClass method boolean b3 = c3.isMemberClass(); System.out.println(\"is \"+c3.toString()+\" a member class : \" + b3); }}Output:is class Test$1 an anonymous class : true\nis class Test a local class : false\nis class Test$A a member class : true\nboolean isEnum() : This method returns true if and only if this class was declared as an enum in the source code.Syntax : \npublic boolean isEnum() \nParameters : \nNA\nReturns :\ntrue iff this class was declared as an enum in the source code.\nfalse,otherwise.\n// Java program to demonstrate isEnum() method enum Color{ RED, GREEN, BLUE;} public class Test{ public static void main(String[] args) { // returns the Class object associated with Color(an enum class) Class c1 = Color.class; // returns the Class object associated with Test class Class c2 = Test.class; // checking for Enum class // isEnum method boolean b1 = c1.isEnum(); boolean b2 = c2.isEnum(); System.out.println(\"is \"+c1.toString()+\" an Enum class : \" + b1); System.out.println(\"is \"+c2.toString()+\" an Enum class : \" + b2); }}Output:is class Color an Enum class : true\nis class Test an Enum class : false\nboolean isAnnotation() : This method determines if this Class object represents an annotation type. Note that if this method returns true, isInterface() method will also return true, as all annotation types are also interfaces.Syntax : \npublic boolean isAnnotation() \nParameters : \nNA\nReturns :\nreturn true if and only if this class represents an annotation type else return false\n// Java program to demonstrate isAnnotation() method // declaring an Annotation Type@interface A{ // Annotation element definitions} public class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object associated with A annotation Class c1 = A.class; // returns the Class object associated with Test class Class c2 = Test.class; // checking for annotation type // isAnnotation method boolean b1 = c1.isAnnotation(); boolean b2 = c2.isAnnotation(); System.out.println(\"is \"+c1.toString()+\" an annotation : \" + b1); System.out.println(\"is \"+c2.toString()+\" an annotation : \" + b2); }}Output:is interface A an annotation : true\nis class Test an annotation : false\nString getName() : This method returns the name of the entity (class, interface, array class, primitive type, or void) represented by this Class object, as a String.Syntax : \npublic String getName()\nParameters : \nNA\nReturns :\nreturns the name of the name of the entity \nrepresented by this object.\n// Java program to demonstrate getName() methodpublic class Test{ public static void main(String[] args) { // returns the Class object associated with Test class Class c = Test.class; System.out.print(\"Class Name associated with c : \"); // returns the name of the class // getName method System.out.println(c.getName()); }}Output:Class Name associated with c : Test\nString getSimpleName() : This method returns the name of the underlying class as given in the source code. It returns an empty string if the underlying class is anonymous class.The simple name of an array is the simple name of the component type with “[]” appended. In particular the simple name of an array whose component type is anonymous is “[]”.Syntax : \npublic String getSimpleName()\nParameters : \nNA\nReturns :\nthe simple name of the underlying class\n// Java program to demonstrate getSimpleName() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"java.lang.String\"); System.out.print(\"Class Name associated with c : \"); // returns the name of the class // getName method System.out.println(c1.getName()); System.out.print(\"Simple class Name associated with c : \"); // returns the simple name of the class // getSimpleName method System.out.println(c1.getSimpleName()); }}Output:Class Name associated with c : java.lang.String\nSimple class Name associated with c : String\nClassLoader getClassLoader() : This method returns the class loader for this class. If the class loader is bootstrap classloader then this method returned null, as bootstrap classloader is implemented in native languages like C, C++.If this object represents a primitive type or void,then also null is returned.Syntax : \npublic ClassLoader getClassLoader()\nParameters : \nNA\nReturns :\nthe class loader that loaded the class or interface represented by this object\nrepresented by this object.\nThrows :\nSecurityException - If a security manager and its checkPermission method \ndenies access to the class loader for the class.\n// Java program to demonstrate getClassLoader() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName(\"Test\"); // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"java.lang.String\"); // returns the Class object for primitive int Class c2 = int.class; System.out.print(\"Test class loader : \"); // getting the class loader for Test class // getClassLoader method on myClass System.out.println(myClass.getClassLoader()); System.out.print(\"String class loader : \"); // getting the class loader for String class // we will get null as String class is loaded // by BootStrap class loader // getClassLoader method on c1 System.out.println(c1.getClassLoader()); System.out.print(\"primitive int loader : \"); // getting the class loader for primitive int // getClassLoader method on c2 System.out.println(c2.getClassLoader()); }}Output:Test class loader : sun.misc.Launcher$AppClassLoader@73d16e93\nString class loader : null\nprimitive int loader : null\nTypeVariable<Class<T>>[ ] getTypeParameters() : This method returns an array of TypeVariable objects that represent the type variables declared by the generic declaration represented by this GenericDeclaration object, in declaration orderSyntax : \npublic TypeVariable<Class<T>>[] getTypeParameters()\nSpecified by:\ngetTypeParameters in interface GenericDeclaration\nParameters : \nNA\nReturns :\nan array of TypeVariable objects that represent the type variables declared \nby this generic declaration represented by this object.\nThrows :\nGenericSignatureFormatError - if the generic signature of this generic declaration \ndoes not conform to the format specified in JVM.\n// Java program to demonstrate getTypeParameters() method import java.lang.reflect.TypeVariable; public class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c = Class.forName(\"java.util.Set\"); // getting array of TypeVariable for myClass object // getTypeParameters method TypeVariable[] tv = c.getTypeParameters(); System.out.println(\"TypeVariables in \"+c.getName()+\" class : \"); // iterating through all TypeVariables for (TypeVariable typeVariable : tv) { System.out.println(typeVariable); } }}Output:TypeVariables in java.util.Set class : \nE\nClass<? super T> getSuperclass() : This method returns the Class representing the superclass of the entity (class, interface, primitive type or void) represented by this Class.If this Class represents either the Object class, an interface, a primitive type, or void, then null is returned.If this object represents an array class then the Class object representing the Object class is returned.Syntax : \npublic Class<? super T> getSuperclass() \nParameters : \nNA\nReturns :\nthe superclass of the class represented by this object\n// Java program to demonstrate getSuperclass() method // base classclass A{ // methods and fields} // derived classclass B extends A{ } // Driver classpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object associated with Test class Class myClass = Test.class; // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"A\"); Class c2 = Class.forName(\"B\"); Class c3 = Class.forName(\"java.lang.Object\"); // getSuperclass method returns the superclass of the class represented // by this class object System.out.print(\"Test superclass : \"); // getSuperclass method on myClass System.out.println(myClass.getSuperclass()); System.out.print(\"A superclass : \"); // getSuperclass method on c1 System.out.println(c1.getSuperclass()); System.out.print(\"B superclass : \"); // getSuperclass method on c2 System.out.println(c2.getSuperclass()); System.out.print(\"Object superclass : \"); // getSuperclass method on c3 System.out.println(c3.getSuperclass()); }}Output:Test superclass : class java.lang.Object\nA superclass : class java.lang.Object\nB superclass : class A\nObject superclass : null\nType getGenericSuperclass() : This method returns the Type representing the direct superclass of the entity (class, interface, primitive type or void) represented by this Class.If this Class represents either the Object class, an interface, a primitive type, or void, then null is returned. If this object represents an array class then the Class object representing the Object class is returned.Syntax : \npublic Type getGenericSuperclass()\nParameters : \nNA\nReturns :\nthe superclass of the class represented by this object\nThrows:\nGenericSignatureFormatError - if the generic class signature does not conform to the format \nspecified in JVM\nTypeNotPresentException - if the generic superclass refers to a non-existent \ntype declaration MalformedParameterizedTypeException - if the generic \nsuperclass refers to a parameterized type\nthat cannot be instantiated for any reason\n// Java program to demonstrate // getGenericSuperclass() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object associated with Test class Class myClass = Test.class; // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"java.util.ArrayList\"); Class c3 = Class.forName(\"java.lang.Object\"); // getGenericSuperclass method returns the generic // superclass of the class represented // by this class object System.out.print(\"Test superclass : \"); // getGenericSuperclass method on myClass System.out.println(myClass.getGenericSuperclass()); System.out.print(\"ArrayList superclass : \"); // getGenericSuperclass method on c1 System.out.println(c1.getGenericSuperclass()); System.out.print(\"Object superclass : \"); // getGenericSuperclass method on c3 System.out.println(c3.getGenericSuperclass()); }}Output:Test superclass : class java.lang.Object\nSet superclass : java.util.AbstractList<E>\nObject superclass : null\nClass<?>[] getInterfaces() : This method returns the interfaces implemented by the class or interface represented by this object.If this object represents a class or interface that implements no interfaces, the method returns an array of length 0.If this object represents a primitive type or void, the method returns an array of length 0.Syntax : \npublic Class<?>[] getInterfaces()\nParameters : \nNA\nReturns :\nan array of interfaces implemented by this class.\n// Java program to demonstrate getInterfaces() method // base interfaceinterface A{ // methods and constant declarations} // derived classclass B implements A{ // methods implementations that were declared in A} // Driver classpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"B\"); Class c2 = Class.forName(\"java.lang.String\"); // getInterface method on c1 // it returns the interfaces implemented by B class Class c1Interfaces[] = c1.getInterfaces(); // getInterface method on c2 // returns the interfaces implemented by String class Class c2Interfaces[] = c2.getInterfaces(); System.out.println(\"interfaces implemented by B class : \"); // iterating through B class interfaces for (Class class1 : c1Interfaces) { System.out.println(class1); } System.out.println(\"interfaces implemented by String class : \"); // iterating through String class interfaces for (Class class1 : c2Interfaces) { System.out.println(class1); } }}Output:interfaces implemented by B class : \ninterface A\ninterfaces implemented by String class : \ninterface java.io.Serializable\ninterface java.lang.Comparable\ninterface java.lang.CharSequence\nType[] getGenericInterfaces() : This method returns the Types representing the interfaces directly implemented by the class or interface represented by this object.If this object represents a class or interface that implements no interfaces, the method returns an array of length 0.If this object represents a primitive type or void, the method returns an array of length 0.Syntax : \npublic Type[] getGenericInterfaces()\nParameters : \nNA\nReturns :\nan array of interfaces implemented by this class\nThrows:\nGenericSignatureFormatError - if the generic class signature does not conform to the format \nspecified in JVM\nTypeNotPresentException - if the generic superinterfaces refers to \na non-existent type declaration MalformedParameterizedTypeException - if the\ngeneric superinterfaces refers to a parameterized type\nthat cannot be instantiated for any reason\n// Java program to demonstrate getGenericInterfaces() method import java.lang.reflect.Type; public class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"java.util.Set\"); // getGenericInterfaces() on c1 // it returns the interfaces implemented by Set interface Type c1GenericInterfaces[] = c1.getGenericInterfaces(); System.out.println(\"interfaces implemented by Set interface : \"); // iterating through Set class interfaces for (Type type : c1GenericInterfaces) { System.out.println(type); } }}Output:interfaces implemented by Set interface : \njava.util.Collection<E>\nPackage getPackage() : This method returns the package for this class. The classloader subsystem in JVM Architecture used this method to find the package of a class or interface.Syntax : \npublic Package getPackage()\nParameters : \nNA\nReturns :\nthe package of the class, \nor null if no package information is available\nfrom the archive or codebase. \n// Java program to demonstrate getPackage() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"java.lang.String\"); Class c2 = Class.forName(\"java.util.ArrayList\"); // getting package of class // getPackage method on c1 System.out.println(c1.getPackage()); // getPackage method on c2 System.out.println(c2.getPackage()); }}Output:package java.lang, Java Platform API Specification, version 1.8\npackage java.util, Java Platform API Specification, version 1.8\nField[] getFields() : This method returns an array of Field objects reflecting all the accessible public fields of the class(and of all its superclasses) or interface(and of all its superclasses) represented by this Class object.Syntax : \npublic Field[] getFields() throws SecurityException\nParameters : \nNA\nReturns :\nthe array of Field objects representing the public fields\nand array of length 0 if the class or interface has no accessible public fields\nor if this Class object represents a primitive type or void.\nThrows :\nSecurityException - If a security manager, s, is present.\n// Java program to demonstrate getFields() method import java.lang.reflect.Field; public class Test{ public static void main(String[] args) throws SecurityException,ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"java.lang.Integer\"); // getFields method on c1 // it array of fields of Integer class Field F[] = c1.getFields(); System.out.println(\"Below are the fields of Integer class : \"); // iterating through all fields of String class for (Field field : F) { System.out.println(field); } }}Output :Below are the fields of Integer class :\npublic static final int java.lang.Integer.MIN_VALUE\npublic static final int java.lang.Integer.MAX_VALUE\npublic static final java.lang.Class java.lang.Integer.TYPE\npublic static final int java.lang.Integer.SIZE\npublic static final int java.lang.Integer.BYTES\nClass<?>[ ] getClasses() : This method returns an array containing Class objects representing all the public classes and interfaces that are members of the class represented by this Class object. The array contains public class and interface members inherited from superclasses and public class and interface members declared by the class.This method returns an array of length 0 if this Class object has no public member classes or interfaces.This method also returns an array of length 0 if this Class object represents a primitive type, an array class, or void.Syntax : \nClass<?>[ ] getClasses()\nParameters : \nNA\nReturns :\nthe array of Class objects representing the public members of this class\nThrows :\nSecurityException - If a security manager, s, is present.\n// Java program to demonstrate getClasses() method public class Test{ // base interface public interface A { // methods and constant declarations } // derived class public class B implements A { // methods implementations that were declared in A } public static void main(String[] args) throws ClassNotFoundException { // returns the Class object associated with Test class Class c1 = Test.class; // getClasses method on c1 // it returns the array of Class objects containing the all // public classes and interfaces represented by Test class Class[] c1Classes = c1.getClasses(); System.out.println(\"public members of Test class : \"); // iterating through all public members of Test class for (Class class1 : c1Classes) { System.out.println(class1); } }}Output:public members of Test class : \ninterface Test$A\nclass Test$B\nMethod[] getMethods() : This method returns an array of Method objects reflecting all the accessible public methods of the class or interface and those inherited from superclasses and super interfaces represented by this Class object.Syntax : \npublic Method[] getMethods() throws SecurityException\nParameters : \nNA\nReturns :\nthe array of Method objects representing the public methods\nand array of length 0 if the class or interface has no accessible public method\nor if this Class object represents a primitive type or void.\nThrows :\nSecurityException - If a security manager, s, is present.\n// Java program to demonstrate getMethods() method import java.lang.reflect.Method; public class Test{ public static void main(String[] args) throws SecurityException,ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"java.lang.Object\"); // getMethods method on c1 // it returns array of methods of Object class Method M[] = c1.getMethods(); System.out.println(\"Below are the methods of Object class : \"); // iterating through all methods of Object class for (Method method : M) { System.out.println(method); } }}Output:Below are the methods of Object class : \npublic final void java.lang.Object.wait() throws java.lang.InterruptedException\npublic final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException\npublic final native void java.lang.Object.wait(long) throws java.lang.InterruptedException\npublic boolean java.lang.Object.equals(java.lang.Object)\npublic java.lang.String java.lang.Object.toString()\npublic native int java.lang.Object.hashCode()\npublic final native java.lang.Class java.lang.Object.getClass()\npublic final native void java.lang.Object.notify()\npublic final native void java.lang.Object.notifyAll()\nConstructor<?>[] getConstructors() : This method returns an array of Constructor objects reflecting all the public constructors of the class represented by this Class object.Syntax : \npublic Constructor<?>[] getConstructors() throws SecurityException\nParameters : \nNA\nReturns :\nthe array of Constructor objects representing the public constructors of this class\nand array of length 0 if the class or interface has no accessible public constructor\nor if this Class object represents a primitive type or void.\nThrows :\nSecurityException - If a security manager, s, is present.\n// Java program to demonstrate getConstructors() method import java.lang.reflect.Constructor; public class Test{ public static void main(String[] args) throws SecurityException,ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"java.lang.Boolean\"); // getConstructor method on c1 // it returns an array of constructors of Boolean class Constructor C[] = c1.getConstructors(); System.out.println(\"Below are the constructors of Boolean class :\"); // iterating through all constructors for (Constructor constructor : C) { System.out.println(constructor); } }}Output:Below are the constructors of Boolean class :\npublic java.lang.Boolean(boolean)\npublic java.lang.Boolean(java.lang.String)\nField getField(String fieldName) : This method returns a Field object that reflects the specified public member field of the class or interface represented by this Class object.Syntax : \npublic Field getField(String fieldName) throws NoSuchFieldException,SecurityException\nParameters : \nfieldName - the field name\nReturns :\nthe Field object of this class specified by name\nThrows :\nNoSuchFieldException - if a field with the specified name is not found.\nNullPointerException - if fieldName is null\nSecurityException - If a security manager, s, is present.\n// Java program to demonstrate getField() method import java.lang.reflect.Field; public class Test{ public static void main(String[] args) throws SecurityException,ClassNotFoundException, NoSuchFieldException { // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"java.lang.Integer\"); // getField method on c1 // it checks a public field in Integer class with specified parameter Field f = c1.getField(\"MIN_VALUE\"); System.out.println(\"public field in Integer class with MIN_VALUE name :\"); System.out.println(f); }}Output:public field in Integer class with MIN_VALUE name :\npublic static final int java.lang.Integer.MIN_VALUE\nMethod getMethod(String methodName,Class... parameterTypes) : This method returns a Method object that reflects the specified public member method of the class or interface represented by this Class object.Syntax : \npublic Method getMethod(String methodName,Class... parameterTypes) throws \nNoSuchFieldException,SecurityException\nParameters : \nmethodName - the method name\nparameterTypes - the list of parameters\nReturns :\nthe method object of this class specified by name\nThrows :\nNoSuchMethodException - if a method with the specified name is not found.\nNullPointerException - if methodName is null\nSecurityException - If a security manager, s, is present.\n// Java program to demonstrate getMethod() method import java.lang.reflect.Method; public class Test{ public static void main(String[] args) throws SecurityException,ClassNotFoundException, NoSuchMethodException { // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"java.lang.Integer\"); Class c2 = Class.forName(\"java.lang.String\"); // getMethod method on c1 // it checks for a public Method in Integer class Method m = c1.getMethod(\"parseInt\",c2); System.out.println(\"method in Integer class specified by parseInt : \"); System.out.println(m); }}Output:public method in Integer class specified by parseInt : \npublic static int java.lang.Integer.parseInt(java.lang.String) \nthrows java.lang.NumberFormatException\nConstructor<?> getConstructor(Class<?>... parameterTypes) : This method returns a Constructor object that reflects the specified public constructor of the class represented by this Class object.The parameterTypes parameter is an array of Class objects that identify the constructor’s formal parameter types, in declared order.Syntax : \npublic Constructor<?> getConstructor(Class<?>... parameterTypes) \nthrows NoSuchMethodException,SecurityException\nParameters : \nparameterTypes - the list of parameters\nReturns :\nthe Constructor object of the public constructor that matches the specified parameterTypes\nThrows :\nNoSuchMethodException - if a Constructor with the specified parameterTypes is not found.\nSecurityException - If a security manager, s, is present.\n// Java program to demonstrate // getConstructor() Constructor import java.lang.reflect.Constructor; public class Test{ public static void main(String[] args) throws SecurityException,ClassNotFoundException, NoSuchMethodException { // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"java.lang.Integer\"); Class c2 = Class.forName(\"java.lang.String\"); // getConstructor method on c1 // it checks a public Constructor in Integer class // with specified parameterTypes Constructor c = c1.getConstructor(c2); System.out.println(\"Constructor in Integer class & String parameterType:\"); System.out.println(c); }}Output:public Constructor in Integer class with String parameterType : \npublic java.lang.Integer(java.lang.String) throws java.lang.NumberFormatException\nNote : The methods getFields(), getMethods(),getConstructors(), getField(), getMethod(), getConstructor() are widely used in Reflection(Refer this for example)T cast(Object obj) : This method is used to casts an object to the class or interface represented by this Class object.Syntax : \npublic T cast(Object obj)\nTypeParameters : \nT - The class type whose object is to be cast\nParameters : \nobj - the object to be cast\nReturns :\nthe object after casting, or null if obj is null\nThrows :\nClassCastException - if the object is not null and is not assignable to the type T. \n// Java program to demonstrate cast() methodclass A{ // methods and fields} class B extends A { // methods and fields} // Driver Classpublic class Test{ public static void main(String[] args) { A a = new A(); System.out.println(a.getClass()); B b = new B(); // casting b to a // cast method a = A.class.cast(b); System.out.println(a.getClass()); }}Output:class A\nclass B\n<U> Class<? extends U> asSubclass(Class<U> clazz) : This method is used to cast this Class object to represent a subclass of the class represented by the specified class object.It always returns a reference to this class object.Syntax : \npublic <U> Class<? extends U> asSubclass(Class<U> class)\nTypeParameters : \nU - The superclass type whose object is to be cast\nParameters : \nclazz - the superclass object to be cast\nReturns :\nthis Class object, cast to represent a subclass of the specified class object.\nThrows :\nClassCastException - if this Class object does not represent a \nsubclass of the specified class\n(here \"subclass\" includes the class itself).\n// Java program to demonstrate asSubclass() methodclass A{ // methods and fields} class B extends A { // methods and fields} // Driver Classpublic class Test{ public static void main(String[] args) { A a = new A(); // returns the Class object for super class(A) Class superClass = a.getClass(); B b = new B(); // returns the Class object for subclass(B) Class subClass = b.getClass(); // asSubclass method // it represent a subclass of the specified class object Class cast = subClass.asSubclass(superClass); System.out.println(cast); }}Output:class B\nThis article is contributed by Gaurav Miglani. 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": 76271, "s": 74819, "text": "String toString() : This method converts the Class object to a string. It returns the string representation which is the string “class” or “interface”, followed by a space, and then by the fully qualified name of the class. If the Class object represents a primitive type, then this method returns the name of the primitive type and if it represents void then it returns “void”.Syntax : \npublic String toString()\nParameters : \nNA\nReturns :\na string representation of this class object.\nOverrides :\ntoString in class Object\n// Java program to demonstrate toString() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"java.lang.String\"); Class c2 = int.class; Class c3 = void.class; System.out.print(\"Class represented by c1: \"); // toString method on c1 System.out.println(c1.toString()); System.out.print(\"Class represented by c2: \"); // toString method on c2 System.out.println(c2.toString()); System.out.print(\"Class represented by c3: \"); // toString method on c3 System.out.println(c3.toString()); }}Output:Class represented by c1: class java.lang.String\nClass represented by c2: int\nClass represented by c3: void\n" }, { "code": null, "e": 76417, "s": 76271, "text": "Syntax : \npublic String toString()\nParameters : \nNA\nReturns :\na string representation of this class object.\nOverrides :\ntoString in class Object\n" }, { "code": "// Java program to demonstrate toString() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"java.lang.String\"); Class c2 = int.class; Class c3 = void.class; System.out.print(\"Class represented by c1: \"); // toString method on c1 System.out.println(c1.toString()); System.out.print(\"Class represented by c2: \"); // toString method on c2 System.out.println(c2.toString()); System.out.print(\"Class represented by c3: \"); // toString method on c3 System.out.println(c3.toString()); }}", "e": 77232, "s": 76417, "text": null }, { "code": null, "e": 77240, "s": 77232, "text": "Output:" }, { "code": null, "e": 77348, "s": 77240, "text": "Class represented by c1: class java.lang.String\nClass represented by c2: int\nClass represented by c3: void\n" }, { "code": null, "e": 78452, "s": 77348, "text": "Class<?> forName(String className) : As discussed earlier, this method returns the Class object associated with the class or interface with the given string name. The other variant of this method is discussed next.Syntax : \npublic static Class<?> forName(String className) throws ClassNotFoundException\nParameters : \nclassName - the fully qualified name of the desired class.\nReturns :\nreturn the Class object for the class with the specified name.\nThrows :\nLinkageError : if the linkage fails\nExceptionInInitializerError - if the initialization provoked by this method fails\nClassNotFoundException - if the class cannot be located\n// Java program to demonstrate forName() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // forName method // it returns the Class object for the class // with the specified name Class c = Class.forName(\"java.lang.String\"); System.out.print(\"Class represented by c : \" + c.toString()); }}Output:Class represented by c : class java.lang.String\n" }, { "code": null, "e": 78871, "s": 78452, "text": "Syntax : \npublic static Class<?> forName(String className) throws ClassNotFoundException\nParameters : \nclassName - the fully qualified name of the desired class.\nReturns :\nreturn the Class object for the class with the specified name.\nThrows :\nLinkageError : if the linkage fails\nExceptionInInitializerError - if the initialization provoked by this method fails\nClassNotFoundException - if the class cannot be located\n" }, { "code": "// Java program to demonstrate forName() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // forName method // it returns the Class object for the class // with the specified name Class c = Class.forName(\"java.lang.String\"); System.out.print(\"Class represented by c : \" + c.toString()); }}", "e": 79288, "s": 78871, "text": null }, { "code": null, "e": 79296, "s": 79288, "text": "Output:" }, { "code": null, "e": 79345, "s": 79296, "text": "Class represented by c : class java.lang.String\n" }, { "code": null, "e": 81070, "s": 79345, "text": "Class<?> forName(String className,boolean initialize, ClassLoader loader) : This method also returns the Class object associated with the class or interface with the given string name using the given class loader.The specified class loader is used to load the class or interface. If the parameter loader is null, the class is loaded through the bootstrap class loader in. The class is initialized only if the initialize parameter is true and if it has not been initialized earlier.Syntax : \npublic static Class<?> forName(String className,boolean initialize, ClassLoader loader) \nthrows ClassNotFoundException\nParameters : \nclassName - the fully qualified name of the desired class\ninitialize - whether the class must be initialized\nloader - class loader from which the class must be loaded\nReturns :\nreturn the Class object for the class with the specified name.\nThrows :\nLinkageError : if the linkage fails\nExceptionInInitializerError - if the initialization provoked by this method fails\nClassNotFoundException - if the class cannot be located\n// Java program to demonstrate forName() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName(\"Test\"); ClassLoader loader = myClass.getClassLoader(); // forName method // it returns the Class object for the class // with the specified name using the given class loader Class c = Class.forName(\"java.lang.String\",true,loader); System.out.print(\"Class represented by c : \" + c.toString()); }}Output:Class represented by c : class java.lang.String\n" }, { "code": null, "e": 81339, "s": 81070, "text": "The specified class loader is used to load the class or interface. If the parameter loader is null, the class is loaded through the bootstrap class loader in. The class is initialized only if the initialize parameter is true and if it has not been initialized earlier." }, { "code": null, "e": 81906, "s": 81339, "text": "Syntax : \npublic static Class<?> forName(String className,boolean initialize, ClassLoader loader) \nthrows ClassNotFoundException\nParameters : \nclassName - the fully qualified name of the desired class\ninitialize - whether the class must be initialized\nloader - class loader from which the class must be loaded\nReturns :\nreturn the Class object for the class with the specified name.\nThrows :\nLinkageError : if the linkage fails\nExceptionInInitializerError - if the initialization provoked by this method fails\nClassNotFoundException - if the class cannot be located\n" }, { "code": "// Java program to demonstrate forName() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName(\"Test\"); ClassLoader loader = myClass.getClassLoader(); // forName method // it returns the Class object for the class // with the specified name using the given class loader Class c = Class.forName(\"java.lang.String\",true,loader); System.out.print(\"Class represented by c : \" + c.toString()); }}", "e": 82529, "s": 81906, "text": null }, { "code": null, "e": 82537, "s": 82529, "text": "Output:" }, { "code": null, "e": 82586, "s": 82537, "text": "Class represented by c : class java.lang.String\n" }, { "code": null, "e": 84155, "s": 82586, "text": "T newInstance() : This method creates a new instance of the class represented by this Class object. The class is created as if by a new expression with an empty argument list. The class is initialized if it has not already been initialized.Syntax : \npublic T newInstance() throws InstantiationException,IllegalAccessException\nTypeParameters : \nT - The class type whose instance is to be returned\nParameters : \nNA\nReturns :\na newly allocated instance of the class represented by this object.\nThrows :\nIllegalAccessException - if the class or its nullary constructor is not accessible.\nInstantiationException - if this Class represents an abstract class, an interface,\nan array class, a primitive type, or void\nor if the class has no nullary constructor; \nor if the instantiation fails for some other reason.\nExceptionInInitializerError - if the initialization provoked by this method fails.\nSecurityException - If a security manager, s, is present\n// Java program to demonstrate newInstance() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException { // returns the Class object for this class Class myClass = Class.forName(\"Test\"); // creating new instance of this class // newInstance method Object obj = myClass.newInstance(); // returns the runtime class of obj System.out.println(\"Class of obj : \" + obj.getClass()); }}Output:Class of obj : class Test\n" }, { "code": null, "e": 84863, "s": 84155, "text": "Syntax : \npublic T newInstance() throws InstantiationException,IllegalAccessException\nTypeParameters : \nT - The class type whose instance is to be returned\nParameters : \nNA\nReturns :\na newly allocated instance of the class represented by this object.\nThrows :\nIllegalAccessException - if the class or its nullary constructor is not accessible.\nInstantiationException - if this Class represents an abstract class, an interface,\nan array class, a primitive type, or void\nor if the class has no nullary constructor; \nor if the instantiation fails for some other reason.\nExceptionInInitializerError - if the initialization provoked by this method fails.\nSecurityException - If a security manager, s, is present\n" }, { "code": "// Java program to demonstrate newInstance() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException { // returns the Class object for this class Class myClass = Class.forName(\"Test\"); // creating new instance of this class // newInstance method Object obj = myClass.newInstance(); // returns the runtime class of obj System.out.println(\"Class of obj : \" + obj.getClass()); }}", "e": 85452, "s": 84863, "text": null }, { "code": null, "e": 85460, "s": 85452, "text": "Output:" }, { "code": null, "e": 85487, "s": 85460, "text": "Class of obj : class Test\n" }, { "code": null, "e": 86583, "s": 85487, "text": "boolean isInstance(Object obj) : This method determines if the specified Object is assignment-compatible with the object represented by this Class. It is equivalent to instanceof operator in java.Syntax : \npublic boolean isInstance(Object obj)\nParameters : \nobj - the object to check\nReturns :\ntrue if obj is an instance of this class else return false\n// Java program to demonstrate isInstance() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c = Class.forName(\"java.lang.String\"); String s = \"GeeksForGeeks\"; int i = 10; // checking for Class instance // isInstance method boolean b1 = c.isInstance(s); boolean b2 = c.isInstance(i); System.out.println(\"is s instance of String : \" + b1); System.out.println(\"is i instance of String : \" + b1); }}Output:is s instance of String : true\nis i instance of String : false\n" }, { "code": null, "e": 86741, "s": 86583, "text": "Syntax : \npublic boolean isInstance(Object obj)\nParameters : \nobj - the object to check\nReturns :\ntrue if obj is an instance of this class else return false\n" }, { "code": "// Java program to demonstrate isInstance() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c = Class.forName(\"java.lang.String\"); String s = \"GeeksForGeeks\"; int i = 10; // checking for Class instance // isInstance method boolean b1 = c.isInstance(s); boolean b2 = c.isInstance(i); System.out.println(\"is s instance of String : \" + b1); System.out.println(\"is i instance of String : \" + b1); }}", "e": 87414, "s": 86741, "text": null }, { "code": null, "e": 87422, "s": 87414, "text": "Output:" }, { "code": null, "e": 87486, "s": 87422, "text": "is s instance of String : true\nis i instance of String : false\n" }, { "code": null, "e": 89155, "s": 87486, "text": "boolean isAssignableFrom(Class<?> cls) : This method determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface, of the class or interface represented by the specified Class parameter.Syntax : \npublic boolean isAssignableFrom(Class<?> cls)\nParameters : \ncls - the Class object to be checked\nReturns :\ntrue if objects of the type cls can be assigned to objects of this class\nThrows:\nNullPointerException - if the specified Class parameter is null.\n// Java program to demonstrate isAssignableFrom() methodpublic class Test extends Thread{ public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException { // returns the Class object for this class Class myClass = Class.forName(\"Test\"); // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"java.lang.Thread\"); Class c2 = Class.forName(\"java.lang.String\"); // isAssignableFrom method on c1 // it checks whether Thread class is assignable from Test boolean b1 = c1.isAssignableFrom(myClass); // isAssignableFrom method on c2 // it checks whether String class is assignable from Test boolean b2 = c2.isAssignableFrom(myClass); System.out.println(\"is Thread class Assignable from Test : \" + b1); System.out.println(\"is String class Assignable from Test : \" + b2); }}Output:is Thread class Assignable from Test : true\nis String class Assignable from Test : false\n" }, { "code": null, "e": 89419, "s": 89155, "text": "Syntax : \npublic boolean isAssignableFrom(Class<?> cls)\nParameters : \ncls - the Class object to be checked\nReturns :\ntrue if objects of the type cls can be assigned to objects of this class\nThrows:\nNullPointerException - if the specified Class parameter is null.\n" }, { "code": "// Java program to demonstrate isAssignableFrom() methodpublic class Test extends Thread{ public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException { // returns the Class object for this class Class myClass = Class.forName(\"Test\"); // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"java.lang.Thread\"); Class c2 = Class.forName(\"java.lang.String\"); // isAssignableFrom method on c1 // it checks whether Thread class is assignable from Test boolean b1 = c1.isAssignableFrom(myClass); // isAssignableFrom method on c2 // it checks whether String class is assignable from Test boolean b2 = c2.isAssignableFrom(myClass); System.out.println(\"is Thread class Assignable from Test : \" + b1); System.out.println(\"is String class Assignable from Test : \" + b2); }}", "e": 90474, "s": 89419, "text": null }, { "code": null, "e": 90482, "s": 90474, "text": "Output:" }, { "code": null, "e": 90572, "s": 90482, "text": "is Thread class Assignable from Test : true\nis String class Assignable from Test : false\n" }, { "code": null, "e": 91642, "s": 90572, "text": "boolean isInterface() : This method determines if the specified Class object represents an interface type.Syntax : \npublic boolean isInterface()\nParameters : \nNA\nReturns :\nreturn true if and only if this class represents an interface type else return false\n// Java program to demonstrate isInterface() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"java.lang.String\"); Class c2 = Class.forName(\"java.lang.Runnable\"); // checking for interface type // isInterface method on c1 boolean b1 = c1.isInterface(); // is Interface method on c2 boolean b2 = c2.isInterface(); System.out.println(\"is java.lang.String an interface : \" + b1); System.out.println(\"is java.lang.Runnable an interface : \" + b2); }}Output:is java.lang.String an interface : false\nis java.lang.Runnable an interface : true\n" }, { "code": null, "e": 91794, "s": 91642, "text": "Syntax : \npublic boolean isInterface()\nParameters : \nNA\nReturns :\nreturn true if and only if this class represents an interface type else return false\n" }, { "code": "// Java program to demonstrate isInterface() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"java.lang.String\"); Class c2 = Class.forName(\"java.lang.Runnable\"); // checking for interface type // isInterface method on c1 boolean b1 = c1.isInterface(); // is Interface method on c2 boolean b2 = c2.isInterface(); System.out.println(\"is java.lang.String an interface : \" + b1); System.out.println(\"is java.lang.Runnable an interface : \" + b2); }}", "e": 92517, "s": 91794, "text": null }, { "code": null, "e": 92525, "s": 92517, "text": "Output:" }, { "code": null, "e": 92609, "s": 92525, "text": "is java.lang.String an interface : false\nis java.lang.Runnable an interface : true\n" }, { "code": null, "e": 93588, "s": 92609, "text": "boolean isPrimitive() : This method determines if the specified Class object represents a primitive type.Syntax : \npublic boolean isPrimitive() \nParameters : \nNA\nReturns :\nreturn true if and only if this class represents a primitive type else return false\n// Java program to demonstrate isPrimitive methodpublic class Test{ public static void main(String[] args) { // returns the Class object associated with an integer; Class c1 = int.class; // returns the Class object associated with Test class Class c2 = Test.class; // checking for primitive type // isPrimitive method on c1 boolean b1 = c1.isPrimitive(); // isPrimitive method on c2 boolean b2 = c2.isPrimitive(); System.out.println(\"is \"+c1.toString()+\" primitive : \" + b1); System.out.println(\"is \"+c2.toString()+\" primitive : \" + b2); }}Output:is int primitive : true\nis class Test primitive : false\n" }, { "code": null, "e": 93740, "s": 93588, "text": "Syntax : \npublic boolean isPrimitive() \nParameters : \nNA\nReturns :\nreturn true if and only if this class represents a primitive type else return false\n" }, { "code": "// Java program to demonstrate isPrimitive methodpublic class Test{ public static void main(String[] args) { // returns the Class object associated with an integer; Class c1 = int.class; // returns the Class object associated with Test class Class c2 = Test.class; // checking for primitive type // isPrimitive method on c1 boolean b1 = c1.isPrimitive(); // isPrimitive method on c2 boolean b2 = c2.isPrimitive(); System.out.println(\"is \"+c1.toString()+\" primitive : \" + b1); System.out.println(\"is \"+c2.toString()+\" primitive : \" + b2); }}", "e": 94400, "s": 93740, "text": null }, { "code": null, "e": 94408, "s": 94400, "text": "Output:" }, { "code": null, "e": 94465, "s": 94408, "text": "is int primitive : true\nis class Test primitive : false\n" }, { "code": null, "e": 95438, "s": 94465, "text": "boolean isArray() : This method determines if the specified Class object represents an array class.Syntax : \npublic boolean isArray() \nParameters : \nNA\nReturns :\nreturn true if and only if this class represents an array type else return false\n// Java program to demonstrate isArray methodpublic class Test{ public static void main(String[] args) { int a[] = new int[2]; // returns the Class object for array class Class c1 = a.getClass(); // returns the Class object for Test class Class c2 = Test.class; // checking for array type // isArray method on c1 boolean b1 = c1.isArray(); // is Array method on c2 boolean b2 = c2.isArray(); System.out.println(\"is \"+c1.toString()+\" an array : \" + b1); System.out.println(\"is \"+c2.toString()+\" an array : \" + b2); }}Output:is class [I an array : true\nis class Test an array : false\n" }, { "code": null, "e": 95583, "s": 95438, "text": "Syntax : \npublic boolean isArray() \nParameters : \nNA\nReturns :\nreturn true if and only if this class represents an array type else return false\n" }, { "code": "// Java program to demonstrate isArray methodpublic class Test{ public static void main(String[] args) { int a[] = new int[2]; // returns the Class object for array class Class c1 = a.getClass(); // returns the Class object for Test class Class c2 = Test.class; // checking for array type // isArray method on c1 boolean b1 = c1.isArray(); // is Array method on c2 boolean b2 = c2.isArray(); System.out.println(\"is \"+c1.toString()+\" an array : \" + b1); System.out.println(\"is \"+c2.toString()+\" an array : \" + b2); }}", "e": 96247, "s": 95583, "text": null }, { "code": null, "e": 96255, "s": 96247, "text": "Output:" }, { "code": null, "e": 96315, "s": 96255, "text": "is class [I an array : true\nis class Test an array : false\n" }, { "code": null, "e": 96646, "s": 96315, "text": "boolean isAnonymousClass() : This method returns true if and only if the this class is an anonymous class. A anonymous class is a like a local classes except that they do not have a name.Syntax : \npublic boolean isAnonymousClass() \nParameters : \nNA\nReturns :\ntrue if and only if this class is an anonymous class.\nfalse,otherwise.\n" }, { "code": null, "e": 96790, "s": 96646, "text": "Syntax : \npublic boolean isAnonymousClass() \nParameters : \nNA\nReturns :\ntrue if and only if this class is an anonymous class.\nfalse,otherwise.\n" }, { "code": null, "e": 97136, "s": 96790, "text": "boolean isLocalClass() : This method returns true if and only if the this class is a local class. A local class is a class that is declared locally within a block of Java code, rather than as a member of a class.Syntax : \npublic boolean isLocalClass()\nParameters : \nNA\nReturns :\ntrue if and only if this class is a local class.\nfalse,otherwise.\n" }, { "code": null, "e": 97270, "s": 97136, "text": "Syntax : \npublic boolean isLocalClass()\nParameters : \nNA\nReturns :\ntrue if and only if this class is a local class.\nfalse,otherwise.\n" }, { "code": null, "e": 99072, "s": 97270, "text": "boolean isMemberClass() : This method returns true if and only if the this class is a Member class.A member class is a class that is declared as a non-static member of a containing class.Syntax : \npublic boolean isMemberClass() \nParameters : \nNA\nReturns :\ntrue if and only if this class is a Member class.\nfalse,otherwise.\nBelow is the Java program explaining uses of isAnonymousClass() ,isLocalClass and isMemberClass() methods.// Java program to demonstrate isAnonymousClass() ,isLocalClass // and isMemberClass() method public class Test{ // any Member class of Test class A{} public static void main(String[] args) { // declaring an anonymous class Test t1 = new Test() { // class definition of anonymous class }; // returns the Class object associated with t1 object Class c1 = t1.getClass(); // returns the Class object associated with Test class Class c2 = Test.class; // returns the Class object associated with A class Class c3 = A.class; // checking for Anonymous class // isAnonymousClass method boolean b1 = c1.isAnonymousClass(); System.out.println(\"is \"+c1.toString()+\" an anonymous class : \"+b1); // checking for Local class // isLocalClass method boolean b2 = c2.isLocalClass(); System.out.println(\"is \"+c2.toString()+\" a local class : \" + b2); // checking for Member class // isMemberClass method boolean b3 = c3.isMemberClass(); System.out.println(\"is \"+c3.toString()+\" a member class : \" + b3); }}Output:is class Test$1 an anonymous class : true\nis class Test a local class : false\nis class Test$A a member class : true\n" }, { "code": null, "e": 99209, "s": 99072, "text": "Syntax : \npublic boolean isMemberClass() \nParameters : \nNA\nReturns :\ntrue if and only if this class is a Member class.\nfalse,otherwise.\n" }, { "code": null, "e": 99316, "s": 99209, "text": "Below is the Java program explaining uses of isAnonymousClass() ,isLocalClass and isMemberClass() methods." }, { "code": "// Java program to demonstrate isAnonymousClass() ,isLocalClass // and isMemberClass() method public class Test{ // any Member class of Test class A{} public static void main(String[] args) { // declaring an anonymous class Test t1 = new Test() { // class definition of anonymous class }; // returns the Class object associated with t1 object Class c1 = t1.getClass(); // returns the Class object associated with Test class Class c2 = Test.class; // returns the Class object associated with A class Class c3 = A.class; // checking for Anonymous class // isAnonymousClass method boolean b1 = c1.isAnonymousClass(); System.out.println(\"is \"+c1.toString()+\" an anonymous class : \"+b1); // checking for Local class // isLocalClass method boolean b2 = c2.isLocalClass(); System.out.println(\"is \"+c2.toString()+\" a local class : \" + b2); // checking for Member class // isMemberClass method boolean b3 = c3.isMemberClass(); System.out.println(\"is \"+c3.toString()+\" a member class : \" + b3); }}", "e": 100566, "s": 99316, "text": null }, { "code": null, "e": 100574, "s": 100566, "text": "Output:" }, { "code": null, "e": 100691, "s": 100574, "text": "is class Test$1 an anonymous class : true\nis class Test a local class : false\nis class Test$A a member class : true\n" }, { "code": null, "e": 101681, "s": 100691, "text": "boolean isEnum() : This method returns true if and only if this class was declared as an enum in the source code.Syntax : \npublic boolean isEnum() \nParameters : \nNA\nReturns :\ntrue iff this class was declared as an enum in the source code.\nfalse,otherwise.\n// Java program to demonstrate isEnum() method enum Color{ RED, GREEN, BLUE;} public class Test{ public static void main(String[] args) { // returns the Class object associated with Color(an enum class) Class c1 = Color.class; // returns the Class object associated with Test class Class c2 = Test.class; // checking for Enum class // isEnum method boolean b1 = c1.isEnum(); boolean b2 = c2.isEnum(); System.out.println(\"is \"+c1.toString()+\" an Enum class : \" + b1); System.out.println(\"is \"+c2.toString()+\" an Enum class : \" + b2); }}Output:is class Color an Enum class : true\nis class Test an Enum class : false\n" }, { "code": null, "e": 101825, "s": 101681, "text": "Syntax : \npublic boolean isEnum() \nParameters : \nNA\nReturns :\ntrue iff this class was declared as an enum in the source code.\nfalse,otherwise.\n" }, { "code": "// Java program to demonstrate isEnum() method enum Color{ RED, GREEN, BLUE;} public class Test{ public static void main(String[] args) { // returns the Class object associated with Color(an enum class) Class c1 = Color.class; // returns the Class object associated with Test class Class c2 = Test.class; // checking for Enum class // isEnum method boolean b1 = c1.isEnum(); boolean b2 = c2.isEnum(); System.out.println(\"is \"+c1.toString()+\" an Enum class : \" + b1); System.out.println(\"is \"+c2.toString()+\" an Enum class : \" + b2); }}", "e": 102480, "s": 101825, "text": null }, { "code": null, "e": 102488, "s": 102480, "text": "Output:" }, { "code": null, "e": 102561, "s": 102488, "text": "is class Color an Enum class : true\nis class Test an Enum class : false\n" }, { "code": null, "e": 103797, "s": 102561, "text": "boolean isAnnotation() : This method determines if this Class object represents an annotation type. Note that if this method returns true, isInterface() method will also return true, as all annotation types are also interfaces.Syntax : \npublic boolean isAnnotation() \nParameters : \nNA\nReturns :\nreturn true if and only if this class represents an annotation type else return false\n// Java program to demonstrate isAnnotation() method // declaring an Annotation Type@interface A{ // Annotation element definitions} public class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object associated with A annotation Class c1 = A.class; // returns the Class object associated with Test class Class c2 = Test.class; // checking for annotation type // isAnnotation method boolean b1 = c1.isAnnotation(); boolean b2 = c2.isAnnotation(); System.out.println(\"is \"+c1.toString()+\" an annotation : \" + b1); System.out.println(\"is \"+c2.toString()+\" an annotation : \" + b2); }}Output:is interface A an annotation : true\nis class Test an annotation : false\n" }, { "code": null, "e": 103952, "s": 103797, "text": "Syntax : \npublic boolean isAnnotation() \nParameters : \nNA\nReturns :\nreturn true if and only if this class represents an annotation type else return false\n" }, { "code": "// Java program to demonstrate isAnnotation() method // declaring an Annotation Type@interface A{ // Annotation element definitions} public class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object associated with A annotation Class c1 = A.class; // returns the Class object associated with Test class Class c2 = Test.class; // checking for annotation type // isAnnotation method boolean b1 = c1.isAnnotation(); boolean b2 = c2.isAnnotation(); System.out.println(\"is \"+c1.toString()+\" an annotation : \" + b1); System.out.println(\"is \"+c2.toString()+\" an annotation : \" + b2); }}", "e": 104727, "s": 103952, "text": null }, { "code": null, "e": 104735, "s": 104727, "text": "Output:" }, { "code": null, "e": 104809, "s": 104735, "text": "is interface A an annotation : true\nis class Test an annotation : false\n" }, { "code": null, "e": 105538, "s": 104809, "text": "String getName() : This method returns the name of the entity (class, interface, array class, primitive type, or void) represented by this Class object, as a String.Syntax : \npublic String getName()\nParameters : \nNA\nReturns :\nreturns the name of the name of the entity \nrepresented by this object.\n// Java program to demonstrate getName() methodpublic class Test{ public static void main(String[] args) { // returns the Class object associated with Test class Class c = Test.class; System.out.print(\"Class Name associated with c : \"); // returns the name of the class // getName method System.out.println(c.getName()); }}Output:Class Name associated with c : Test\n" }, { "code": null, "e": 105672, "s": 105538, "text": "Syntax : \npublic String getName()\nParameters : \nNA\nReturns :\nreturns the name of the name of the entity \nrepresented by this object.\n" }, { "code": "// Java program to demonstrate getName() methodpublic class Test{ public static void main(String[] args) { // returns the Class object associated with Test class Class c = Test.class; System.out.print(\"Class Name associated with c : \"); // returns the name of the class // getName method System.out.println(c.getName()); }}", "e": 106060, "s": 105672, "text": null }, { "code": null, "e": 106068, "s": 106060, "text": "Output:" }, { "code": null, "e": 106105, "s": 106068, "text": "Class Name associated with c : Test\n" }, { "code": null, "e": 107350, "s": 106105, "text": "String getSimpleName() : This method returns the name of the underlying class as given in the source code. It returns an empty string if the underlying class is anonymous class.The simple name of an array is the simple name of the component type with “[]” appended. In particular the simple name of an array whose component type is anonymous is “[]”.Syntax : \npublic String getSimpleName()\nParameters : \nNA\nReturns :\nthe simple name of the underlying class\n// Java program to demonstrate getSimpleName() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"java.lang.String\"); System.out.print(\"Class Name associated with c : \"); // returns the name of the class // getName method System.out.println(c1.getName()); System.out.print(\"Simple class Name associated with c : \"); // returns the simple name of the class // getSimpleName method System.out.println(c1.getSimpleName()); }}Output:Class Name associated with c : java.lang.String\nSimple class Name associated with c : String\n" }, { "code": null, "e": 107524, "s": 107350, "text": "The simple name of an array is the simple name of the component type with “[]” appended. In particular the simple name of an array whose component type is anonymous is “[]”." }, { "code": null, "e": 107632, "s": 107524, "text": "Syntax : \npublic String getSimpleName()\nParameters : \nNA\nReturns :\nthe simple name of the underlying class\n" }, { "code": "// Java program to demonstrate getSimpleName() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"java.lang.String\"); System.out.print(\"Class Name associated with c : \"); // returns the name of the class // getName method System.out.println(c1.getName()); System.out.print(\"Simple class Name associated with c : \"); // returns the simple name of the class // getSimpleName method System.out.println(c1.getSimpleName()); }}", "e": 108320, "s": 107632, "text": null }, { "code": null, "e": 108328, "s": 108320, "text": "Output:" }, { "code": null, "e": 108422, "s": 108328, "text": "Class Name associated with c : java.lang.String\nSimple class Name associated with c : String\n" }, { "code": null, "e": 110424, "s": 108422, "text": "ClassLoader getClassLoader() : This method returns the class loader for this class. If the class loader is bootstrap classloader then this method returned null, as bootstrap classloader is implemented in native languages like C, C++.If this object represents a primitive type or void,then also null is returned.Syntax : \npublic ClassLoader getClassLoader()\nParameters : \nNA\nReturns :\nthe class loader that loaded the class or interface represented by this object\nrepresented by this object.\nThrows :\nSecurityException - If a security manager and its checkPermission method \ndenies access to the class loader for the class.\n// Java program to demonstrate getClassLoader() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName(\"Test\"); // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"java.lang.String\"); // returns the Class object for primitive int Class c2 = int.class; System.out.print(\"Test class loader : \"); // getting the class loader for Test class // getClassLoader method on myClass System.out.println(myClass.getClassLoader()); System.out.print(\"String class loader : \"); // getting the class loader for String class // we will get null as String class is loaded // by BootStrap class loader // getClassLoader method on c1 System.out.println(c1.getClassLoader()); System.out.print(\"primitive int loader : \"); // getting the class loader for primitive int // getClassLoader method on c2 System.out.println(c2.getClassLoader()); }}Output:Test class loader : sun.misc.Launcher$AppClassLoader@73d16e93\nString class loader : null\nprimitive int loader : null\n" }, { "code": null, "e": 110737, "s": 110424, "text": "Syntax : \npublic ClassLoader getClassLoader()\nParameters : \nNA\nReturns :\nthe class loader that loaded the class or interface represented by this object\nrepresented by this object.\nThrows :\nSecurityException - If a security manager and its checkPermission method \ndenies access to the class loader for the class.\n" }, { "code": "// Java program to demonstrate getClassLoader() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName(\"Test\"); // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"java.lang.String\"); // returns the Class object for primitive int Class c2 = int.class; System.out.print(\"Test class loader : \"); // getting the class loader for Test class // getClassLoader method on myClass System.out.println(myClass.getClassLoader()); System.out.print(\"String class loader : \"); // getting the class loader for String class // we will get null as String class is loaded // by BootStrap class loader // getClassLoader method on c1 System.out.println(c1.getClassLoader()); System.out.print(\"primitive int loader : \"); // getting the class loader for primitive int // getClassLoader method on c2 System.out.println(c2.getClassLoader()); }}", "e": 111992, "s": 110737, "text": null }, { "code": null, "e": 112000, "s": 111992, "text": "Output:" }, { "code": null, "e": 112118, "s": 112000, "text": "Test class loader : sun.misc.Launcher$AppClassLoader@73d16e93\nString class loader : null\nprimitive int loader : null\n" }, { "code": null, "e": 113601, "s": 112118, "text": "TypeVariable<Class<T>>[ ] getTypeParameters() : This method returns an array of TypeVariable objects that represent the type variables declared by the generic declaration represented by this GenericDeclaration object, in declaration orderSyntax : \npublic TypeVariable<Class<T>>[] getTypeParameters()\nSpecified by:\ngetTypeParameters in interface GenericDeclaration\nParameters : \nNA\nReturns :\nan array of TypeVariable objects that represent the type variables declared \nby this generic declaration represented by this object.\nThrows :\nGenericSignatureFormatError - if the generic signature of this generic declaration \ndoes not conform to the format specified in JVM.\n// Java program to demonstrate getTypeParameters() method import java.lang.reflect.TypeVariable; public class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c = Class.forName(\"java.util.Set\"); // getting array of TypeVariable for myClass object // getTypeParameters method TypeVariable[] tv = c.getTypeParameters(); System.out.println(\"TypeVariables in \"+c.getName()+\" class : \"); // iterating through all TypeVariables for (TypeVariable typeVariable : tv) { System.out.println(typeVariable); } }}Output:TypeVariables in java.util.Set class : \nE\n" }, { "code": null, "e": 114030, "s": 113601, "text": "Syntax : \npublic TypeVariable<Class<T>>[] getTypeParameters()\nSpecified by:\ngetTypeParameters in interface GenericDeclaration\nParameters : \nNA\nReturns :\nan array of TypeVariable objects that represent the type variables declared \nby this generic declaration represented by this object.\nThrows :\nGenericSignatureFormatError - if the generic signature of this generic declaration \ndoes not conform to the format specified in JVM.\n" }, { "code": "// Java program to demonstrate getTypeParameters() method import java.lang.reflect.TypeVariable; public class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c = Class.forName(\"java.util.Set\"); // getting array of TypeVariable for myClass object // getTypeParameters method TypeVariable[] tv = c.getTypeParameters(); System.out.println(\"TypeVariables in \"+c.getName()+\" class : \"); // iterating through all TypeVariables for (TypeVariable typeVariable : tv) { System.out.println(typeVariable); } }}", "e": 114798, "s": 114030, "text": null }, { "code": null, "e": 114806, "s": 114798, "text": "Output:" }, { "code": null, "e": 114849, "s": 114806, "text": "TypeVariables in java.util.Set class : \nE\n" }, { "code": null, "e": 116846, "s": 114849, "text": "Class<? super T> getSuperclass() : This method returns the Class representing the superclass of the entity (class, interface, primitive type or void) represented by this Class.If this Class represents either the Object class, an interface, a primitive type, or void, then null is returned.If this object represents an array class then the Class object representing the Object class is returned.Syntax : \npublic Class<? super T> getSuperclass() \nParameters : \nNA\nReturns :\nthe superclass of the class represented by this object\n// Java program to demonstrate getSuperclass() method // base classclass A{ // methods and fields} // derived classclass B extends A{ } // Driver classpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object associated with Test class Class myClass = Test.class; // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"A\"); Class c2 = Class.forName(\"B\"); Class c3 = Class.forName(\"java.lang.Object\"); // getSuperclass method returns the superclass of the class represented // by this class object System.out.print(\"Test superclass : \"); // getSuperclass method on myClass System.out.println(myClass.getSuperclass()); System.out.print(\"A superclass : \"); // getSuperclass method on c1 System.out.println(c1.getSuperclass()); System.out.print(\"B superclass : \"); // getSuperclass method on c2 System.out.println(c2.getSuperclass()); System.out.print(\"Object superclass : \"); // getSuperclass method on c3 System.out.println(c3.getSuperclass()); }}Output:Test superclass : class java.lang.Object\nA superclass : class java.lang.Object\nB superclass : class A\nObject superclass : null\n" }, { "code": null, "e": 116980, "s": 116846, "text": "Syntax : \npublic Class<? super T> getSuperclass() \nParameters : \nNA\nReturns :\nthe superclass of the class represented by this object\n" }, { "code": "// Java program to demonstrate getSuperclass() method // base classclass A{ // methods and fields} // derived classclass B extends A{ } // Driver classpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object associated with Test class Class myClass = Test.class; // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"A\"); Class c2 = Class.forName(\"B\"); Class c3 = Class.forName(\"java.lang.Object\"); // getSuperclass method returns the superclass of the class represented // by this class object System.out.print(\"Test superclass : \"); // getSuperclass method on myClass System.out.println(myClass.getSuperclass()); System.out.print(\"A superclass : \"); // getSuperclass method on c1 System.out.println(c1.getSuperclass()); System.out.print(\"B superclass : \"); // getSuperclass method on c2 System.out.println(c2.getSuperclass()); System.out.print(\"Object superclass : \"); // getSuperclass method on c3 System.out.println(c3.getSuperclass()); }}", "e": 118316, "s": 116980, "text": null }, { "code": null, "e": 118324, "s": 118316, "text": "Output:" }, { "code": null, "e": 118452, "s": 118324, "text": "Test superclass : class java.lang.Object\nA superclass : class java.lang.Object\nB superclass : class A\nObject superclass : null\n" }, { "code": null, "e": 120588, "s": 118452, "text": "Type getGenericSuperclass() : This method returns the Type representing the direct superclass of the entity (class, interface, primitive type or void) represented by this Class.If this Class represents either the Object class, an interface, a primitive type, or void, then null is returned. If this object represents an array class then the Class object representing the Object class is returned.Syntax : \npublic Type getGenericSuperclass()\nParameters : \nNA\nReturns :\nthe superclass of the class represented by this object\nThrows:\nGenericSignatureFormatError - if the generic class signature does not conform to the format \nspecified in JVM\nTypeNotPresentException - if the generic superclass refers to a non-existent \ntype declaration MalformedParameterizedTypeException - if the generic \nsuperclass refers to a parameterized type\nthat cannot be instantiated for any reason\n// Java program to demonstrate // getGenericSuperclass() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object associated with Test class Class myClass = Test.class; // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"java.util.ArrayList\"); Class c3 = Class.forName(\"java.lang.Object\"); // getGenericSuperclass method returns the generic // superclass of the class represented // by this class object System.out.print(\"Test superclass : \"); // getGenericSuperclass method on myClass System.out.println(myClass.getGenericSuperclass()); System.out.print(\"ArrayList superclass : \"); // getGenericSuperclass method on c1 System.out.println(c1.getGenericSuperclass()); System.out.print(\"Object superclass : \"); // getGenericSuperclass method on c3 System.out.println(c3.getGenericSuperclass()); }}Output:Test superclass : class java.lang.Object\nSet superclass : java.util.AbstractList<E>\nObject superclass : null\n" }, { "code": null, "e": 120808, "s": 120588, "text": "If this Class represents either the Object class, an interface, a primitive type, or void, then null is returned. If this object represents an array class then the Class object representing the Object class is returned." }, { "code": null, "e": 121288, "s": 120808, "text": "Syntax : \npublic Type getGenericSuperclass()\nParameters : \nNA\nReturns :\nthe superclass of the class represented by this object\nThrows:\nGenericSignatureFormatError - if the generic class signature does not conform to the format \nspecified in JVM\nTypeNotPresentException - if the generic superclass refers to a non-existent \ntype declaration MalformedParameterizedTypeException - if the generic \nsuperclass refers to a parameterized type\nthat cannot be instantiated for any reason\n" }, { "code": "// Java program to demonstrate // getGenericSuperclass() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object associated with Test class Class myClass = Test.class; // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"java.util.ArrayList\"); Class c3 = Class.forName(\"java.lang.Object\"); // getGenericSuperclass method returns the generic // superclass of the class represented // by this class object System.out.print(\"Test superclass : \"); // getGenericSuperclass method on myClass System.out.println(myClass.getGenericSuperclass()); System.out.print(\"ArrayList superclass : \"); // getGenericSuperclass method on c1 System.out.println(c1.getGenericSuperclass()); System.out.print(\"Object superclass : \"); // getGenericSuperclass method on c3 System.out.println(c3.getGenericSuperclass()); }}", "e": 122433, "s": 121288, "text": null }, { "code": null, "e": 122441, "s": 122433, "text": "Output:" }, { "code": null, "e": 122551, "s": 122441, "text": "Test superclass : class java.lang.Object\nSet superclass : java.util.AbstractList<E>\nObject superclass : null\n" }, { "code": null, "e": 124545, "s": 122551, "text": "Class<?>[] getInterfaces() : This method returns the interfaces implemented by the class or interface represented by this object.If this object represents a class or interface that implements no interfaces, the method returns an array of length 0.If this object represents a primitive type or void, the method returns an array of length 0.Syntax : \npublic Class<?>[] getInterfaces()\nParameters : \nNA\nReturns :\nan array of interfaces implemented by this class.\n// Java program to demonstrate getInterfaces() method // base interfaceinterface A{ // methods and constant declarations} // derived classclass B implements A{ // methods implementations that were declared in A} // Driver classpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"B\"); Class c2 = Class.forName(\"java.lang.String\"); // getInterface method on c1 // it returns the interfaces implemented by B class Class c1Interfaces[] = c1.getInterfaces(); // getInterface method on c2 // returns the interfaces implemented by String class Class c2Interfaces[] = c2.getInterfaces(); System.out.println(\"interfaces implemented by B class : \"); // iterating through B class interfaces for (Class class1 : c1Interfaces) { System.out.println(class1); } System.out.println(\"interfaces implemented by String class : \"); // iterating through String class interfaces for (Class class1 : c2Interfaces) { System.out.println(class1); } }}Output:interfaces implemented by B class : \ninterface A\ninterfaces implemented by String class : \ninterface java.io.Serializable\ninterface java.lang.Comparable\ninterface java.lang.CharSequence\n" }, { "code": null, "e": 124756, "s": 124545, "text": "If this object represents a class or interface that implements no interfaces, the method returns an array of length 0.If this object represents a primitive type or void, the method returns an array of length 0." }, { "code": null, "e": 124878, "s": 124756, "text": "Syntax : \npublic Class<?>[] getInterfaces()\nParameters : \nNA\nReturns :\nan array of interfaces implemented by this class.\n" }, { "code": "// Java program to demonstrate getInterfaces() method // base interfaceinterface A{ // methods and constant declarations} // derived classclass B implements A{ // methods implementations that were declared in A} // Driver classpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"B\"); Class c2 = Class.forName(\"java.lang.String\"); // getInterface method on c1 // it returns the interfaces implemented by B class Class c1Interfaces[] = c1.getInterfaces(); // getInterface method on c2 // returns the interfaces implemented by String class Class c2Interfaces[] = c2.getInterfaces(); System.out.println(\"interfaces implemented by B class : \"); // iterating through B class interfaces for (Class class1 : c1Interfaces) { System.out.println(class1); } System.out.println(\"interfaces implemented by String class : \"); // iterating through String class interfaces for (Class class1 : c2Interfaces) { System.out.println(class1); } }}", "e": 126219, "s": 124878, "text": null }, { "code": null, "e": 126227, "s": 126219, "text": "Output:" }, { "code": null, "e": 126414, "s": 126227, "text": "interfaces implemented by B class : \ninterface A\ninterfaces implemented by String class : \ninterface java.io.Serializable\ninterface java.lang.Comparable\ninterface java.lang.CharSequence\n" }, { "code": null, "e": 128115, "s": 126414, "text": "Type[] getGenericInterfaces() : This method returns the Types representing the interfaces directly implemented by the class or interface represented by this object.If this object represents a class or interface that implements no interfaces, the method returns an array of length 0.If this object represents a primitive type or void, the method returns an array of length 0.Syntax : \npublic Type[] getGenericInterfaces()\nParameters : \nNA\nReturns :\nan array of interfaces implemented by this class\nThrows:\nGenericSignatureFormatError - if the generic class signature does not conform to the format \nspecified in JVM\nTypeNotPresentException - if the generic superinterfaces refers to \na non-existent type declaration MalformedParameterizedTypeException - if the\ngeneric superinterfaces refers to a parameterized type\nthat cannot be instantiated for any reason\n// Java program to demonstrate getGenericInterfaces() method import java.lang.reflect.Type; public class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"java.util.Set\"); // getGenericInterfaces() on c1 // it returns the interfaces implemented by Set interface Type c1GenericInterfaces[] = c1.getGenericInterfaces(); System.out.println(\"interfaces implemented by Set interface : \"); // iterating through Set class interfaces for (Type type : c1GenericInterfaces) { System.out.println(type); } }}Output:interfaces implemented by Set interface : \njava.util.Collection<E>\n" }, { "code": null, "e": 128326, "s": 128115, "text": "If this object represents a class or interface that implements no interfaces, the method returns an array of length 0.If this object represents a primitive type or void, the method returns an array of length 0." }, { "code": null, "e": 128811, "s": 128326, "text": "Syntax : \npublic Type[] getGenericInterfaces()\nParameters : \nNA\nReturns :\nan array of interfaces implemented by this class\nThrows:\nGenericSignatureFormatError - if the generic class signature does not conform to the format \nspecified in JVM\nTypeNotPresentException - if the generic superinterfaces refers to \na non-existent type declaration MalformedParameterizedTypeException - if the\ngeneric superinterfaces refers to a parameterized type\nthat cannot be instantiated for any reason\n" }, { "code": "// Java program to demonstrate getGenericInterfaces() method import java.lang.reflect.Type; public class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"java.util.Set\"); // getGenericInterfaces() on c1 // it returns the interfaces implemented by Set interface Type c1GenericInterfaces[] = c1.getGenericInterfaces(); System.out.println(\"interfaces implemented by Set interface : \"); // iterating through Set class interfaces for (Type type : c1GenericInterfaces) { System.out.println(type); } }}", "e": 129580, "s": 128811, "text": null }, { "code": null, "e": 129588, "s": 129580, "text": "Output:" }, { "code": null, "e": 129656, "s": 129588, "text": "interfaces implemented by Set interface : \njava.util.Collection<E>\n" }, { "code": null, "e": 130692, "s": 129656, "text": "Package getPackage() : This method returns the package for this class. The classloader subsystem in JVM Architecture used this method to find the package of a class or interface.Syntax : \npublic Package getPackage()\nParameters : \nNA\nReturns :\nthe package of the class, \nor null if no package information is available\nfrom the archive or codebase. \n// Java program to demonstrate getPackage() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"java.lang.String\"); Class c2 = Class.forName(\"java.util.ArrayList\"); // getting package of class // getPackage method on c1 System.out.println(c1.getPackage()); // getPackage method on c2 System.out.println(c2.getPackage()); }}Output:package java.lang, Java Platform API Specification, version 1.8\npackage java.util, Java Platform API Specification, version 1.8\n" }, { "code": null, "e": 130863, "s": 130692, "text": "Syntax : \npublic Package getPackage()\nParameters : \nNA\nReturns :\nthe package of the class, \nor null if no package information is available\nfrom the archive or codebase. \n" }, { "code": "// Java program to demonstrate getPackage() methodpublic class Test{ public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"java.lang.String\"); Class c2 = Class.forName(\"java.util.ArrayList\"); // getting package of class // getPackage method on c1 System.out.println(c1.getPackage()); // getPackage method on c2 System.out.println(c2.getPackage()); }}", "e": 131416, "s": 130863, "text": null }, { "code": null, "e": 131424, "s": 131416, "text": "Output:" }, { "code": null, "e": 131553, "s": 131424, "text": "package java.lang, Java Platform API Specification, version 1.8\npackage java.util, Java Platform API Specification, version 1.8\n" }, { "code": null, "e": 133162, "s": 131553, "text": "Field[] getFields() : This method returns an array of Field objects reflecting all the accessible public fields of the class(and of all its superclasses) or interface(and of all its superclasses) represented by this Class object.Syntax : \npublic Field[] getFields() throws SecurityException\nParameters : \nNA\nReturns :\nthe array of Field objects representing the public fields\nand array of length 0 if the class or interface has no accessible public fields\nor if this Class object represents a primitive type or void.\nThrows :\nSecurityException - If a security manager, s, is present.\n// Java program to demonstrate getFields() method import java.lang.reflect.Field; public class Test{ public static void main(String[] args) throws SecurityException,ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"java.lang.Integer\"); // getFields method on c1 // it array of fields of Integer class Field F[] = c1.getFields(); System.out.println(\"Below are the fields of Integer class : \"); // iterating through all fields of String class for (Field field : F) { System.out.println(field); } }}Output :Below are the fields of Integer class :\npublic static final int java.lang.Integer.MIN_VALUE\npublic static final int java.lang.Integer.MAX_VALUE\npublic static final java.lang.Class java.lang.Integer.TYPE\npublic static final int java.lang.Integer.SIZE\npublic static final int java.lang.Integer.BYTES\n" }, { "code": null, "e": 133520, "s": 133162, "text": "Syntax : \npublic Field[] getFields() throws SecurityException\nParameters : \nNA\nReturns :\nthe array of Field objects representing the public fields\nand array of length 0 if the class or interface has no accessible public fields\nor if this Class object represents a primitive type or void.\nThrows :\nSecurityException - If a security manager, s, is present.\n" }, { "code": "// Java program to demonstrate getFields() method import java.lang.reflect.Field; public class Test{ public static void main(String[] args) throws SecurityException,ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"java.lang.Integer\"); // getFields method on c1 // it array of fields of Integer class Field F[] = c1.getFields(); System.out.println(\"Below are the fields of Integer class : \"); // iterating through all fields of String class for (Field field : F) { System.out.println(field); } }}", "e": 134237, "s": 133520, "text": null }, { "code": null, "e": 134246, "s": 134237, "text": "Output :" }, { "code": null, "e": 134545, "s": 134246, "text": "Below are the fields of Integer class :\npublic static final int java.lang.Integer.MIN_VALUE\npublic static final int java.lang.Integer.MAX_VALUE\npublic static final java.lang.Class java.lang.Integer.TYPE\npublic static final int java.lang.Integer.SIZE\npublic static final int java.lang.Integer.BYTES\n" }, { "code": null, "e": 136340, "s": 134545, "text": "Class<?>[ ] getClasses() : This method returns an array containing Class objects representing all the public classes and interfaces that are members of the class represented by this Class object. The array contains public class and interface members inherited from superclasses and public class and interface members declared by the class.This method returns an array of length 0 if this Class object has no public member classes or interfaces.This method also returns an array of length 0 if this Class object represents a primitive type, an array class, or void.Syntax : \nClass<?>[ ] getClasses()\nParameters : \nNA\nReturns :\nthe array of Class objects representing the public members of this class\nThrows :\nSecurityException - If a security manager, s, is present.\n// Java program to demonstrate getClasses() method public class Test{ // base interface public interface A { // methods and constant declarations } // derived class public class B implements A { // methods implementations that were declared in A } public static void main(String[] args) throws ClassNotFoundException { // returns the Class object associated with Test class Class c1 = Test.class; // getClasses method on c1 // it returns the array of Class objects containing the all // public classes and interfaces represented by Test class Class[] c1Classes = c1.getClasses(); System.out.println(\"public members of Test class : \"); // iterating through all public members of Test class for (Class class1 : c1Classes) { System.out.println(class1); } }}Output:public members of Test class : \ninterface Test$A\nclass Test$B\n" }, { "code": null, "e": 136566, "s": 136340, "text": "This method returns an array of length 0 if this Class object has no public member classes or interfaces.This method also returns an array of length 0 if this Class object represents a primitive type, an array class, or void." }, { "code": null, "e": 136769, "s": 136566, "text": "Syntax : \nClass<?>[ ] getClasses()\nParameters : \nNA\nReturns :\nthe array of Class objects representing the public members of this class\nThrows :\nSecurityException - If a security manager, s, is present.\n" }, { "code": "// Java program to demonstrate getClasses() method public class Test{ // base interface public interface A { // methods and constant declarations } // derived class public class B implements A { // methods implementations that were declared in A } public static void main(String[] args) throws ClassNotFoundException { // returns the Class object associated with Test class Class c1 = Test.class; // getClasses method on c1 // it returns the array of Class objects containing the all // public classes and interfaces represented by Test class Class[] c1Classes = c1.getClasses(); System.out.println(\"public members of Test class : \"); // iterating through all public members of Test class for (Class class1 : c1Classes) { System.out.println(class1); } }}", "e": 137729, "s": 136769, "text": null }, { "code": null, "e": 137737, "s": 137729, "text": "Output:" }, { "code": null, "e": 137800, "s": 137737, "text": "public members of Test class : \ninterface Test$A\nclass Test$B\n" }, { "code": null, "e": 139748, "s": 137800, "text": "Method[] getMethods() : This method returns an array of Method objects reflecting all the accessible public methods of the class or interface and those inherited from superclasses and super interfaces represented by this Class object.Syntax : \npublic Method[] getMethods() throws SecurityException\nParameters : \nNA\nReturns :\nthe array of Method objects representing the public methods\nand array of length 0 if the class or interface has no accessible public method\nor if this Class object represents a primitive type or void.\nThrows :\nSecurityException - If a security manager, s, is present.\n// Java program to demonstrate getMethods() method import java.lang.reflect.Method; public class Test{ public static void main(String[] args) throws SecurityException,ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"java.lang.Object\"); // getMethods method on c1 // it returns array of methods of Object class Method M[] = c1.getMethods(); System.out.println(\"Below are the methods of Object class : \"); // iterating through all methods of Object class for (Method method : M) { System.out.println(method); } }}Output:Below are the methods of Object class : \npublic final void java.lang.Object.wait() throws java.lang.InterruptedException\npublic final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException\npublic final native void java.lang.Object.wait(long) throws java.lang.InterruptedException\npublic boolean java.lang.Object.equals(java.lang.Object)\npublic java.lang.String java.lang.Object.toString()\npublic native int java.lang.Object.hashCode()\npublic final native java.lang.Class java.lang.Object.getClass()\npublic final native void java.lang.Object.notify()\npublic final native void java.lang.Object.notifyAll()\n" }, { "code": null, "e": 140109, "s": 139748, "text": "Syntax : \npublic Method[] getMethods() throws SecurityException\nParameters : \nNA\nReturns :\nthe array of Method objects representing the public methods\nand array of length 0 if the class or interface has no accessible public method\nor if this Class object represents a primitive type or void.\nThrows :\nSecurityException - If a security manager, s, is present.\n" }, { "code": "// Java program to demonstrate getMethods() method import java.lang.reflect.Method; public class Test{ public static void main(String[] args) throws SecurityException,ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"java.lang.Object\"); // getMethods method on c1 // it returns array of methods of Object class Method M[] = c1.getMethods(); System.out.println(\"Below are the methods of Object class : \"); // iterating through all methods of Object class for (Method method : M) { System.out.println(method); } }}", "e": 140832, "s": 140109, "text": null }, { "code": null, "e": 140840, "s": 140832, "text": "Output:" }, { "code": null, "e": 141465, "s": 140840, "text": "Below are the methods of Object class : \npublic final void java.lang.Object.wait() throws java.lang.InterruptedException\npublic final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException\npublic final native void java.lang.Object.wait(long) throws java.lang.InterruptedException\npublic boolean java.lang.Object.equals(java.lang.Object)\npublic java.lang.String java.lang.Object.toString()\npublic native int java.lang.Object.hashCode()\npublic final native java.lang.Class java.lang.Object.getClass()\npublic final native void java.lang.Object.notify()\npublic final native void java.lang.Object.notifyAll()\n" }, { "code": null, "e": 142937, "s": 141465, "text": "Constructor<?>[] getConstructors() : This method returns an array of Constructor objects reflecting all the public constructors of the class represented by this Class object.Syntax : \npublic Constructor<?>[] getConstructors() throws SecurityException\nParameters : \nNA\nReturns :\nthe array of Constructor objects representing the public constructors of this class\nand array of length 0 if the class or interface has no accessible public constructor\nor if this Class object represents a primitive type or void.\nThrows :\nSecurityException - If a security manager, s, is present.\n// Java program to demonstrate getConstructors() method import java.lang.reflect.Constructor; public class Test{ public static void main(String[] args) throws SecurityException,ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"java.lang.Boolean\"); // getConstructor method on c1 // it returns an array of constructors of Boolean class Constructor C[] = c1.getConstructors(); System.out.println(\"Below are the constructors of Boolean class :\"); // iterating through all constructors for (Constructor constructor : C) { System.out.println(constructor); } }}Output:Below are the constructors of Boolean class :\npublic java.lang.Boolean(boolean)\npublic java.lang.Boolean(java.lang.String)\n" }, { "code": null, "e": 143340, "s": 142937, "text": "Syntax : \npublic Constructor<?>[] getConstructors() throws SecurityException\nParameters : \nNA\nReturns :\nthe array of Constructor objects representing the public constructors of this class\nand array of length 0 if the class or interface has no accessible public constructor\nor if this Class object represents a primitive type or void.\nThrows :\nSecurityException - If a security manager, s, is present.\n" }, { "code": "// Java program to demonstrate getConstructors() method import java.lang.reflect.Constructor; public class Test{ public static void main(String[] args) throws SecurityException,ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"java.lang.Boolean\"); // getConstructor method on c1 // it returns an array of constructors of Boolean class Constructor C[] = c1.getConstructors(); System.out.println(\"Below are the constructors of Boolean class :\"); // iterating through all constructors for (Constructor constructor : C) { System.out.println(constructor); } }}", "e": 144106, "s": 143340, "text": null }, { "code": null, "e": 144114, "s": 144106, "text": "Output:" }, { "code": null, "e": 144238, "s": 144114, "text": "Below are the constructors of Boolean class :\npublic java.lang.Boolean(boolean)\npublic java.lang.Boolean(java.lang.String)\n" }, { "code": null, "e": 145584, "s": 144238, "text": "Field getField(String fieldName) : This method returns a Field object that reflects the specified public member field of the class or interface represented by this Class object.Syntax : \npublic Field getField(String fieldName) throws NoSuchFieldException,SecurityException\nParameters : \nfieldName - the field name\nReturns :\nthe Field object of this class specified by name\nThrows :\nNoSuchFieldException - if a field with the specified name is not found.\nNullPointerException - if fieldName is null\nSecurityException - If a security manager, s, is present.\n// Java program to demonstrate getField() method import java.lang.reflect.Field; public class Test{ public static void main(String[] args) throws SecurityException,ClassNotFoundException, NoSuchFieldException { // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"java.lang.Integer\"); // getField method on c1 // it checks a public field in Integer class with specified parameter Field f = c1.getField(\"MIN_VALUE\"); System.out.println(\"public field in Integer class with MIN_VALUE name :\"); System.out.println(f); }}Output:public field in Integer class with MIN_VALUE name :\npublic static final int java.lang.Integer.MIN_VALUE\n" }, { "code": null, "e": 145965, "s": 145584, "text": "Syntax : \npublic Field getField(String fieldName) throws NoSuchFieldException,SecurityException\nParameters : \nfieldName - the field name\nReturns :\nthe Field object of this class specified by name\nThrows :\nNoSuchFieldException - if a field with the specified name is not found.\nNullPointerException - if fieldName is null\nSecurityException - If a security manager, s, is present.\n" }, { "code": "// Java program to demonstrate getField() method import java.lang.reflect.Field; public class Test{ public static void main(String[] args) throws SecurityException,ClassNotFoundException, NoSuchFieldException { // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"java.lang.Integer\"); // getField method on c1 // it checks a public field in Integer class with specified parameter Field f = c1.getField(\"MIN_VALUE\"); System.out.println(\"public field in Integer class with MIN_VALUE name :\"); System.out.println(f); }}", "e": 146643, "s": 145965, "text": null }, { "code": null, "e": 146651, "s": 146643, "text": "Output:" }, { "code": null, "e": 146756, "s": 146651, "text": "public field in Integer class with MIN_VALUE name :\npublic static final int java.lang.Integer.MIN_VALUE\n" }, { "code": null, "e": 148298, "s": 146756, "text": "Method getMethod(String methodName,Class... parameterTypes) : This method returns a Method object that reflects the specified public member method of the class or interface represented by this Class object.Syntax : \npublic Method getMethod(String methodName,Class... parameterTypes) throws \nNoSuchFieldException,SecurityException\nParameters : \nmethodName - the method name\nparameterTypes - the list of parameters\nReturns :\nthe method object of this class specified by name\nThrows :\nNoSuchMethodException - if a method with the specified name is not found.\nNullPointerException - if methodName is null\nSecurityException - If a security manager, s, is present.\n// Java program to demonstrate getMethod() method import java.lang.reflect.Method; public class Test{ public static void main(String[] args) throws SecurityException,ClassNotFoundException, NoSuchMethodException { // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"java.lang.Integer\"); Class c2 = Class.forName(\"java.lang.String\"); // getMethod method on c1 // it checks for a public Method in Integer class Method m = c1.getMethod(\"parseInt\",c2); System.out.println(\"method in Integer class specified by parseInt : \"); System.out.println(m); }}Output:public method in Integer class specified by parseInt : \npublic static int java.lang.Integer.parseInt(java.lang.String) \nthrows java.lang.NumberFormatException\n" }, { "code": null, "e": 148753, "s": 148298, "text": "Syntax : \npublic Method getMethod(String methodName,Class... parameterTypes) throws \nNoSuchFieldException,SecurityException\nParameters : \nmethodName - the method name\nparameterTypes - the list of parameters\nReturns :\nthe method object of this class specified by name\nThrows :\nNoSuchMethodException - if a method with the specified name is not found.\nNullPointerException - if methodName is null\nSecurityException - If a security manager, s, is present.\n" }, { "code": "// Java program to demonstrate getMethod() method import java.lang.reflect.Method; public class Test{ public static void main(String[] args) throws SecurityException,ClassNotFoundException, NoSuchMethodException { // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"java.lang.Integer\"); Class c2 = Class.forName(\"java.lang.String\"); // getMethod method on c1 // it checks for a public Method in Integer class Method m = c1.getMethod(\"parseInt\",c2); System.out.println(\"method in Integer class specified by parseInt : \"); System.out.println(m); }}", "e": 149469, "s": 148753, "text": null }, { "code": null, "e": 149477, "s": 149469, "text": "Output:" }, { "code": null, "e": 149637, "s": 149477, "text": "public method in Integer class specified by parseInt : \npublic static int java.lang.Integer.parseInt(java.lang.String) \nthrows java.lang.NumberFormatException\n" }, { "code": null, "e": 151490, "s": 149637, "text": "Constructor<?> getConstructor(Class<?>... parameterTypes) : This method returns a Constructor object that reflects the specified public constructor of the class represented by this Class object.The parameterTypes parameter is an array of Class objects that identify the constructor’s formal parameter types, in declared order.Syntax : \npublic Constructor<?> getConstructor(Class<?>... parameterTypes) \nthrows NoSuchMethodException,SecurityException\nParameters : \nparameterTypes - the list of parameters\nReturns :\nthe Constructor object of the public constructor that matches the specified parameterTypes\nThrows :\nNoSuchMethodException - if a Constructor with the specified parameterTypes is not found.\nSecurityException - If a security manager, s, is present.\n// Java program to demonstrate // getConstructor() Constructor import java.lang.reflect.Constructor; public class Test{ public static void main(String[] args) throws SecurityException,ClassNotFoundException, NoSuchMethodException { // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"java.lang.Integer\"); Class c2 = Class.forName(\"java.lang.String\"); // getConstructor method on c1 // it checks a public Constructor in Integer class // with specified parameterTypes Constructor c = c1.getConstructor(c2); System.out.println(\"Constructor in Integer class & String parameterType:\"); System.out.println(c); }}Output:public Constructor in Integer class with String parameterType : \npublic java.lang.Integer(java.lang.String) throws java.lang.NumberFormatException\nNote : The methods getFields(), getMethods(),getConstructors(), getField(), getMethod(), getConstructor() are widely used in Reflection(Refer this for example)" }, { "code": null, "e": 151925, "s": 151490, "text": "Syntax : \npublic Constructor<?> getConstructor(Class<?>... parameterTypes) \nthrows NoSuchMethodException,SecurityException\nParameters : \nparameterTypes - the list of parameters\nReturns :\nthe Constructor object of the public constructor that matches the specified parameterTypes\nThrows :\nNoSuchMethodException - if a Constructor with the specified parameterTypes is not found.\nSecurityException - If a security manager, s, is present.\n" }, { "code": "// Java program to demonstrate // getConstructor() Constructor import java.lang.reflect.Constructor; public class Test{ public static void main(String[] args) throws SecurityException,ClassNotFoundException, NoSuchMethodException { // returns the Class object for the class // with the specified name Class c1 = Class.forName(\"java.lang.Integer\"); Class c2 = Class.forName(\"java.lang.String\"); // getConstructor method on c1 // it checks a public Constructor in Integer class // with specified parameterTypes Constructor c = c1.getConstructor(c2); System.out.println(\"Constructor in Integer class & String parameterType:\"); System.out.println(c); }}", "e": 152705, "s": 151925, "text": null }, { "code": null, "e": 152713, "s": 152705, "text": "Output:" }, { "code": null, "e": 152861, "s": 152713, "text": "public Constructor in Integer class with String parameterType : \npublic java.lang.Integer(java.lang.String) throws java.lang.NumberFormatException\n" }, { "code": null, "e": 153021, "s": 152861, "text": "Note : The methods getFields(), getMethods(),getConstructors(), getField(), getMethod(), getConstructor() are widely used in Reflection(Refer this for example)" }, { "code": null, "e": 153917, "s": 153021, "text": "T cast(Object obj) : This method is used to casts an object to the class or interface represented by this Class object.Syntax : \npublic T cast(Object obj)\nTypeParameters : \nT - The class type whose object is to be cast\nParameters : \nobj - the object to be cast\nReturns :\nthe object after casting, or null if obj is null\nThrows :\nClassCastException - if the object is not null and is not assignable to the type T. \n// Java program to demonstrate cast() methodclass A{ // methods and fields} class B extends A { // methods and fields} // Driver Classpublic class Test{ public static void main(String[] args) { A a = new A(); System.out.println(a.getClass()); B b = new B(); // casting b to a // cast method a = A.class.cast(b); System.out.println(a.getClass()); }}Output:class A\nclass B\n" }, { "code": null, "e": 154213, "s": 153917, "text": "Syntax : \npublic T cast(Object obj)\nTypeParameters : \nT - The class type whose object is to be cast\nParameters : \nobj - the object to be cast\nReturns :\nthe object after casting, or null if obj is null\nThrows :\nClassCastException - if the object is not null and is not assignable to the type T. \n" }, { "code": "// Java program to demonstrate cast() methodclass A{ // methods and fields} class B extends A { // methods and fields} // Driver Classpublic class Test{ public static void main(String[] args) { A a = new A(); System.out.println(a.getClass()); B b = new B(); // casting b to a // cast method a = A.class.cast(b); System.out.println(a.getClass()); }}", "e": 154672, "s": 154213, "text": null }, { "code": null, "e": 154680, "s": 154672, "text": "Output:" }, { "code": null, "e": 154697, "s": 154680, "text": "class A\nclass B\n" }, { "code": null, "e": 156511, "s": 154697, "text": "<U> Class<? extends U> asSubclass(Class<U> clazz) : This method is used to cast this Class object to represent a subclass of the class represented by the specified class object.It always returns a reference to this class object.Syntax : \npublic <U> Class<? extends U> asSubclass(Class<U> class)\nTypeParameters : \nU - The superclass type whose object is to be cast\nParameters : \nclazz - the superclass object to be cast\nReturns :\nthis Class object, cast to represent a subclass of the specified class object.\nThrows :\nClassCastException - if this Class object does not represent a \nsubclass of the specified class\n(here \"subclass\" includes the class itself).\n// Java program to demonstrate asSubclass() methodclass A{ // methods and fields} class B extends A { // methods and fields} // Driver Classpublic class Test{ public static void main(String[] args) { A a = new A(); // returns the Class object for super class(A) Class superClass = a.getClass(); B b = new B(); // returns the Class object for subclass(B) Class subClass = b.getClass(); // asSubclass method // it represent a subclass of the specified class object Class cast = subClass.asSubclass(superClass); System.out.println(cast); }}Output:class B\nThis article is contributed by Gaurav Miglani. 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": 156942, "s": 156511, "text": "Syntax : \npublic <U> Class<? extends U> asSubclass(Class<U> class)\nTypeParameters : \nU - The superclass type whose object is to be cast\nParameters : \nclazz - the superclass object to be cast\nReturns :\nthis Class object, cast to represent a subclass of the specified class object.\nThrows :\nClassCastException - if this Class object does not represent a \nsubclass of the specified class\n(here \"subclass\" includes the class itself).\n" }, { "code": "// Java program to demonstrate asSubclass() methodclass A{ // methods and fields} class B extends A { // methods and fields} // Driver Classpublic class Test{ public static void main(String[] args) { A a = new A(); // returns the Class object for super class(A) Class superClass = a.getClass(); B b = new B(); // returns the Class object for subclass(B) Class subClass = b.getClass(); // asSubclass method // it represent a subclass of the specified class object Class cast = subClass.asSubclass(superClass); System.out.println(cast); }}", "e": 157627, "s": 156942, "text": null }, { "code": null, "e": 157635, "s": 157627, "text": "Output:" }, { "code": null, "e": 157644, "s": 157635, "text": "class B\n" }, { "code": null, "e": 157942, "s": 157644, "text": "This article is contributed by Gaurav Miglani. 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": 158067, "s": 157942, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 158085, "s": 158067, "text": "Java-lang package" }, { "code": null, "e": 158090, "s": 158085, "text": "Java" }, { "code": null, "e": 158095, "s": 158090, "text": "Java" }, { "code": null, "e": 158193, "s": 158095, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 158244, "s": 158193, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 158274, "s": 158244, "text": "HashMap in Java with Examples" }, { "code": null, "e": 158289, "s": 158274, "text": "Stream In Java" }, { "code": null, "e": 158308, "s": 158289, "text": "Interfaces in Java" }, { "code": null, "e": 158339, "s": 158308, "text": "How to iterate any Map in Java" }, { "code": null, "e": 158357, "s": 158339, "text": "ArrayList in Java" }, { "code": null, "e": 158389, "s": 158357, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 158409, "s": 158389, "text": "Stack Class in Java" }, { "code": null, "e": 158433, "s": 158409, "text": "Singleton Class in Java" } ]
PyQt5 QLabel - Setting blur radius to the blur effect - GeeksforGeeks
10 May, 2020 In this article we will see how we can set blur radius to the label blur effect, The blur radius (required), if set to 0 the shadow will be sharp, the higher the number, the more blurred it will be. By default the blur radius value is 5.0 we can change it any time. In order to do this we use setBlurRadius method. Syntax : blur_effect.setBlurRadius(n)Here blur_effect is the QGraphicsBlurEffect object Argument : It takes float value as argument Return : It returns None Below is the implementation # importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating label label = QLabel("Label", self) # setting geometry to the label label.setGeometry(200, 100, 150, 60) # setting alignment to the label label.setAlignment(Qt.AlignCenter) # setting font label.setFont(QFont('Arial', 15)) # setting style sheet of the label label.setStyleSheet("QLabel" "{" "border : 2px solid green;" "background : lightgreen;" "}") # creating a blur effect self.blur_effect = QGraphicsBlurEffect() # setting blur radius self.blur_effect.setBlurRadius(15) # adding blur effect to the label label.setGraphicsEffect(self.blur_effect) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python PyQt5-Label Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() Reading and Writing to text files in Python *args and **kwargs in Python Convert integer to string in Python
[ { "code": null, "e": 26215, "s": 26187, "text": "\n10 May, 2020" }, { "code": null, "e": 26481, "s": 26215, "text": "In this article we will see how we can set blur radius to the label blur effect, The blur radius (required), if set to 0 the shadow will be sharp, the higher the number, the more blurred it will be. By default the blur radius value is 5.0 we can change it any time." }, { "code": null, "e": 26530, "s": 26481, "text": "In order to do this we use setBlurRadius method." }, { "code": null, "e": 26618, "s": 26530, "text": "Syntax : blur_effect.setBlurRadius(n)Here blur_effect is the QGraphicsBlurEffect object" }, { "code": null, "e": 26662, "s": 26618, "text": "Argument : It takes float value as argument" }, { "code": null, "e": 26687, "s": 26662, "text": "Return : It returns None" }, { "code": null, "e": 26715, "s": 26687, "text": "Below is the implementation" }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating label label = QLabel(\"Label\", self) # setting geometry to the label label.setGeometry(200, 100, 150, 60) # setting alignment to the label label.setAlignment(Qt.AlignCenter) # setting font label.setFont(QFont('Arial', 15)) # setting style sheet of the label label.setStyleSheet(\"QLabel\" \"{\" \"border : 2px solid green;\" \"background : lightgreen;\" \"}\") # creating a blur effect self.blur_effect = QGraphicsBlurEffect() # setting blur radius self.blur_effect.setBlurRadius(15) # adding blur effect to the label label.setGraphicsEffect(self.blur_effect) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 28176, "s": 26715, "text": null }, { "code": null, "e": 28185, "s": 28176, "text": "Output :" }, { "code": null, "e": 28204, "s": 28185, "text": "Python PyQt5-Label" }, { "code": null, "e": 28215, "s": 28204, "text": "Python-gui" }, { "code": null, "e": 28227, "s": 28215, "text": "Python-PyQt" }, { "code": null, "e": 28234, "s": 28227, "text": "Python" }, { "code": null, "e": 28332, "s": 28234, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28350, "s": 28332, "text": "Python Dictionary" }, { "code": null, "e": 28385, "s": 28350, "text": "Read a file line by line in Python" }, { "code": null, "e": 28417, "s": 28385, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28439, "s": 28417, "text": "Enumerate() in Python" }, { "code": null, "e": 28481, "s": 28439, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28511, "s": 28481, "text": "Iterate over a list in Python" }, { "code": null, "e": 28537, "s": 28511, "text": "Python String | replace()" }, { "code": null, "e": 28581, "s": 28537, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28610, "s": 28581, "text": "*args and **kwargs in Python" } ]
Check if elements of an array can be arranged satisfying the given condition - GeeksforGeeks
09 Jun, 2021 Given an array arr of N (even) integer elements. The task is to check if it is possible to reorder the elements of the array such that: arr[2*i + 1] = 2 * A[2 * i] for i = 0 ... N-1. Print True if it is possible, otherwise print False.Examples: Input: arr[] = {4, -2, 2, -4} Output: True {-2, -4, 2, 4} is a valid arrangement, -2 * 2 = -4 and 2 * 2 = 4Input: arr[] = {1, 2, 4, 16, 8, 4} Output: False Approach: The idea is that, if k is current minimum element in the array then it must pair with 2 * k as there does not exist any other element k / 2 to pair it with. We check elements in ascending order. When we check an element k and it isn’t used, it must pair with 2 * k. We will attempt to arrange k followed by 2 * k however if we can’t, then the answer is False. In the end, if all the operations are successful, then print True. We will store a count of each element to keep track of what we have not yet considered. Below is the implementation of above approach: C++ Java Python C# Javascript // C++ implementation of the approach#include<bits/stdc++.h>using namespace std; // Function to return true if the elements// can be arranged in the desired orderstring canReorder(int A[],int n){ map<int,int> m; for(int i=0;i<n;i++) m[A[i]]++; sort(A,A+n); int count = 0; for(int i=0;i<n;i++) { if (m[A[i]] == 0) continue; // If 2 * x is not found to pair if (m[2 * A[i]]){ count+=2; // Remove an occurrence of x // and an occurrence of 2 * x m[A[i]] -= 1; m[2 * A[i]] -= 1; } } if(count ==n) return "true"; else return "false";} // Driver Codeint main(){int A[] = {4, -2, 2, -4};int n= sizeof(A)/sizeof(int); // Function call to print required answercout<<(canReorder(A,n)); return 0;}//contributed by Arnab Kundu // Java implementation of the approachimport java.util.HashMap;import java.util.Map;import java.util.Arrays; class GfG{ // Function to return true if the elements // can be arranged in the desired order static String canReorder(int A[],int n) { HashMap<Integer,Integer> m = new HashMap<>(); for(int i = 0; i < n; i++) { if (m.containsKey(A[i])) m.put(A[i], m.get(A[i]) + 1); else m.put(A[i], 1); } Arrays.sort(A); int count = 0; for(int i = 0; i < n; i++) { if (m.get(A[i]) == 0) continue; // If 2 * x is not found to pair if (m.containsKey(2 * A[i])) { count += 2; // Remove an occurrence of x // and an occurrence of 2 * x m.put(A[i], m.get(A[i]) - 1); m.put(2 * A[i], m.get(2 * A[i]) - 1); } } if(count == n) return "true"; else return "false"; } // Driver code public static void main(String []args) { int A[] = {4, -2, 2, -4}; int n = A.length; // Function call to print required answer System.out.println(canReorder(A,n)); }} // This code is contributed by Rituraj Jain # Python implementation of the approachimport collections # Function to return true if the elements# can be arranged in the desired orderdef canReorder(A): count = collections.Counter(A) for x in sorted(A, key = abs): if count[x] == 0: continue # If 2 * x is not found to pair if count[2 * x] == 0: return False # Remove an occurrence of x # and an occurrence of 2 * x count[x] -= 1 count[2 * x] -= 1 return True # Driver CodeA = [4, -2, 2, -4] # Function call to print required answerprint(canReorder(A)) // C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Function to return true if the elements// can be arranged in the desired orderstatic String canReorder(int []A,int n){ Dictionary<int, int> m = new Dictionary<int, int>(); for(int i = 0; i < n; i++) { if (m.ContainsKey(A[i])) m[A[i]]= m[A[i]] + 1; else m.Add(A[i], 1); } Array.Sort(A); int count = 0; for(int i = 0; i < n; i++) { if (m[A[i]] == 0) continue; // If 2 * x is not found to pair if (m.ContainsKey(2 * A[i])) { count += 2; // Remove an occurrence of x // and an occurrence of 2 * x m[A[i]]= m[A[i]] - 1; if (m.ContainsKey(2 * A[i])) m[2 * A[i]]= m[2 * A[i]] - 1; else m.Add(2 * A[i], m[2 * A[i]] - 1); } } if(count == n) return "True"; else return "False";} // Driver codepublic static void Main(String []args){ int []A = {4, -2, 2, -4}; int n = A.Length; // Function call to print required answer Console.WriteLine(canReorder(A,n));}} // This code is contributed by Rajput-Ji <script> // JavaScript implementation of the approach // Function to return true if the elements// can be arranged in the desired orderfunction canReorder(A, n){ let m = new Map(); for(let i=0;i<n;i++){ if(m.has(A[i])){ m.set(A[i], m.get(A[i]) + 1) }else{ m.set(A[i], 1) } } A.sort((a, b) => a - b); let count = 0; for(let i=0;i<n;i++) { if (m.get(A[i]) == 0) continue; // If 2 * x is not found to pair if (m.get(2 * A[i])){ count+=2; // Remove an occurrence of x // and an occurrence of 2 * x m.set(A[i], m.get(A[i]) - 1); m.set(2 * A[i], m.get(2 * A[i])- 1); } } if(count ==n) return "True"; else return "False";} // Driver Code let A = [4, -2, 2, -4];let n= A.length; // Function call to print required answerdocument.write((canReorder(A,n))); // This code is contributed by _saurabh_jaiswal </script> True andrew1234 rituraj_jain Rajput-Ji _saurabh_jaiswal Arrays Greedy Mathematical Python Programs Arrays Greedy Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count pairs with given sum Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element Dijkstra's shortest path algorithm | Greedy Algo-7 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Write a program to print all permutations of a given string Huffman Coding | Greedy Algo-3
[ { "code": null, "e": 26065, "s": 26037, "text": "\n09 Jun, 2021" }, { "code": null, "e": 26203, "s": 26065, "text": "Given an array arr of N (even) integer elements. The task is to check if it is possible to reorder the elements of the array such that: " }, { "code": null, "e": 26253, "s": 26203, "text": "arr[2*i + 1] = 2 * A[2 * i] \n\nfor i = 0 ... N-1. " }, { "code": null, "e": 26317, "s": 26253, "text": "Print True if it is possible, otherwise print False.Examples: " }, { "code": null, "e": 26475, "s": 26317, "text": "Input: arr[] = {4, -2, 2, -4} Output: True {-2, -4, 2, 4} is a valid arrangement, -2 * 2 = -4 and 2 * 2 = 4Input: arr[] = {1, 2, 4, 16, 8, 4} Output: False " }, { "code": null, "e": 27051, "s": 26477, "text": "Approach: The idea is that, if k is current minimum element in the array then it must pair with 2 * k as there does not exist any other element k / 2 to pair it with. We check elements in ascending order. When we check an element k and it isn’t used, it must pair with 2 * k. We will attempt to arrange k followed by 2 * k however if we can’t, then the answer is False. In the end, if all the operations are successful, then print True. We will store a count of each element to keep track of what we have not yet considered. Below is the implementation of above approach: " }, { "code": null, "e": 27055, "s": 27051, "text": "C++" }, { "code": null, "e": 27060, "s": 27055, "text": "Java" }, { "code": null, "e": 27067, "s": 27060, "text": "Python" }, { "code": null, "e": 27070, "s": 27067, "text": "C#" }, { "code": null, "e": 27081, "s": 27070, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include<bits/stdc++.h>using namespace std; // Function to return true if the elements// can be arranged in the desired orderstring canReorder(int A[],int n){ map<int,int> m; for(int i=0;i<n;i++) m[A[i]]++; sort(A,A+n); int count = 0; for(int i=0;i<n;i++) { if (m[A[i]] == 0) continue; // If 2 * x is not found to pair if (m[2 * A[i]]){ count+=2; // Remove an occurrence of x // and an occurrence of 2 * x m[A[i]] -= 1; m[2 * A[i]] -= 1; } } if(count ==n) return \"true\"; else return \"false\";} // Driver Codeint main(){int A[] = {4, -2, 2, -4};int n= sizeof(A)/sizeof(int); // Function call to print required answercout<<(canReorder(A,n)); return 0;}//contributed by Arnab Kundu", "e": 27946, "s": 27081, "text": null }, { "code": "// Java implementation of the approachimport java.util.HashMap;import java.util.Map;import java.util.Arrays; class GfG{ // Function to return true if the elements // can be arranged in the desired order static String canReorder(int A[],int n) { HashMap<Integer,Integer> m = new HashMap<>(); for(int i = 0; i < n; i++) { if (m.containsKey(A[i])) m.put(A[i], m.get(A[i]) + 1); else m.put(A[i], 1); } Arrays.sort(A); int count = 0; for(int i = 0; i < n; i++) { if (m.get(A[i]) == 0) continue; // If 2 * x is not found to pair if (m.containsKey(2 * A[i])) { count += 2; // Remove an occurrence of x // and an occurrence of 2 * x m.put(A[i], m.get(A[i]) - 1); m.put(2 * A[i], m.get(2 * A[i]) - 1); } } if(count == n) return \"true\"; else return \"false\"; } // Driver code public static void main(String []args) { int A[] = {4, -2, 2, -4}; int n = A.length; // Function call to print required answer System.out.println(canReorder(A,n)); }} // This code is contributed by Rituraj Jain", "e": 29381, "s": 27946, "text": null }, { "code": "# Python implementation of the approachimport collections # Function to return true if the elements# can be arranged in the desired orderdef canReorder(A): count = collections.Counter(A) for x in sorted(A, key = abs): if count[x] == 0: continue # If 2 * x is not found to pair if count[2 * x] == 0: return False # Remove an occurrence of x # and an occurrence of 2 * x count[x] -= 1 count[2 * x] -= 1 return True # Driver CodeA = [4, -2, 2, -4] # Function call to print required answerprint(canReorder(A))", "e": 29973, "s": 29381, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Function to return true if the elements// can be arranged in the desired orderstatic String canReorder(int []A,int n){ Dictionary<int, int> m = new Dictionary<int, int>(); for(int i = 0; i < n; i++) { if (m.ContainsKey(A[i])) m[A[i]]= m[A[i]] + 1; else m.Add(A[i], 1); } Array.Sort(A); int count = 0; for(int i = 0; i < n; i++) { if (m[A[i]] == 0) continue; // If 2 * x is not found to pair if (m.ContainsKey(2 * A[i])) { count += 2; // Remove an occurrence of x // and an occurrence of 2 * x m[A[i]]= m[A[i]] - 1; if (m.ContainsKey(2 * A[i])) m[2 * A[i]]= m[2 * A[i]] - 1; else m.Add(2 * A[i], m[2 * A[i]] - 1); } } if(count == n) return \"True\"; else return \"False\";} // Driver codepublic static void Main(String []args){ int []A = {4, -2, 2, -4}; int n = A.Length; // Function call to print required answer Console.WriteLine(canReorder(A,n));}} // This code is contributed by Rajput-Ji", "e": 31281, "s": 29973, "text": null }, { "code": "<script> // JavaScript implementation of the approach // Function to return true if the elements// can be arranged in the desired orderfunction canReorder(A, n){ let m = new Map(); for(let i=0;i<n;i++){ if(m.has(A[i])){ m.set(A[i], m.get(A[i]) + 1) }else{ m.set(A[i], 1) } } A.sort((a, b) => a - b); let count = 0; for(let i=0;i<n;i++) { if (m.get(A[i]) == 0) continue; // If 2 * x is not found to pair if (m.get(2 * A[i])){ count+=2; // Remove an occurrence of x // and an occurrence of 2 * x m.set(A[i], m.get(A[i]) - 1); m.set(2 * A[i], m.get(2 * A[i])- 1); } } if(count ==n) return \"True\"; else return \"False\";} // Driver Code let A = [4, -2, 2, -4];let n= A.length; // Function call to print required answerdocument.write((canReorder(A,n))); // This code is contributed by _saurabh_jaiswal </script>", "e": 32276, "s": 31281, "text": null }, { "code": null, "e": 32281, "s": 32276, "text": "True" }, { "code": null, "e": 32294, "s": 32283, "text": "andrew1234" }, { "code": null, "e": 32307, "s": 32294, "text": "rituraj_jain" }, { "code": null, "e": 32317, "s": 32307, "text": "Rajput-Ji" }, { "code": null, "e": 32334, "s": 32317, "text": "_saurabh_jaiswal" }, { "code": null, "e": 32341, "s": 32334, "text": "Arrays" }, { "code": null, "e": 32348, "s": 32341, "text": "Greedy" }, { "code": null, "e": 32361, "s": 32348, "text": "Mathematical" }, { "code": null, "e": 32377, "s": 32361, "text": "Python Programs" }, { "code": null, "e": 32384, "s": 32377, "text": "Arrays" }, { "code": null, "e": 32391, "s": 32384, "text": "Greedy" }, { "code": null, "e": 32404, "s": 32391, "text": "Mathematical" }, { "code": null, "e": 32502, "s": 32404, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32529, "s": 32502, "text": "Count pairs with given sum" }, { "code": null, "e": 32560, "s": 32529, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 32585, "s": 32560, "text": "Window Sliding Technique" }, { "code": null, "e": 32623, "s": 32585, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 32644, "s": 32623, "text": "Next Greater Element" }, { "code": null, "e": 32695, "s": 32644, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 32746, "s": 32695, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 32804, "s": 32746, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 32864, "s": 32804, "text": "Write a program to print all permutations of a given string" } ]
Program to check if input is an integer or a string - GeeksforGeeks
04 May, 2021 Write a function to check whether a given input is an integer or a string. Definition of an integer : Every element should be a valid digit, i.e '0-9'. Definition of a string : Any one element should be an invalid digit, i.e any symbol other than '0-9'. Examples: Input : 127 Output : Integer Explanation : All digits are in the range '0-9'. Input : 199.7 Output : String Explanation : A dot is present. Input : 122B Output : String Explanation : A alphabet is present. The idea is to use isdigit() function and is_numeric() function.. Below is the implementation of the above idea. C++ Java Python 3 C# PHP Javascript // CPP program to check if a given string// is a valid integer#include <iostream>using namespace std; // Returns true if s is a number else falsebool isNumber(string s){ for (int i = 0; i < s.length(); i++) if (isdigit(s[i]) == false) return false; return true;} // Driver codeint main(){ // Saving the input in a string string str = "6790"; // Function returns 1 if all elements // are in range '0-9' if (isNumber(str)) cout << "Integer"; // Function returns 0 if the input is // not an integer else cout << "String";} // Java program to check if a given// string is a valid integerimport java.io.*; public class GFG { // Returns true if s is // a number else false static boolean isNumber(String s) { for (int i = 0; i < s.length(); i++) if (Character.isDigit(s.charAt(i)) == false) return false; return true; } // Driver code static public void main(String[] args) { // Saving the input in a string String str = "6790"; // Function returns 1 if all elements // are in range '0 - 9' if (isNumber(str)) System.out.println("Integer"); // Function returns 0 if the // input is not an integer else System.out.println("String"); }} // This code is contributed by vt_m. # Python 3 program to check if a given string# is a valid integer # This function Returns true if# s is a number else falsedef isNumber(s): for i in range(len(s)): if s[i].isdigit() != True: return False return True # Driver codeif __name__ == "__main__": # Store the input in a str variable str = "6790" # Function Call if isNumber(str): print("Integer") else: print("String") # This code is contributed by ANKITRAI1 // C# program to check if a given// string is a valid integerusing System; public class GFG { // Returns true if s is a // number else false static bool isNumber(string s) { for (int i = 0; i < s.Length; i++) if (char.IsDigit(s[i]) == false) return false; return true; } // Driver code static public void Main(String[] args) { // Saving the input in a string string str = "6790"; // Function returns 1 if all elements // are in range '0 - 9' if (isNumber(str)) Console.WriteLine("Integer"); // Function returns 0 if the // input is not an integer else Console.WriteLine("String"); }} // This code is contributed by vt_m. <?php// PHP program to check if a// given string is a valid integer // Returns true if s// is a number else falsefunction isNumber($s){ for ($i = 0; $i < strlen($s); $i++) if (is_numeric($s[$i]) == false) return false; return true;} // Driver code // Saving the input// in a string$str = "6790"; // Function returns// 1 if all elements// are in range '0-9'if (isNumber($str)) echo "Integer";else echo "String"; // This code is contributed by ajit?> <script> // Javascript program to check if a given // string is a valid integer // Returns true if s is a // number else false function isNumber(s) { for (let i = 0; i < s.length; i++) if (s[i] < '0' || s[i] > '9') return false; return true; } // Saving the input in a string let str = "6790"; // Function returns 1 if all elements // are in range '0 - 9' if (isNumber(str)) document.write("Integer"); // Function returns 0 if the // input is not an integer else document.write("String"); </script> Integer Using special Python built-in type() function: type() is a built-in function provided by python . type() takes object as parameter and returns its class type as its name says. Below is the implementation of the above idea: Python3 # Python program to find# whether the user input# is int or string type # Function to determine whether# the user input is string or# integer typedef isNumber(x): if type(x) == int: return True else: return False # Driver Codeinput1 = 122input2 = '122' # Function Call # for input1if isNumber(input1): print("Integer")else: print("String") # for input2if isNumber(input2): print("Integer")else: print("String") Integer String This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.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. vt_m jit_t ankthon aditisinggh divyeshrabadiya07 Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Check for Balanced Brackets in an expression (well-formedness) using Stack Python program to check if a string is palindrome or not KMP Algorithm for Pattern Searching Different methods to reverse a string in C/C++ Convert string to char array in C++ Longest Palindromic Substring | Set 1 Caesar Cipher in Cryptography Check whether two strings are anagram of each other Top 50 String Coding Problems for Interviews Length of the longest substring without repeating characters
[ { "code": null, "e": 26141, "s": 26113, "text": "\n04 May, 2021" }, { "code": null, "e": 26216, "s": 26141, "text": "Write a function to check whether a given input is an integer or a string." }, { "code": null, "e": 26244, "s": 26216, "text": "Definition of an integer : " }, { "code": null, "e": 26294, "s": 26244, "text": "Every element should be a valid digit, i.e '0-9'." }, { "code": null, "e": 26320, "s": 26294, "text": "Definition of a string : " }, { "code": null, "e": 26397, "s": 26320, "text": "Any one element should be an invalid digit, i.e any symbol other than '0-9'." }, { "code": null, "e": 26408, "s": 26397, "text": "Examples: " }, { "code": null, "e": 26617, "s": 26408, "text": "Input : 127\nOutput : Integer\nExplanation : All digits are in the range '0-9'.\n\nInput : 199.7\nOutput : String\nExplanation : A dot is present. \n\nInput : 122B\nOutput : String\nExplanation : A alphabet is present." }, { "code": null, "e": 26684, "s": 26617, "text": "The idea is to use isdigit() function and is_numeric() function.. " }, { "code": null, "e": 26732, "s": 26684, "text": "Below is the implementation of the above idea. " }, { "code": null, "e": 26736, "s": 26732, "text": "C++" }, { "code": null, "e": 26741, "s": 26736, "text": "Java" }, { "code": null, "e": 26750, "s": 26741, "text": "Python 3" }, { "code": null, "e": 26753, "s": 26750, "text": "C#" }, { "code": null, "e": 26757, "s": 26753, "text": "PHP" }, { "code": null, "e": 26768, "s": 26757, "text": "Javascript" }, { "code": "// CPP program to check if a given string// is a valid integer#include <iostream>using namespace std; // Returns true if s is a number else falsebool isNumber(string s){ for (int i = 0; i < s.length(); i++) if (isdigit(s[i]) == false) return false; return true;} // Driver codeint main(){ // Saving the input in a string string str = \"6790\"; // Function returns 1 if all elements // are in range '0-9' if (isNumber(str)) cout << \"Integer\"; // Function returns 0 if the input is // not an integer else cout << \"String\";}", "e": 27353, "s": 26768, "text": null }, { "code": "// Java program to check if a given// string is a valid integerimport java.io.*; public class GFG { // Returns true if s is // a number else false static boolean isNumber(String s) { for (int i = 0; i < s.length(); i++) if (Character.isDigit(s.charAt(i)) == false) return false; return true; } // Driver code static public void main(String[] args) { // Saving the input in a string String str = \"6790\"; // Function returns 1 if all elements // are in range '0 - 9' if (isNumber(str)) System.out.println(\"Integer\"); // Function returns 0 if the // input is not an integer else System.out.println(\"String\"); }} // This code is contributed by vt_m.", "e": 28149, "s": 27353, "text": null }, { "code": "# Python 3 program to check if a given string# is a valid integer # This function Returns true if# s is a number else falsedef isNumber(s): for i in range(len(s)): if s[i].isdigit() != True: return False return True # Driver codeif __name__ == \"__main__\": # Store the input in a str variable str = \"6790\" # Function Call if isNumber(str): print(\"Integer\") else: print(\"String\") # This code is contributed by ANKITRAI1", "e": 28626, "s": 28149, "text": null }, { "code": "// C# program to check if a given// string is a valid integerusing System; public class GFG { // Returns true if s is a // number else false static bool isNumber(string s) { for (int i = 0; i < s.Length; i++) if (char.IsDigit(s[i]) == false) return false; return true; } // Driver code static public void Main(String[] args) { // Saving the input in a string string str = \"6790\"; // Function returns 1 if all elements // are in range '0 - 9' if (isNumber(str)) Console.WriteLine(\"Integer\"); // Function returns 0 if the // input is not an integer else Console.WriteLine(\"String\"); }} // This code is contributed by vt_m.", "e": 29398, "s": 28626, "text": null }, { "code": "<?php// PHP program to check if a// given string is a valid integer // Returns true if s// is a number else falsefunction isNumber($s){ for ($i = 0; $i < strlen($s); $i++) if (is_numeric($s[$i]) == false) return false; return true;} // Driver code // Saving the input// in a string$str = \"6790\"; // Function returns// 1 if all elements// are in range '0-9'if (isNumber($str)) echo \"Integer\";else echo \"String\"; // This code is contributed by ajit?>", "e": 29878, "s": 29398, "text": null }, { "code": "<script> // Javascript program to check if a given // string is a valid integer // Returns true if s is a // number else false function isNumber(s) { for (let i = 0; i < s.length; i++) if (s[i] < '0' || s[i] > '9') return false; return true; } // Saving the input in a string let str = \"6790\"; // Function returns 1 if all elements // are in range '0 - 9' if (isNumber(str)) document.write(\"Integer\"); // Function returns 0 if the // input is not an integer else document.write(\"String\"); </script>", "e": 30490, "s": 29878, "text": null }, { "code": null, "e": 30498, "s": 30490, "text": "Integer" }, { "code": null, "e": 30545, "s": 30498, "text": "Using special Python built-in type() function:" }, { "code": null, "e": 30674, "s": 30545, "text": "type() is a built-in function provided by python . type() takes object as parameter and returns its class type as its name says." }, { "code": null, "e": 30721, "s": 30674, "text": "Below is the implementation of the above idea:" }, { "code": null, "e": 30729, "s": 30721, "text": "Python3" }, { "code": "# Python program to find# whether the user input# is int or string type # Function to determine whether# the user input is string or# integer typedef isNumber(x): if type(x) == int: return True else: return False # Driver Codeinput1 = 122input2 = '122' # Function Call # for input1if isNumber(input1): print(\"Integer\")else: print(\"String\") # for input2if isNumber(input2): print(\"Integer\")else: print(\"String\")", "e": 31175, "s": 30729, "text": null }, { "code": null, "e": 31190, "s": 31175, "text": "Integer\nString" }, { "code": null, "e": 31613, "s": 31190, "text": "This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.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": 31618, "s": 31613, "text": "vt_m" }, { "code": null, "e": 31624, "s": 31618, "text": "jit_t" }, { "code": null, "e": 31632, "s": 31624, "text": "ankthon" }, { "code": null, "e": 31644, "s": 31632, "text": "aditisinggh" }, { "code": null, "e": 31662, "s": 31644, "text": "divyeshrabadiya07" }, { "code": null, "e": 31670, "s": 31662, "text": "Strings" }, { "code": null, "e": 31678, "s": 31670, "text": "Strings" }, { "code": null, "e": 31776, "s": 31678, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31851, "s": 31776, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 31908, "s": 31851, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 31944, "s": 31908, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 31991, "s": 31944, "text": "Different methods to reverse a string in C/C++" }, { "code": null, "e": 32027, "s": 31991, "text": "Convert string to char array in C++" }, { "code": null, "e": 32065, "s": 32027, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 32095, "s": 32065, "text": "Caesar Cipher in Cryptography" }, { "code": null, "e": 32147, "s": 32095, "text": "Check whether two strings are anagram of each other" }, { "code": null, "e": 32192, "s": 32147, "text": "Top 50 String Coding Problems for Interviews" } ]
Python Program For Chocolate Distribution Problem - GeeksforGeeks
06 Jan, 2022 Given an array of n integers where each value represents the number of chocolates in a packet. Each packet can have a variable number of chocolates. There are m students, the task is to distribute chocolate packets such that: Each student gets one packet.The difference between the number of chocolates in the packet with maximum chocolates and packet with minimum chocolates given to the students is minimum. Each student gets one packet. The difference between the number of chocolates in the packet with maximum chocolates and packet with minimum chocolates given to the students is minimum. Examples: Input : arr[] = {7, 3, 2, 4, 9, 12, 56} , m = 3 Output: Minimum Difference is 2 Explanation:We have seven packets of chocolates and we need to pick three packets for 3 students If we pick 2, 3 and 4, we get the minimum difference between maximum and minimum packet sizes. Input : arr[] = {3, 4, 1, 9, 56, 7, 9, 12} , m = 5 Output: Minimum Difference is 6 Explanation:The set goes like 3,4,7,9,9 and the output is 9-3 = 6 Input : arr[] = {12, 4, 7, 9, 2, 23, 25, 41, 30, 40, 28, 42, 30, 44, 48, 43, 50} , m = 7 Output: Minimum Difference is 10 Explanation:We need to pick 7 packets. We pick 40, 41, 42, 44, 48, 43 and 50 to minimize difference between maximum and minimum. Source: Flipkart Interview Experience A simple solution is to generate all subsets of size m of arr[0..n-1]. For every subset, find the difference between the maximum and minimum elements in it. Finally, return the minimum difference.An efficient solution is based on the observation that to minimize the difference, we must choose consecutive elements from a sorted packet. We first sort the array arr[0..n-1], then find the subarray of size m with the minimum difference between the last and first elements. Below image is a dry run of the above approach: Below is the implementation of the above approach: Python3 # Python3 program to solve chocolate# distribution problem # arr[0..n-1] represents sizes of packets# m is number of students.# Returns minimum difference between maximum# and minimum values of distribution.def findMinDiff(arr, n, m): # if there are no chocolates or number # of students is 0 if (m==0 or n==0): return 0 # Sort the given packets arr.sort() # Number of students cannot be more # than number of packets if (n < m): return -1 # Largest number of chocolates min_diff = arr[n-1] - arr[0] # Find the subarray of size m such that # difference between last (maximum in case # of sorted) and first (minimum in case of # sorted) elements of subarray is minimum. for i in range(len(arr) - m + 1): min_diff = min(min_diff , arr[i + m - 1] - arr[i]) return min_diff # Driver Codeif __name__ == "__main__": arr = [12, 4, 7, 9, 2, 23, 25, 41, 30, 40, 28, 42, 30, 44, 48, 43, 50] # Number of students m = 7 n = len(arr) print("Minimum difference is", findMinDiff(arr, n, m))# This code is contributed by Smitha Output: Minimum difference is 10 Time Complexity: O(n Log n) as we apply sorting before subarray search. Please refer complete article on Chocolate Distribution Problem for more details! Flipkart subset Arrays Python Programs Sorting Flipkart Arrays Sorting subset Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Chocolate Distribution Problem Count pairs with given sum Window Sliding Technique Reversal algorithm for array rotation Next Greater Element Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 26041, "s": 26013, "text": "\n06 Jan, 2022" }, { "code": null, "e": 26268, "s": 26041, "text": "Given an array of n integers where each value represents the number of chocolates in a packet. Each packet can have a variable number of chocolates. There are m students, the task is to distribute chocolate packets such that: " }, { "code": null, "e": 26452, "s": 26268, "text": "Each student gets one packet.The difference between the number of chocolates in the packet with maximum chocolates and packet with minimum chocolates given to the students is minimum." }, { "code": null, "e": 26482, "s": 26452, "text": "Each student gets one packet." }, { "code": null, "e": 26637, "s": 26482, "text": "The difference between the number of chocolates in the packet with maximum chocolates and packet with minimum chocolates given to the students is minimum." }, { "code": null, "e": 26647, "s": 26637, "text": "Examples:" }, { "code": null, "e": 26919, "s": 26647, "text": "Input : arr[] = {7, 3, 2, 4, 9, 12, 56} , m = 3 Output: Minimum Difference is 2 Explanation:We have seven packets of chocolates and we need to pick three packets for 3 students If we pick 2, 3 and 4, we get the minimum difference between maximum and minimum packet sizes." }, { "code": null, "e": 27068, "s": 26919, "text": "Input : arr[] = {3, 4, 1, 9, 56, 7, 9, 12} , m = 5 Output: Minimum Difference is 6 Explanation:The set goes like 3,4,7,9,9 and the output is 9-3 = 6" }, { "code": null, "e": 27320, "s": 27068, "text": "Input : arr[] = {12, 4, 7, 9, 2, 23, 25, 41, 30, 40, 28, 42, 30, 44, 48, 43, 50} , m = 7 Output: Minimum Difference is 10 Explanation:We need to pick 7 packets. We pick 40, 41, 42, 44, 48, 43 and 50 to minimize difference between maximum and minimum. " }, { "code": null, "e": 27358, "s": 27320, "text": "Source: Flipkart Interview Experience" }, { "code": null, "e": 27830, "s": 27358, "text": "A simple solution is to generate all subsets of size m of arr[0..n-1]. For every subset, find the difference between the maximum and minimum elements in it. Finally, return the minimum difference.An efficient solution is based on the observation that to minimize the difference, we must choose consecutive elements from a sorted packet. We first sort the array arr[0..n-1], then find the subarray of size m with the minimum difference between the last and first elements." }, { "code": null, "e": 27878, "s": 27830, "text": "Below image is a dry run of the above approach:" }, { "code": null, "e": 27930, "s": 27878, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27938, "s": 27930, "text": "Python3" }, { "code": "# Python3 program to solve chocolate# distribution problem # arr[0..n-1] represents sizes of packets# m is number of students.# Returns minimum difference between maximum# and minimum values of distribution.def findMinDiff(arr, n, m): # if there are no chocolates or number # of students is 0 if (m==0 or n==0): return 0 # Sort the given packets arr.sort() # Number of students cannot be more # than number of packets if (n < m): return -1 # Largest number of chocolates min_diff = arr[n-1] - arr[0] # Find the subarray of size m such that # difference between last (maximum in case # of sorted) and first (minimum in case of # sorted) elements of subarray is minimum. for i in range(len(arr) - m + 1): min_diff = min(min_diff , arr[i + m - 1] - arr[i]) return min_diff # Driver Codeif __name__ == \"__main__\": arr = [12, 4, 7, 9, 2, 23, 25, 41, 30, 40, 28, 42, 30, 44, 48, 43, 50] # Number of students m = 7 n = len(arr) print(\"Minimum difference is\", findMinDiff(arr, n, m))# This code is contributed by Smitha", "e": 29120, "s": 27938, "text": null }, { "code": null, "e": 29128, "s": 29120, "text": "Output:" }, { "code": null, "e": 29153, "s": 29128, "text": "Minimum difference is 10" }, { "code": null, "e": 29225, "s": 29153, "text": "Time Complexity: O(n Log n) as we apply sorting before subarray search." }, { "code": null, "e": 29307, "s": 29225, "text": "Please refer complete article on Chocolate Distribution Problem for more details!" }, { "code": null, "e": 29316, "s": 29307, "text": "Flipkart" }, { "code": null, "e": 29323, "s": 29316, "text": "subset" }, { "code": null, "e": 29330, "s": 29323, "text": "Arrays" }, { "code": null, "e": 29346, "s": 29330, "text": "Python Programs" }, { "code": null, "e": 29354, "s": 29346, "text": "Sorting" }, { "code": null, "e": 29363, "s": 29354, "text": "Flipkart" }, { "code": null, "e": 29370, "s": 29363, "text": "Arrays" }, { "code": null, "e": 29378, "s": 29370, "text": "Sorting" }, { "code": null, "e": 29385, "s": 29378, "text": "subset" }, { "code": null, "e": 29483, "s": 29385, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29514, "s": 29483, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 29541, "s": 29514, "text": "Count pairs with given sum" }, { "code": null, "e": 29566, "s": 29541, "text": "Window Sliding Technique" }, { "code": null, "e": 29604, "s": 29566, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 29625, "s": 29604, "text": "Next Greater Element" }, { "code": null, "e": 29668, "s": 29625, "text": "Python program to convert a list to string" }, { "code": null, "e": 29690, "s": 29668, "text": "Defaultdict in Python" }, { "code": null, "e": 29729, "s": 29690, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 29775, "s": 29729, "text": "Python | Split string into list of characters" } ]
Number Representation - GeeksforGeeks
12 Mar, 2018 P is a 16-bit signed integer. The 2's complement representation of P is (F87B)16.The 2's complement representation of 8*P (C3D8)16 (187B)16 (F878)16 (987B)16 P = (F87B)16 is -1111 1000 0111 1011 in binary Note that most significant bit in the binary representation is 1, which implies that the number is negative. To get the value of the number performs the 2's complement of the number. We get P as -1925 and 8P as -15400 Since 8P is also negative, we need to find 2's complement of it (-15400) Binary of 15400 = 0011 1100 0010 1000 2's Complement = 1100 0011 1101 1000 = (C3D8)16 xy=30 possible combinations =(1,30),(2,15),(3,10) Since No is negative S bit will be 1 Convert 14.25 into binary 1110.01 Normalize it : 1.11001 X 2 ^ 3 Biased Exponent (Add 127) : 3 + 127 = 130 (In binary 10000010) Mantissa : 110010.....0 (Total 23 bits) Num represented in IEEE 754 single precision format : 1 10000010 11001000000000000000000 In Hex (Group of Four bits) - 1100 0001 0110 0100 0000 0000 0000 0000 Num becomes : C1640000 0001 =1 1010 =A 1111 =F Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Best Time to Buy and Sell Stock Must Do Coding Questions for Product Based Companies How to calculate MOVING AVERAGE in a Pandas DataFrame? What is Transmission Control Protocol (TCP)? How to Calculate Number of Host in a Subnet? Python OpenCV - Canny() Function How to Convert Categorical Variable to Numeric in Pandas? How to Replace Values in Column Based on Condition in Pandas? How to Fix: SyntaxError: positional argument follows keyword argument in Python How to Fix: KeyError in Pandas
[ { "code": null, "e": 28055, "s": 28027, "text": "\n12 Mar, 2018" }, { "code": null, "e": 28178, "s": 28055, "text": "P is a 16-bit signed integer. The 2's complement representation of P is (F87B)16.The 2's complement representation of 8*P " }, { "code": null, "e": 28188, "s": 28178, "text": "(C3D8)16 " }, { "code": null, "e": 28198, "s": 28188, "text": "(187B)16 " }, { "code": null, "e": 28208, "s": 28198, "text": "(F878)16 " }, { "code": null, "e": 28218, "s": 28208, "text": "(987B)16 " }, { "code": null, "e": 28643, "s": 28218, "text": "P = (F87B)16 is -1111 1000 0111 1011 in binary Note that most significant bit in the binary representation is 1, which implies that the number is negative. To get the value of the number performs the 2's complement of the number. We get P as -1925 and 8P as -15400 Since 8P is also negative, we need to find 2's complement of it (-15400) Binary of 15400 = 0011 1100 0010 1000 2's Complement = 1100 0011 1101 1000 = (C3D8)16 " }, { "code": null, "e": 28649, "s": 28643, "text": "xy=30" }, { "code": null, "e": 28693, "s": 28649, "text": "possible combinations =(1,30),(2,15),(3,10)" }, { "code": null, "e": 29086, "s": 28693, "text": "Since No is negative S bit will be 1\nConvert 14.25 into binary 1110.01\nNormalize it : 1.11001 X 2 ^ 3\nBiased Exponent (Add 127) : 3 + 127 = 130 (In binary 10000010)\nMantissa : 110010.....0 (Total 23 bits)\n\nNum represented in IEEE 754 single precision format :\n\n1 10000010 11001000000000000000000\n\nIn Hex (Group of Four bits) -\n\n1100 0001 0110 0100 0000 0000 0000 0000\n\nNum becomes : C1640000\n" }, { "code": null, "e": 29094, "s": 29086, "text": "0001 =1" }, { "code": null, "e": 29102, "s": 29094, "text": "1010 =A" }, { "code": null, "e": 29110, "s": 29102, "text": "1111 =F" }, { "code": null, "e": 29208, "s": 29110, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 29240, "s": 29208, "text": "Best Time to Buy and Sell Stock" }, { "code": null, "e": 29293, "s": 29240, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 29348, "s": 29293, "text": "How to calculate MOVING AVERAGE in a Pandas DataFrame?" }, { "code": null, "e": 29393, "s": 29348, "text": "What is Transmission Control Protocol (TCP)?" }, { "code": null, "e": 29438, "s": 29393, "text": "How to Calculate Number of Host in a Subnet?" }, { "code": null, "e": 29471, "s": 29438, "text": "Python OpenCV - Canny() Function" }, { "code": null, "e": 29529, "s": 29471, "text": "How to Convert Categorical Variable to Numeric in Pandas?" }, { "code": null, "e": 29591, "s": 29529, "text": "How to Replace Values in Column Based on Condition in Pandas?" }, { "code": null, "e": 29671, "s": 29591, "text": "How to Fix: SyntaxError: positional argument follows keyword argument in Python" } ]
BFS using vectors & queue as per the algorithm of CLRS - GeeksforGeeks
15 Nov, 2021 Breadth-first search traversal of a graph using the algorithm given in CLRS book.BFS is one of the ways to traverse a graph. It is named so because it expands the frontier between discovered and undiscovered vertices uniformly across the breadth of the frontier. What it means is that the algorithm first discovers all the vertices connected to “u” at a distance of k before discovering the vertices at a distance of k+1 from u. The algorithm given in CLRS uses the concept of “colour” to check if a vertex is discovered fully or partially or undiscovered. It also keeps a track of the distance a vertex u is from the source s. BFS(G,s) 1 for each vertex u in G.V - {s} 2 u.color = white 3 u.d = INF 4 u.p = NIL 5 s.color = green 6 s.d = 0 7 s.p = NIL 8 Q = NULL 9 ENQUEUE(Q,s) 10 while Q != NULL 11 u = DEQUEUE(Q) 12 for each v in G.Adj[u] 13 if v.color == white 14 v.color = green 15 v.d = u.d + 1 16 v.p = u 17 ENQUEUE(Q,v) 18 u.color = dark_green It produces a “breadth-first tree” with root s that contains all reachable vertices. Let’s take a simple directed graph and see how BFS traverses it. The graph Starting of traversal 1st traversal 1st traversal completes C++ Python3 Javascript // CPP program to implement BFS as per CLRS // algorithm.#include <bits/stdc++.h>using namespace std; // Declaring the vectors to store color, distance// and parentvector<string> colour;vector<int> d;vector<int> p; /* This function adds an edge to the graph.It is an undirected graph. So edges are added for both the nodes. */void addEdge(vector <int> g[], int u, int v){ g[u].push_back(v); g[v].push_back(u);} /* This function does the Breadth First Search*/void BFSSingleSource(vector <int> g[], int s){ // The Queue used for the BFS operation queue<int> q; // Pushing the root node inside the queue q.push(s); /* Distance of root node is 0 & colour is gray as it is visited partially now */ d[s] = 0; colour[s] = "green"; /* Loop to traverse the graph. Traversal will happen traverse until the queue is not empty.*/ while (!q.empty()) { /* Extracting the front element(node) and poping it out of queue. */ int u = q.front(); q.pop(); cout << u << " "; /* This loop traverses all the child nodes of u */ for (auto i = g[u].begin(); i != g[u].end(); i++) { /* If the colour is white then the said node is not traversed. */ if (colour[*i] == "white") { colour[*i] = "green"; d[*i] = d[u] + 1; p[*i] = u; /* Pushing the node inside queue to traverse its children. */ q.push(*i); } } /* Now the node u is completely traversed and colour is changed to black. */ colour[u] = "dark_green"; }} void BFSFull(vector <int> g[], int n){ /* Initially all nodes are not traversed. Therefore, the colour is white. */ colour.assign(n, "white"); d.assign(n, 0); p.assign(n, -1); // Calling BFSSingleSource() for all white // vertices. for (int i = 0; i < n; i++) if (colour[i] == "white") BFSSingleSource(g, i); } // Driver Functionint main(){ // Graph with 7 nodes and 6 edges. int n = 7; // The Graph vector vector <int> g[n]; addEdge(g, 0, 1); addEdge(g, 0, 2); addEdge(g, 1, 3); addEdge(g, 1, 4); addEdge(g, 2, 5); addEdge(g, 2, 6); BFSFull(g, n); return 0;} # Python3 program to implement BFS as # per CLRS algorithm. import queue # This function adds an edge to the graph. # It is an undirected graph. So edges # are added for both the nodes. def addEdge(g, u, v): g[u].append(v) g[v].append(u) # This function does the Breadth# First Searchdef BFSSingleSource(g, s): # The Queue used for the BFS operation q = queue.Queue() # Pushing the root node inside # the queue q.put(s) # Distance of root node is 0 & colour is # gray as it is visited partially now d[s] = 0 colour[s] = "green" # Loop to traverse the graph. Traversal # will happen traverse until the queue # is not empty. while (not q.empty()): # Extracting the front element(node) # and poping it out of queue. u = q.get() print(u, end = " ") # This loop traverses all the child # nodes of u i = 0 while i < len(g[u]): # If the colour is white then # the said node is not traversed. if (colour[g[u][i]] == "white"): colour[g[u][i]] = "green" d[g[u][i]] = d[u] + 1 p[g[u][i]] = u # Pushing the node inside queue # to traverse its children. q.put(g[u][i]) i += 1 # Now the node u is completely traversed # and colour is changed to black. colour[u] = "dark_green" def BFSFull(g, n): # Initially all nodes are not traversed. # Therefore, the colour is white. colour = ["white"] * n d = [0] * n p = [-1] * n # Calling BFSSingleSource() for all # white vertices for i in range(n): if (colour[i] == "white"): BFSSingleSource(g, i) # Driver Code # Graph with 7 nodes and 6 edges. n = 7 # Declaring the vectors to store color, # distance and parent colour = [None] * nd = [None] * np = [None] * n # The Graph vector g = [[] for i in range(n)] addEdge(g, 0, 1) addEdge(g, 0, 2) addEdge(g, 1, 3) addEdge(g, 1, 4) addEdge(g, 2, 5) addEdge(g, 2, 6) BFSFull(g, n) # This code is contributed by Pranchalk <script>// Javascript program to implement BFS as per CLRS // algorithm. // Declaring the vectors to store color, distance// and parentvar colour = [];var d = [];var p = []; /* This function adds an edge to the graph.It is an undirected graph. So edges are added for both the nodes. */function addEdge(g, u, v){ g[u].push(v); g[v].push(u);} /* This function does the Breadth First Search*/function BFSSingleSource(g, s){ // The Queue used for the BFS operation var q = []; // Pushing the root node inside the queue q.push(s); /* Distance of root node is 0 & colour is gray as it is visited partially now */ d[s] = 0; colour[s] = "green"; /* Loop to traverse the graph. Traversal will happen traverse until the queue is not empty.*/ while (q.length!=0) { /* Extracting the front element(node) and poping it out of queue. */ var u = q[0]; q.shift(); document.write( u + " "); /* This loop traverses all the child nodes of u */ for(var i of g[u]) { /* If the colour is white then the said node is not traversed. */ if (colour[i] == "white") { colour[i] = "green"; d[i] = d[u] + 1; p[i] = u; /* Pushing the node inside queue to traverse its children. */ q.push(i); } } /* Now the node u is completely traversed and colour is changed to black. */ colour[u] = "dark_green"; }} function BFSFull(g, n){ /* Initially all nodes are not traversed. Therefore, the colour is white. */ colour = Array(n).fill("white"); d = Array(n).fill(0); p = Array(n).fill(0); // Calling BFSSingleSource() for all white // vertices. for (var i = 0; i < n; i++) if (colour[i] == "white") BFSSingleSource(g, i); } // Driver Function// Graph with 7 nodes and 6 edges.var n = 7; // The Graph vectorvar g = Array.from(Array(n), ()=>Array()); addEdge(g, 0, 1);addEdge(g, 0, 2);addEdge(g, 1, 3);addEdge(g, 1, 4);addEdge(g, 2, 5);addEdge(g, 2, 6);BFSFull(g, n); // This code is contributed by rutvik_56.</script> Output: 0 1 2 3 4 5 6 Kunjal Rupala PranchalKatiyar rutvik_56 BFS Graph Graph BFS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Ford-Fulkerson Algorithm for Maximum Flow Problem Traveling Salesman Problem (TSP) Implementation Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8 Hamiltonian Cycle | Backtracking-6 m Coloring Problem | Backtracking-5 Check whether a given graph is Bipartite or not Union-Find Algorithm | Set 2 (Union By Rank and Path Compression) Shortest path in an unweighted graph Best First Search (Informed Search) Connected Components in an undirected graph
[ { "code": null, "e": 26337, "s": 26309, "text": "\n15 Nov, 2021" }, { "code": null, "e": 26966, "s": 26337, "text": "Breadth-first search traversal of a graph using the algorithm given in CLRS book.BFS is one of the ways to traverse a graph. It is named so because it expands the frontier between discovered and undiscovered vertices uniformly across the breadth of the frontier. What it means is that the algorithm first discovers all the vertices connected to “u” at a distance of k before discovering the vertices at a distance of k+1 from u. The algorithm given in CLRS uses the concept of “colour” to check if a vertex is discovered fully or partially or undiscovered. It also keeps a track of the distance a vertex u is from the source s. " }, { "code": null, "e": 27358, "s": 26966, "text": "BFS(G,s)\n1 for each vertex u in G.V - {s}\n2 u.color = white\n3 u.d = INF\n4 u.p = NIL\n5 s.color = green\n6 s.d = 0\n7 s.p = NIL\n8 Q = NULL\n9 ENQUEUE(Q,s)\n10 while Q != NULL\n11 u = DEQUEUE(Q)\n12 for each v in G.Adj[u]\n13 if v.color == white\n14 v.color = green\n15 v.d = u.d + 1\n16 v.p = u\n17 ENQUEUE(Q,v)\n18 u.color = dark_green" }, { "code": null, "e": 27509, "s": 27358, "text": "It produces a “breadth-first tree” with root s that contains all reachable vertices. Let’s take a simple directed graph and see how BFS traverses it. " }, { "code": null, "e": 27519, "s": 27509, "text": "The graph" }, { "code": null, "e": 27543, "s": 27521, "text": "Starting of traversal" }, { "code": null, "e": 27559, "s": 27545, "text": "1st traversal" }, { "code": null, "e": 27585, "s": 27561, "text": "1st traversal completes" }, { "code": null, "e": 27593, "s": 27589, "text": "C++" }, { "code": null, "e": 27601, "s": 27593, "text": "Python3" }, { "code": null, "e": 27612, "s": 27601, "text": "Javascript" }, { "code": "// CPP program to implement BFS as per CLRS // algorithm.#include <bits/stdc++.h>using namespace std; // Declaring the vectors to store color, distance// and parentvector<string> colour;vector<int> d;vector<int> p; /* This function adds an edge to the graph.It is an undirected graph. So edges are added for both the nodes. */void addEdge(vector <int> g[], int u, int v){ g[u].push_back(v); g[v].push_back(u);} /* This function does the Breadth First Search*/void BFSSingleSource(vector <int> g[], int s){ // The Queue used for the BFS operation queue<int> q; // Pushing the root node inside the queue q.push(s); /* Distance of root node is 0 & colour is gray as it is visited partially now */ d[s] = 0; colour[s] = \"green\"; /* Loop to traverse the graph. Traversal will happen traverse until the queue is not empty.*/ while (!q.empty()) { /* Extracting the front element(node) and poping it out of queue. */ int u = q.front(); q.pop(); cout << u << \" \"; /* This loop traverses all the child nodes of u */ for (auto i = g[u].begin(); i != g[u].end(); i++) { /* If the colour is white then the said node is not traversed. */ if (colour[*i] == \"white\") { colour[*i] = \"green\"; d[*i] = d[u] + 1; p[*i] = u; /* Pushing the node inside queue to traverse its children. */ q.push(*i); } } /* Now the node u is completely traversed and colour is changed to black. */ colour[u] = \"dark_green\"; }} void BFSFull(vector <int> g[], int n){ /* Initially all nodes are not traversed. Therefore, the colour is white. */ colour.assign(n, \"white\"); d.assign(n, 0); p.assign(n, -1); // Calling BFSSingleSource() for all white // vertices. for (int i = 0; i < n; i++) if (colour[i] == \"white\") BFSSingleSource(g, i); } // Driver Functionint main(){ // Graph with 7 nodes and 6 edges. int n = 7; // The Graph vector vector <int> g[n]; addEdge(g, 0, 1); addEdge(g, 0, 2); addEdge(g, 1, 3); addEdge(g, 1, 4); addEdge(g, 2, 5); addEdge(g, 2, 6); BFSFull(g, n); return 0;}", "e": 29973, "s": 27612, "text": null }, { "code": "# Python3 program to implement BFS as # per CLRS algorithm. import queue # This function adds an edge to the graph. # It is an undirected graph. So edges # are added for both the nodes. def addEdge(g, u, v): g[u].append(v) g[v].append(u) # This function does the Breadth# First Searchdef BFSSingleSource(g, s): # The Queue used for the BFS operation q = queue.Queue() # Pushing the root node inside # the queue q.put(s) # Distance of root node is 0 & colour is # gray as it is visited partially now d[s] = 0 colour[s] = \"green\" # Loop to traverse the graph. Traversal # will happen traverse until the queue # is not empty. while (not q.empty()): # Extracting the front element(node) # and poping it out of queue. u = q.get() print(u, end = \" \") # This loop traverses all the child # nodes of u i = 0 while i < len(g[u]): # If the colour is white then # the said node is not traversed. if (colour[g[u][i]] == \"white\"): colour[g[u][i]] = \"green\" d[g[u][i]] = d[u] + 1 p[g[u][i]] = u # Pushing the node inside queue # to traverse its children. q.put(g[u][i]) i += 1 # Now the node u is completely traversed # and colour is changed to black. colour[u] = \"dark_green\" def BFSFull(g, n): # Initially all nodes are not traversed. # Therefore, the colour is white. colour = [\"white\"] * n d = [0] * n p = [-1] * n # Calling BFSSingleSource() for all # white vertices for i in range(n): if (colour[i] == \"white\"): BFSSingleSource(g, i) # Driver Code # Graph with 7 nodes and 6 edges. n = 7 # Declaring the vectors to store color, # distance and parent colour = [None] * nd = [None] * np = [None] * n # The Graph vector g = [[] for i in range(n)] addEdge(g, 0, 1) addEdge(g, 0, 2) addEdge(g, 1, 3) addEdge(g, 1, 4) addEdge(g, 2, 5) addEdge(g, 2, 6) BFSFull(g, n) # This code is contributed by Pranchalk", "e": 32167, "s": 29973, "text": null }, { "code": "<script>// Javascript program to implement BFS as per CLRS // algorithm. // Declaring the vectors to store color, distance// and parentvar colour = [];var d = [];var p = []; /* This function adds an edge to the graph.It is an undirected graph. So edges are added for both the nodes. */function addEdge(g, u, v){ g[u].push(v); g[v].push(u);} /* This function does the Breadth First Search*/function BFSSingleSource(g, s){ // The Queue used for the BFS operation var q = []; // Pushing the root node inside the queue q.push(s); /* Distance of root node is 0 & colour is gray as it is visited partially now */ d[s] = 0; colour[s] = \"green\"; /* Loop to traverse the graph. Traversal will happen traverse until the queue is not empty.*/ while (q.length!=0) { /* Extracting the front element(node) and poping it out of queue. */ var u = q[0]; q.shift(); document.write( u + \" \"); /* This loop traverses all the child nodes of u */ for(var i of g[u]) { /* If the colour is white then the said node is not traversed. */ if (colour[i] == \"white\") { colour[i] = \"green\"; d[i] = d[u] + 1; p[i] = u; /* Pushing the node inside queue to traverse its children. */ q.push(i); } } /* Now the node u is completely traversed and colour is changed to black. */ colour[u] = \"dark_green\"; }} function BFSFull(g, n){ /* Initially all nodes are not traversed. Therefore, the colour is white. */ colour = Array(n).fill(\"white\"); d = Array(n).fill(0); p = Array(n).fill(0); // Calling BFSSingleSource() for all white // vertices. for (var i = 0; i < n; i++) if (colour[i] == \"white\") BFSSingleSource(g, i); } // Driver Function// Graph with 7 nodes and 6 edges.var n = 7; // The Graph vectorvar g = Array.from(Array(n), ()=>Array()); addEdge(g, 0, 1);addEdge(g, 0, 2);addEdge(g, 1, 3);addEdge(g, 1, 4);addEdge(g, 2, 5);addEdge(g, 2, 6);BFSFull(g, n); // This code is contributed by rutvik_56.</script>", "e": 34408, "s": 32167, "text": null }, { "code": null, "e": 34418, "s": 34408, "text": "Output: " }, { "code": null, "e": 34432, "s": 34418, "text": "0 1 2 3 4 5 6" }, { "code": null, "e": 34448, "s": 34434, "text": "Kunjal Rupala" }, { "code": null, "e": 34464, "s": 34448, "text": "PranchalKatiyar" }, { "code": null, "e": 34474, "s": 34464, "text": "rutvik_56" }, { "code": null, "e": 34478, "s": 34474, "text": "BFS" }, { "code": null, "e": 34484, "s": 34478, "text": "Graph" }, { "code": null, "e": 34490, "s": 34484, "text": "Graph" }, { "code": null, "e": 34494, "s": 34490, "text": "BFS" }, { "code": null, "e": 34592, "s": 34494, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34642, "s": 34592, "text": "Ford-Fulkerson Algorithm for Maximum Flow Problem" }, { "code": null, "e": 34690, "s": 34642, "text": "Traveling Salesman Problem (TSP) Implementation" }, { "code": null, "e": 34761, "s": 34690, "text": "Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8" }, { "code": null, "e": 34796, "s": 34761, "text": "Hamiltonian Cycle | Backtracking-6" }, { "code": null, "e": 34832, "s": 34796, "text": "m Coloring Problem | Backtracking-5" }, { "code": null, "e": 34880, "s": 34832, "text": "Check whether a given graph is Bipartite or not" }, { "code": null, "e": 34946, "s": 34880, "text": "Union-Find Algorithm | Set 2 (Union By Rank and Path Compression)" }, { "code": null, "e": 34983, "s": 34946, "text": "Shortest path in an unweighted graph" }, { "code": null, "e": 35019, "s": 34983, "text": "Best First Search (Informed Search)" } ]
Replace Negative Number by Zeros in Pandas DataFrame - GeeksforGeeks
05 Sep, 2020 In this article, Let’s discuss how to replace the negative numbers by zero in Pandas Approach: Import pandas module. Create a Dataframe. Check the DataFrame element is less than zero, if yes then assign zero in this element. Display the final DataFrame First, let’s create the dataframe. Python3 # importing pandas moduleimport pandas as pd # Creating pandas DataFramedf = pd.DataFrame({"A": [1, 2, -3, 4, -5, 6], "B": [3, -5, -6, 7, 3, -2], "C": [-4, 5, 6, -7, 5, 4], "D": [34, 5, 32, -3, -56, -54]}) # Displaying the original DataFrameprint("Original Array : ")df Output : Now, let’s find the negative element and replace it with zero. Python3 # checking the element is < 0df[df < 0] = 0print("New Array :")df Output : Python pandas-dataFrame Python Pandas-exercise Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Reading and Writing to text files in Python *args and **kwargs in Python Convert integer to string in Python Check if element exists in list in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 26229, "s": 26201, "text": "\n05 Sep, 2020" }, { "code": null, "e": 26315, "s": 26229, "text": "In this article, Let’s discuss how to replace the negative numbers by zero in Pandas " }, { "code": null, "e": 26325, "s": 26315, "text": "Approach:" }, { "code": null, "e": 26347, "s": 26325, "text": "Import pandas module." }, { "code": null, "e": 26367, "s": 26347, "text": "Create a Dataframe." }, { "code": null, "e": 26455, "s": 26367, "text": "Check the DataFrame element is less than zero, if yes then assign zero in this element." }, { "code": null, "e": 26483, "s": 26455, "text": "Display the final DataFrame" }, { "code": null, "e": 26519, "s": 26483, "text": " First, let’s create the dataframe." }, { "code": null, "e": 26527, "s": 26519, "text": "Python3" }, { "code": "# importing pandas moduleimport pandas as pd # Creating pandas DataFramedf = pd.DataFrame({\"A\": [1, 2, -3, 4, -5, 6], \"B\": [3, -5, -6, 7, 3, -2], \"C\": [-4, 5, 6, -7, 5, 4], \"D\": [34, 5, 32, -3, -56, -54]}) # Displaying the original DataFrameprint(\"Original Array : \")df", "e": 26853, "s": 26527, "text": null }, { "code": null, "e": 26862, "s": 26853, "text": "Output :" }, { "code": null, "e": 26925, "s": 26862, "text": "Now, let’s find the negative element and replace it with zero." }, { "code": null, "e": 26933, "s": 26925, "text": "Python3" }, { "code": "# checking the element is < 0df[df < 0] = 0print(\"New Array :\")df", "e": 26999, "s": 26933, "text": null }, { "code": null, "e": 27008, "s": 26999, "text": "Output :" }, { "code": null, "e": 27032, "s": 27008, "text": "Python pandas-dataFrame" }, { "code": null, "e": 27055, "s": 27032, "text": "Python Pandas-exercise" }, { "code": null, "e": 27069, "s": 27055, "text": "Python-pandas" }, { "code": null, "e": 27076, "s": 27069, "text": "Python" }, { "code": null, "e": 27174, "s": 27076, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27192, "s": 27174, "text": "Python Dictionary" }, { "code": null, "e": 27224, "s": 27192, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27246, "s": 27224, "text": "Enumerate() in Python" }, { "code": null, "e": 27288, "s": 27246, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27318, "s": 27288, "text": "Iterate over a list in Python" }, { "code": null, "e": 27362, "s": 27318, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 27391, "s": 27362, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27427, "s": 27391, "text": "Convert integer to string in Python" }, { "code": null, "e": 27469, "s": 27427, "text": "Check if element exists in list in Python" } ]
Portfolio Optimization With NumPy | by Tony Yiu | Towards Data Science
Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details. If you would like to see my code, you can find it on my GitHub here. Last time we talked about how and why portfolio optimizations works: towardsdatascience.com Today, we will dive into the technicalities of actually optimizing a portfolio. The cool think about portfolio optimization is that it can be done purely with matrix algebra, no optimization software needed. Before we start, let’s refresh ourselves on our objective. Quoting my previous post: What we want to make sure of (as much as we can) is that for a specified level of risk, we are investing in a portfolio that maximizes our chances of earning a positive return. The portfolio that does that, a.k.a. the optimal portfolio, is the one with the highest expected return (or in statistical terms, the one with the highest Z-score). For a given level of risk, solve for the weights, W, that:Maximize W.T @ ESubject to: W.T @ Cov @ W = (target risk)^2 and sum(W) = 1Where W is a vector representing the weights of the asset in our portfolio.E is a vector representing the expected returns of the asset.Cov is the covariance matrix of the asset's returns.@ denotes matrix multiplication..T denotes the transpose operation. W @ E is the expected return of the portfolio.The portfolio’s variance is calculated as W.T @ Cov @ W). Variance is the square of the portfolio’s standard deviation (a.k.a. its risk). In our objective function, we want our portfolio’s variance to be equal to the target variance (the square of our target risk level). W @ E is the expected return of the portfolio. The portfolio’s variance is calculated as W.T @ Cov @ W). Variance is the square of the portfolio’s standard deviation (a.k.a. its risk). In our objective function, we want our portfolio’s variance to be equal to the target variance (the square of our target risk level). Minimization problems are often easier to solve than maximization problems so let’s flip our problem around: For a given level of risk, solve for the weights, W, that:Minimize W.T @ Cov @ WSubject to: W.T @ E = target return = mu and sum(W) = 1Where W is a vector representing the weights of the asset in our portfolio.E is a vector representing the expected returns of the asset.Cov is the covariance matrix of the asset's returns.@ denotes matrix multiplication..T denotes the transpose operation. Now instead of maxing return for a given level of variance (a.k.a. the square of risk), we are minimizing variance for a given level of return. To solve this analytically, we can take advantage of the Lagrange Multiplier and rewrite our problem as follows: L(W,h1,h2) = W.T@Cov@W + h1*(W.T@E - mu) + h1*(W.T@ones - 1)ones denotes a vector of ones with the same length as W Notice that we have now a single equation that includes the thing we want to minimize (W.T@Cov@W) as well as our two constraints — that the expected return of the portfolio must equal the target return (W@E — mu) and that the portfolio weights must sum to 1 (W@ones — 1). We can solve this by solving: gradient{L(W,h1,h2)} = 0 This is basically gradient descent, where we want to find the point where the partial derivatives (a.k.a. slope) with respect to each of the variables is zero. When we reach that point, we know we are the minimum. We can solve the previous equation with matrix algebra. First let’s write out each partial derivative: gradient L with respect to W = 2*Cov@W + h1*mu + h2*ones = 0gradient L with respect to h1 = W.T@E - mu = 0gradient L with respect to h2 = W.T@ones - 1 = 0 We can rewrite our system of equations as: 2*Cov@W + h1*mu + h2*ones = 0W.T@E = muW.T@ones = 1 The nice thing about matrices is that they allow us to represent systems of equations like this one easily (and solve them easily). In Python matrix notation, the previous three equations would be: [[2*Cov h1 h2], [[W ], [[0 ], [E.T. 0 0 ], @ [h1], = [mu], [ones.T 0. 0 ]] [h2]] [1 ]] A @ X = b So we can capture our entire problem with three matrices A, X, and b and using the matrix equation A@X=b. Now all we need to do is solve for X, which we can do easily by multiplying b by the inverse of A: X = inverse(A)@bThe first n elements of X are the optimal weights where n is the number of different assets whose weights we are optimizing for. First we start with some returns. I downloaded mine from Shardar via the QUANDL API. My returns data which I stored in a dataframe called final looks like this: S&P 500 Treasury Bonds TIPS Golddate 2020-10-07 0.017407 -0.007293 -0.000080 -0.0004512020-10-08 0.008863 0.005400 0.003977 0.0035552020-10-09 0.008930 -0.000187 0.000317 0.0181612020-10-12 0.016088 0.003186 0.000634 -0.0028722020-10-13 -0.006526 0.007161 0.000000 -0.01572 There are four assets, and I have several years of daily returns for each. We can calculate the inputs we need for our optimization with the following code: # final is a dataframe of daily returns for the assets# I use the historical mean return for my expected returnE = np.array(final.mean(axis=0)).reshape(-1,1)# Calculate the covariance matrix of the asset's returnscov_matrix = np.array(final.cov())# Ones vectorones = np.ones((E.shape[0],1))zeros = np.zeros((2,2)) Next we create the matrixes from our equation (A@X=b): # Put together the A matrixA = 2*cov_matrixA = np.append(A, E.T, axis=0)A = np.append(A, ones.T, axis=0)temp = np.append(E, ones, axis=1)temp = np.append(temp, zeros, axis=0)A = np.append(A, temp, axis=1)# Put together the b vectorb = np.array([[0], [0], [0], [0], E[0], # I set the target return to be [1]]) # the expected return of stocks# So in essense, I am looking for an optimal portfolio# that is expected to give the same return as I get from# investing in stocks (but with lower risk) Here’s what each of them look like: A = 0.000237 -0.000096 -0.000015 0.000004 0.000555 1.0 -0.000096 0.000170 0.000046 0.000038 0.000371 1.0 -0.000015 0.000046 0.000024 0.000022 0.000154 1.0 0.000004 0.000038 0.000022 0.000200 0.000228 1.0 0.000555 0.000371 0.000154 0.000228 0.000000 0.0 1.000000 1.000000 1.000000 1.000000 0.000000 0.0b = 0.000000 0.000000 0.000000 0.000000 0.000555 1.000000# The 0.000555 number in b is the historical daily mean return of # the S&P 500 Finally, we can calculate the optimal weights by inverting matrix A and multiplying it against matrix b: # Optimize using matrix algebrafrom numpy.linalg import invresults = inv(A)@b# Grab first 4 elements of results because those are the weights# Recall that we optimize across 4 assets so there are 4 weightsopt_W = results[:final.shape[1]] Let’s take a look at our optimal weights. The optimal portfolio consists primarily of stocks and bonds with a short to TIPS and a tiny allocation to gold. The analytical solution can only produce unconstrained weights (meaning shorts are allowed). If we want only positive weights, we will have to use gradient descent. These weights were calculated using very naive assumptions and purely historical data. These should definitely not be taken as investment recommendations! Optimal WeightsS&P 500 0.602329Treasury Bonds 0.726293TIPS -0.357301Gold 0.028680 Finally, let’s see if our supposedly optimal portfolio is actually optimal. We should expect the return of our optimal portfolio to be similar to that of stocks (S&P 500) but with less volatility. We can see that our optimal portfolio’s return (the purple line) was both higher and less volatile than that of stocks (the blue line). Bear in mind that this simple analysis is highly biased. The purpose is to show you how portfolio optimization with matrix algebra works. I optimized the portfolio and backtested it over the same timeframe (there was no train-test split), so of course the portfolio will look really good. Once you finish calculating the optimal weights, there’s still more work to do. The portfolio optimization process is notoriously sensitive to small changes in the inputs (especially expected returns). So shocking the optimization inputs (via resampling or even adding some artificial noise) to see how the weights change is a good idea. Finally, it’s good to think about what the optimal portfolio really represents. It’s a portfolio designed to be held for a long time (years). That’s because the data (time series of returns) we use to estimate our inputs need to cover as much time as possible, and ideally multiple business cycles. It’s not a process designed to help you time the market in the short-term. Expected returns and covariance matrices estimated over short timeframes would introduce substantial risk of estimation error — remember, garbage in garbage out. Cheers!
[ { "code": null, "e": 472, "s": 172, "text": "Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details." }, { "code": null, "e": 541, "s": 472, "text": "If you would like to see my code, you can find it on my GitHub here." }, { "code": null, "e": 610, "s": 541, "text": "Last time we talked about how and why portfolio optimizations works:" }, { "code": null, "e": 633, "s": 610, "text": "towardsdatascience.com" }, { "code": null, "e": 841, "s": 633, "text": "Today, we will dive into the technicalities of actually optimizing a portfolio. The cool think about portfolio optimization is that it can be done purely with matrix algebra, no optimization software needed." }, { "code": null, "e": 926, "s": 841, "text": "Before we start, let’s refresh ourselves on our objective. Quoting my previous post:" }, { "code": null, "e": 1268, "s": 926, "text": "What we want to make sure of (as much as we can) is that for a specified level of risk, we are investing in a portfolio that maximizes our chances of earning a positive return. The portfolio that does that, a.k.a. the optimal portfolio, is the one with the highest expected return (or in statistical terms, the one with the highest Z-score)." }, { "code": null, "e": 1659, "s": 1268, "text": "For a given level of risk, solve for the weights, W, that:Maximize W.T @ ESubject to: W.T @ Cov @ W = (target risk)^2 and sum(W) = 1Where W is a vector representing the weights of the asset in our portfolio.E is a vector representing the expected returns of the asset.Cov is the covariance matrix of the asset's returns.@ denotes matrix multiplication..T denotes the transpose operation." }, { "code": null, "e": 1977, "s": 1659, "text": "W @ E is the expected return of the portfolio.The portfolio’s variance is calculated as W.T @ Cov @ W). Variance is the square of the portfolio’s standard deviation (a.k.a. its risk). In our objective function, we want our portfolio’s variance to be equal to the target variance (the square of our target risk level)." }, { "code": null, "e": 2024, "s": 1977, "text": "W @ E is the expected return of the portfolio." }, { "code": null, "e": 2296, "s": 2024, "text": "The portfolio’s variance is calculated as W.T @ Cov @ W). Variance is the square of the portfolio’s standard deviation (a.k.a. its risk). In our objective function, we want our portfolio’s variance to be equal to the target variance (the square of our target risk level)." }, { "code": null, "e": 2405, "s": 2296, "text": "Minimization problems are often easier to solve than maximization problems so let’s flip our problem around:" }, { "code": null, "e": 2798, "s": 2405, "text": "For a given level of risk, solve for the weights, W, that:Minimize W.T @ Cov @ WSubject to: W.T @ E = target return = mu and sum(W) = 1Where W is a vector representing the weights of the asset in our portfolio.E is a vector representing the expected returns of the asset.Cov is the covariance matrix of the asset's returns.@ denotes matrix multiplication..T denotes the transpose operation." }, { "code": null, "e": 2942, "s": 2798, "text": "Now instead of maxing return for a given level of variance (a.k.a. the square of risk), we are minimizing variance for a given level of return." }, { "code": null, "e": 3055, "s": 2942, "text": "To solve this analytically, we can take advantage of the Lagrange Multiplier and rewrite our problem as follows:" }, { "code": null, "e": 3171, "s": 3055, "text": "L(W,h1,h2) = W.T@Cov@W + h1*(W.T@E - mu) + h1*(W.T@ones - 1)ones denotes a vector of ones with the same length as W" }, { "code": null, "e": 3443, "s": 3171, "text": "Notice that we have now a single equation that includes the thing we want to minimize (W.T@Cov@W) as well as our two constraints — that the expected return of the portfolio must equal the target return (W@E — mu) and that the portfolio weights must sum to 1 (W@ones — 1)." }, { "code": null, "e": 3473, "s": 3443, "text": "We can solve this by solving:" }, { "code": null, "e": 3498, "s": 3473, "text": "gradient{L(W,h1,h2)} = 0" }, { "code": null, "e": 3712, "s": 3498, "text": "This is basically gradient descent, where we want to find the point where the partial derivatives (a.k.a. slope) with respect to each of the variables is zero. When we reach that point, we know we are the minimum." }, { "code": null, "e": 3815, "s": 3712, "text": "We can solve the previous equation with matrix algebra. First let’s write out each partial derivative:" }, { "code": null, "e": 3971, "s": 3815, "text": "gradient L with respect to W = 2*Cov@W + h1*mu + h2*ones = 0gradient L with respect to h1 = W.T@E - mu = 0gradient L with respect to h2 = W.T@ones - 1 = 0" }, { "code": null, "e": 4014, "s": 3971, "text": "We can rewrite our system of equations as:" }, { "code": null, "e": 4103, "s": 4014, "text": "2*Cov@W + h1*mu + h2*ones = 0W.T@E = muW.T@ones = 1" }, { "code": null, "e": 4301, "s": 4103, "text": "The nice thing about matrices is that they allow us to represent systems of equations like this one easily (and solve them easily). In Python matrix notation, the previous three equations would be:" }, { "code": null, "e": 4459, "s": 4301, "text": "[[2*Cov h1 h2], [[W ], [[0 ], [E.T. 0 0 ], @ [h1], = [mu], [ones.T 0. 0 ]] [h2]] [1 ]] A @ X = b" }, { "code": null, "e": 4565, "s": 4459, "text": "So we can capture our entire problem with three matrices A, X, and b and using the matrix equation A@X=b." }, { "code": null, "e": 4664, "s": 4565, "text": "Now all we need to do is solve for X, which we can do easily by multiplying b by the inverse of A:" }, { "code": null, "e": 4809, "s": 4664, "text": "X = inverse(A)@bThe first n elements of X are the optimal weights where n is the number of different assets whose weights we are optimizing for." }, { "code": null, "e": 4970, "s": 4809, "text": "First we start with some returns. I downloaded mine from Shardar via the QUANDL API. My returns data which I stored in a dataframe called final looks like this:" }, { "code": null, "e": 5362, "s": 4970, "text": " S&P 500 Treasury Bonds TIPS Golddate 2020-10-07 0.017407 -0.007293 -0.000080 -0.0004512020-10-08 0.008863 0.005400 0.003977 0.0035552020-10-09 0.008930 -0.000187 0.000317 0.0181612020-10-12 0.016088 0.003186 0.000634 -0.0028722020-10-13 -0.006526 0.007161 0.000000 -0.01572" }, { "code": null, "e": 5519, "s": 5362, "text": "There are four assets, and I have several years of daily returns for each. We can calculate the inputs we need for our optimization with the following code:" }, { "code": null, "e": 5833, "s": 5519, "text": "# final is a dataframe of daily returns for the assets# I use the historical mean return for my expected returnE = np.array(final.mean(axis=0)).reshape(-1,1)# Calculate the covariance matrix of the asset's returnscov_matrix = np.array(final.cov())# Ones vectorones = np.ones((E.shape[0],1))zeros = np.zeros((2,2))" }, { "code": null, "e": 5888, "s": 5833, "text": "Next we create the matrixes from our equation (A@X=b):" }, { "code": null, "e": 6449, "s": 5888, "text": "# Put together the A matrixA = 2*cov_matrixA = np.append(A, E.T, axis=0)A = np.append(A, ones.T, axis=0)temp = np.append(E, ones, axis=1)temp = np.append(temp, zeros, axis=0)A = np.append(A, temp, axis=1)# Put together the b vectorb = np.array([[0], [0], [0], [0], E[0], # I set the target return to be [1]]) # the expected return of stocks# So in essense, I am looking for an optimal portfolio# that is expected to give the same return as I get from# investing in stocks (but with lower risk)" }, { "code": null, "e": 6485, "s": 6449, "text": "Here’s what each of them look like:" }, { "code": null, "e": 6963, "s": 6485, "text": "A = 0.000237 -0.000096 -0.000015 0.000004 0.000555 1.0 -0.000096 0.000170 0.000046 0.000038 0.000371 1.0 -0.000015 0.000046 0.000024 0.000022 0.000154 1.0 0.000004 0.000038 0.000022 0.000200 0.000228 1.0 0.000555 0.000371 0.000154 0.000228 0.000000 0.0 1.000000 1.000000 1.000000 1.000000 0.000000 0.0b = 0.000000 0.000000 0.000000 0.000000 0.000555 1.000000# The 0.000555 number in b is the historical daily mean return of # the S&P 500" }, { "code": null, "e": 7068, "s": 6963, "text": "Finally, we can calculate the optimal weights by inverting matrix A and multiplying it against matrix b:" }, { "code": null, "e": 7306, "s": 7068, "text": "# Optimize using matrix algebrafrom numpy.linalg import invresults = inv(A)@b# Grab first 4 elements of results because those are the weights# Recall that we optimize across 4 assets so there are 4 weightsopt_W = results[:final.shape[1]]" }, { "code": null, "e": 7626, "s": 7306, "text": "Let’s take a look at our optimal weights. The optimal portfolio consists primarily of stocks and bonds with a short to TIPS and a tiny allocation to gold. The analytical solution can only produce unconstrained weights (meaning shorts are allowed). If we want only positive weights, we will have to use gradient descent." }, { "code": null, "e": 7781, "s": 7626, "text": "These weights were calculated using very naive assumptions and purely historical data. These should definitely not be taken as investment recommendations!" }, { "code": null, "e": 7937, "s": 7781, "text": " Optimal WeightsS&P 500 0.602329Treasury Bonds 0.726293TIPS -0.357301Gold 0.028680" }, { "code": null, "e": 8270, "s": 7937, "text": "Finally, let’s see if our supposedly optimal portfolio is actually optimal. We should expect the return of our optimal portfolio to be similar to that of stocks (S&P 500) but with less volatility. We can see that our optimal portfolio’s return (the purple line) was both higher and less volatile than that of stocks (the blue line)." }, { "code": null, "e": 8559, "s": 8270, "text": "Bear in mind that this simple analysis is highly biased. The purpose is to show you how portfolio optimization with matrix algebra works. I optimized the portfolio and backtested it over the same timeframe (there was no train-test split), so of course the portfolio will look really good." }, { "code": null, "e": 8761, "s": 8559, "text": "Once you finish calculating the optimal weights, there’s still more work to do. The portfolio optimization process is notoriously sensitive to small changes in the inputs (especially expected returns)." }, { "code": null, "e": 8897, "s": 8761, "text": "So shocking the optimization inputs (via resampling or even adding some artificial noise) to see how the weights change is a good idea." }, { "code": null, "e": 9196, "s": 8897, "text": "Finally, it’s good to think about what the optimal portfolio really represents. It’s a portfolio designed to be held for a long time (years). That’s because the data (time series of returns) we use to estimate our inputs need to cover as much time as possible, and ideally multiple business cycles." } ]
How to use Plotly.js in React to Visualize and Interact with Your Data | by Ran (Reine) | Towards Data Science
I’ve written a tutorial on how to visualize interactive 3D networks (or data) with Python Plotly a few months ago and thought maybe it’ll be a good idea to write another one for Plotly.js. One of the reasons why someone might prefer Plotly.js over Python Plotly could be because of loading speeds — I’ve once written a React + Flask application (where the datasets and Plotly figures are on Flask) and when I compared it to my React + Plotly.js application, interactivity and loading speeds are much better with Plotly.js. So here’s a quick tutorial on how to use Plotly.js with React! ʕ•́ᴥ•̀ʔっ♡ The final codes for this tutorial can be found in this GitHub repository: https://github.com/Reine0017/mini-tutorials/tree/master/React-Tutorials/visualize-data-plotly. Let’s start off with a basic React application. In your desired project directory, run: npx create-react-app . Then run: npm start to bring up the web page. Next, we’ll want to install the Plotly.js library. You can refer to this link for installation instructions. But basically, you’ll want to just run (from their npm package page linked above): npm install react-plotly.js plotly.js Okay now that installation is done, let’s begin writing some codes! There are TONS of different plots, maps and charts that you can play with with Plotly. In this tutorial, we’ll look at how to create a simple helix-shaped interactive 3D scatter plot with Plotly.js. Let’s start off by creating the Plotly component and then importing the react-plotly library. After that, just type in the <Plot/> component like so: Once we import it into our App.js file, Here’s what it brings up: Now, let’s populate the graph with some data. You can check out their official site to see what kinds of visualizations you can create with Plotly too. Since we want to create a Helix 3D graph in this tutorial, we’ll first get the x, y, and z data coordinates for this 3D graph: Next, let’s populate our <Plot/> component with this data. There are way more parameters that you can play with for your desired diagram. But in this case, I only made some minor modifications to it. Here’s the final result: This 3D scatter plot is fully interactive and you can configure certain actions too when a user clicks on it. For demo purposes, I’ll just make it console log its coordinates onClick. To register a user’s clicks (on the coordinate points in the diagram), we can just write something like: onClick={(data) => { console.log(data.points[0])}} inside the <Plot/> component. Here’s the final result: That’s it for today’s tutorial! Hope it was helpful and please feel free to comment or message me if you have any questions at all. Thank you guys for reading this and happy
[ { "code": null, "e": 361, "s": 172, "text": "I’ve written a tutorial on how to visualize interactive 3D networks (or data) with Python Plotly a few months ago and thought maybe it’ll be a good idea to write another one for Plotly.js." }, { "code": null, "e": 695, "s": 361, "text": "One of the reasons why someone might prefer Plotly.js over Python Plotly could be because of loading speeds — I’ve once written a React + Flask application (where the datasets and Plotly figures are on Flask) and when I compared it to my React + Plotly.js application, interactivity and loading speeds are much better with Plotly.js." }, { "code": null, "e": 768, "s": 695, "text": "So here’s a quick tutorial on how to use Plotly.js with React! ʕ•́ᴥ•̀ʔっ♡" }, { "code": null, "e": 937, "s": 768, "text": "The final codes for this tutorial can be found in this GitHub repository: https://github.com/Reine0017/mini-tutorials/tree/master/React-Tutorials/visualize-data-plotly." }, { "code": null, "e": 1025, "s": 937, "text": "Let’s start off with a basic React application. In your desired project directory, run:" }, { "code": null, "e": 1048, "s": 1025, "text": "npx create-react-app ." }, { "code": null, "e": 1058, "s": 1048, "text": "Then run:" }, { "code": null, "e": 1068, "s": 1058, "text": "npm start" }, { "code": null, "e": 1094, "s": 1068, "text": "to bring up the web page." }, { "code": null, "e": 1286, "s": 1094, "text": "Next, we’ll want to install the Plotly.js library. You can refer to this link for installation instructions. But basically, you’ll want to just run (from their npm package page linked above):" }, { "code": null, "e": 1324, "s": 1286, "text": "npm install react-plotly.js plotly.js" }, { "code": null, "e": 1392, "s": 1324, "text": "Okay now that installation is done, let’s begin writing some codes!" }, { "code": null, "e": 1591, "s": 1392, "text": "There are TONS of different plots, maps and charts that you can play with with Plotly. In this tutorial, we’ll look at how to create a simple helix-shaped interactive 3D scatter plot with Plotly.js." }, { "code": null, "e": 1741, "s": 1591, "text": "Let’s start off by creating the Plotly component and then importing the react-plotly library. After that, just type in the <Plot/> component like so:" }, { "code": null, "e": 1781, "s": 1741, "text": "Once we import it into our App.js file," }, { "code": null, "e": 1807, "s": 1781, "text": "Here’s what it brings up:" }, { "code": null, "e": 1959, "s": 1807, "text": "Now, let’s populate the graph with some data. You can check out their official site to see what kinds of visualizations you can create with Plotly too." }, { "code": null, "e": 2086, "s": 1959, "text": "Since we want to create a Helix 3D graph in this tutorial, we’ll first get the x, y, and z data coordinates for this 3D graph:" }, { "code": null, "e": 2145, "s": 2086, "text": "Next, let’s populate our <Plot/> component with this data." }, { "code": null, "e": 2311, "s": 2145, "text": "There are way more parameters that you can play with for your desired diagram. But in this case, I only made some minor modifications to it. Here’s the final result:" }, { "code": null, "e": 2495, "s": 2311, "text": "This 3D scatter plot is fully interactive and you can configure certain actions too when a user clicks on it. For demo purposes, I’ll just make it console log its coordinates onClick." }, { "code": null, "e": 2600, "s": 2495, "text": "To register a user’s clicks (on the coordinate points in the diagram), we can just write something like:" }, { "code": null, "e": 2652, "s": 2600, "text": "onClick={(data) => { console.log(data.points[0])}}" }, { "code": null, "e": 2682, "s": 2652, "text": "inside the <Plot/> component." }, { "code": null, "e": 2707, "s": 2682, "text": "Here’s the final result:" } ]
All About Target Encoding For Classification Tasks | by Nishant Mohan | Towards Data Science
Recently I did a project wherein the target was multi-class. It was a simple prediction task and the dataset involved both categorical as well as numerical features. For those of you who are wondering what multi-class classification is: If you want to answer in ‘0 vs 1’, ‘clicked vs not-clicked’ or ‘cat vs dog’, your classification problem is binary; if you want to answer in ‘red vs green vs blue vs yellow’ or ‘sedan vs hatch vs SUV’, then the problem is multi-class. Therefore, I was researching suitable ways to encode the categorical features. No points for guessing, I was taken to medium articles enumerating benefits of mean target encoding and how it outperforms other methods and how you can use category_encoders library to do the task in just 2 lines of code. However, to my surprise, I found that no article demonstrated this on multi-class target. I went to the documentation of category_encoders and found that it does not say anything about supporting multi-class targets. I dug deeper, scouring through the source code and realized that the library only works for binary or continuous targets. So I thought: “Inside of every problem lies an opportunity.” — Robert Kiposaki Going deep, I went straight for the original paper by Daniele Micci-Barreca that introduced mean target encoding. Not only for regression problem, the paper gives the solution for both binary classification as well as multi-class classification. This is the same paper that category_encoders cites for target encoding as well. While there are several articles explaining target encoding for regression and binary classification problems, my aim is to implement target encoding for multi-class variables. However, before that, we need to understand how it’s done for binary targets. In this article, I cover an overview of the paper that introduced target encoding, and show by example how target encoding works for binary problems. Here is what the paper says for categorical target, in a nutshell: (Skip this section if you wish to understand through an example) One can map every occurrence of a category to the probability estimate of the target attribute. In a classification scenario, the numerical representation corresponds to the posterior probability of the target, conditioned by the value of the categorical attribute. This is effectively a numerical representation of the expected value of the target, given the value of the categorical attribute. In order to avoid overfitting due to a small number of observations in a category, smoothing of the means is also applied. Let’s look at this practically. In binary problem the target is either 0 or 1. Then, the probability estimate for a category within a categorical variable can be given by Empirical Bayesian probability, P(Y=1|X=Xi), i.e. where n(TR) is the total row count, n(Y) is the total row count with 1’s in target, n(i) is the count of rows with i-th category and n(iY) is the count of rows with target 1 in i-th category . Therefore, the fraction in the first term represents probability of 1 in the i-th category, while the fraction in second term represents probability of 1 in overall data. λ is a function which gives monotonic weight which helps when we have a small number of several categories, increasing with n(i) count from 0 to 1. If you have used TargetEncoder from category_encoders library, k is the ‘min_sample_leaf’ parameter, and f is the ‘smoothing’ parameter. Introducing the weighting factor makes sense because when the sample size is large, we should assign more credit to the posterior probability estimate provided by the first term above. However, if the sample size is small, then we replace the probability estimate with the null hypothesis given by the prior probability of the dependent attribute (i.e. mean of all Ys). With this transformation, missing values are handled by treating them as just another variable. The paper extends the same concept to multi-class target as well. We have one new feature for each class of target. Each feature is then effectively a numerical representation of the expected value of exactly one class of target, given the value of the categorical attribute. Of course, the number of inputs can increase significantly if the target has a very high number of classes. However, practically the number of classes is usually small. Read more on this in my next article. In the next section, we look at binary classification situation, with an example. Let’s look at a binary target example. What is the probability of Target being 1 if the category of feature Gender is ‘Male’? It’s 1/2=0.5. Similarly, what is the probability of Target being 1 if the category of feature Gender is ‘Female’? It’s 1/4=0.25. Simple enough? Wait, now if you replace all occurrences of ‘Female’ with 0.25, you risk what is called overfitting. This is because you did not consider that overall probability of 1’s is not 0.5. It’s 4/9=0.4. To account for this fact, we add a weight to this ‘prior’ information, using the formula shown in the previous section. Setting min_sample_leaf, k=1 and smoothing, f=1, for ‘Male’, we have two rows, so n=2; λ(‘Male’)=1/(1+exp(-(2–1)/1))=0.73 # Weight Factor for 'Male' Target Statistic=(Weight Factor * Probability of 1 for Males) + ((1-Weight Factor) * Probability of 1 Overall)S(‘Male’)=(0.73 * 0.5) + ((1–0.73) * 0.4) = 0.485 Similarly, for ‘Female’, we have four rows, so n=4; λ(‘Female’)=1/(1+exp(-(4–1)/1))=0.95 # Weight Factor for 'Female'Target Statistic=(Weight Factor * Probability of 1 for Females) + ((1-Weight Factor) * Probability of 1 Overall)S(‘Female’)=(0.95 * 0.25) + ((1–0.95) * 0.4) = 0.259 If you look closer, you may notice that λ helps giving importance to those categories for which number of rows are more. In our example, there were 4 rows of Gender ‘Female’, as opposed to only 2 rows of Gender ‘Male’. The corresponding Weight Factor were 0.95 and 0.73. Thus, replace all occurrences of ‘Male’ with 0.485 and ‘Female’ with 0.259. Value for ‘Other’ can be calculated in a similar fashion. Congratulations! You just implemented target encoding. Don’t trust me? Check for yourself by running this code, which does the same using your favorite category_encoders library: !pip install category_encodersimport category_encoders as cex=['Male','Male','Female','Female','Female','Female','Other','Other','Other']y=[1,0,0,0,0,1,1,1,0]print(ce.TargetEncoder().fit_transform(x,y)) In this article, I introduced a shortcoming of the TargetEncoder class of category_encoders library. I explained and summarized the paper that introduced target encoding. I explained through an example how the categories can be replaced with a numerical value. My next article will focus completely on how we can do the same for multi-class targets. Stay tuned! Edit: Published the next one, demonstrating and implementing multi-class target encoding here. Connect with me on LinkedIn Check out some of my interesting projects on GitHub
[ { "code": null, "e": 337, "s": 171, "text": "Recently I did a project wherein the target was multi-class. It was a simple prediction task and the dataset involved both categorical as well as numerical features." }, { "code": null, "e": 643, "s": 337, "text": "For those of you who are wondering what multi-class classification is: If you want to answer in ‘0 vs 1’, ‘clicked vs not-clicked’ or ‘cat vs dog’, your classification problem is binary; if you want to answer in ‘red vs green vs blue vs yellow’ or ‘sedan vs hatch vs SUV’, then the problem is multi-class." }, { "code": null, "e": 1284, "s": 643, "text": "Therefore, I was researching suitable ways to encode the categorical features. No points for guessing, I was taken to medium articles enumerating benefits of mean target encoding and how it outperforms other methods and how you can use category_encoders library to do the task in just 2 lines of code. However, to my surprise, I found that no article demonstrated this on multi-class target. I went to the documentation of category_encoders and found that it does not say anything about supporting multi-class targets. I dug deeper, scouring through the source code and realized that the library only works for binary or continuous targets." }, { "code": null, "e": 1363, "s": 1284, "text": "So I thought: “Inside of every problem lies an opportunity.” — Robert Kiposaki" }, { "code": null, "e": 1690, "s": 1363, "text": "Going deep, I went straight for the original paper by Daniele Micci-Barreca that introduced mean target encoding. Not only for regression problem, the paper gives the solution for both binary classification as well as multi-class classification. This is the same paper that category_encoders cites for target encoding as well." }, { "code": null, "e": 2095, "s": 1690, "text": "While there are several articles explaining target encoding for regression and binary classification problems, my aim is to implement target encoding for multi-class variables. However, before that, we need to understand how it’s done for binary targets. In this article, I cover an overview of the paper that introduced target encoding, and show by example how target encoding works for binary problems." }, { "code": null, "e": 2162, "s": 2095, "text": "Here is what the paper says for categorical target, in a nutshell:" }, { "code": null, "e": 2227, "s": 2162, "text": "(Skip this section if you wish to understand through an example)" }, { "code": null, "e": 2746, "s": 2227, "text": "One can map every occurrence of a category to the probability estimate of the target attribute. In a classification scenario, the numerical representation corresponds to the posterior probability of the target, conditioned by the value of the categorical attribute. This is effectively a numerical representation of the expected value of the target, given the value of the categorical attribute. In order to avoid overfitting due to a small number of observations in a category, smoothing of the means is also applied." }, { "code": null, "e": 2967, "s": 2746, "text": "Let’s look at this practically. In binary problem the target is either 0 or 1. Then, the probability estimate for a category within a categorical variable can be given by Empirical Bayesian probability, P(Y=1|X=Xi), i.e." }, { "code": null, "e": 3479, "s": 2967, "text": "where n(TR) is the total row count, n(Y) is the total row count with 1’s in target, n(i) is the count of rows with i-th category and n(iY) is the count of rows with target 1 in i-th category . Therefore, the fraction in the first term represents probability of 1 in the i-th category, while the fraction in second term represents probability of 1 in overall data. λ is a function which gives monotonic weight which helps when we have a small number of several categories, increasing with n(i) count from 0 to 1." }, { "code": null, "e": 3616, "s": 3479, "text": "If you have used TargetEncoder from category_encoders library, k is the ‘min_sample_leaf’ parameter, and f is the ‘smoothing’ parameter." }, { "code": null, "e": 4082, "s": 3616, "text": "Introducing the weighting factor makes sense because when the sample size is large, we should assign more credit to the posterior probability estimate provided by the first term above. However, if the sample size is small, then we replace the probability estimate with the null hypothesis given by the prior probability of the dependent attribute (i.e. mean of all Ys). With this transformation, missing values are handled by treating them as just another variable." }, { "code": null, "e": 4565, "s": 4082, "text": "The paper extends the same concept to multi-class target as well. We have one new feature for each class of target. Each feature is then effectively a numerical representation of the expected value of exactly one class of target, given the value of the categorical attribute. Of course, the number of inputs can increase significantly if the target has a very high number of classes. However, practically the number of classes is usually small. Read more on this in my next article." }, { "code": null, "e": 4647, "s": 4565, "text": "In the next section, we look at binary classification situation, with an example." }, { "code": null, "e": 4686, "s": 4647, "text": "Let’s look at a binary target example." }, { "code": null, "e": 4773, "s": 4686, "text": "What is the probability of Target being 1 if the category of feature Gender is ‘Male’?" }, { "code": null, "e": 4787, "s": 4773, "text": "It’s 1/2=0.5." }, { "code": null, "e": 4887, "s": 4787, "text": "Similarly, what is the probability of Target being 1 if the category of feature Gender is ‘Female’?" }, { "code": null, "e": 4902, "s": 4887, "text": "It’s 1/4=0.25." }, { "code": null, "e": 4917, "s": 4902, "text": "Simple enough?" }, { "code": null, "e": 5113, "s": 4917, "text": "Wait, now if you replace all occurrences of ‘Female’ with 0.25, you risk what is called overfitting. This is because you did not consider that overall probability of 1’s is not 0.5. It’s 4/9=0.4." }, { "code": null, "e": 5233, "s": 5113, "text": "To account for this fact, we add a weight to this ‘prior’ information, using the formula shown in the previous section." }, { "code": null, "e": 5282, "s": 5233, "text": "Setting min_sample_leaf, k=1 and smoothing, f=1," }, { "code": null, "e": 5320, "s": 5282, "text": "for ‘Male’, we have two rows, so n=2;" }, { "code": null, "e": 5563, "s": 5320, "text": "λ(‘Male’)=1/(1+exp(-(2–1)/1))=0.73 # Weight Factor for 'Male' Target Statistic=(Weight Factor * Probability of 1 for Males) + ((1-Weight Factor) * Probability of 1 Overall)S(‘Male’)=(0.73 * 0.5) + ((1–0.73) * 0.4) = 0.485" }, { "code": null, "e": 5615, "s": 5563, "text": "Similarly, for ‘Female’, we have four rows, so n=4;" }, { "code": null, "e": 5865, "s": 5615, "text": "λ(‘Female’)=1/(1+exp(-(4–1)/1))=0.95 # Weight Factor for 'Female'Target Statistic=(Weight Factor * Probability of 1 for Females) + ((1-Weight Factor) * Probability of 1 Overall)S(‘Female’)=(0.95 * 0.25) + ((1–0.95) * 0.4) = 0.259" }, { "code": null, "e": 6136, "s": 5865, "text": "If you look closer, you may notice that λ helps giving importance to those categories for which number of rows are more. In our example, there were 4 rows of Gender ‘Female’, as opposed to only 2 rows of Gender ‘Male’. The corresponding Weight Factor were 0.95 and 0.73." }, { "code": null, "e": 6270, "s": 6136, "text": "Thus, replace all occurrences of ‘Male’ with 0.485 and ‘Female’ with 0.259. Value for ‘Other’ can be calculated in a similar fashion." }, { "code": null, "e": 6325, "s": 6270, "text": "Congratulations! You just implemented target encoding." }, { "code": null, "e": 6341, "s": 6325, "text": "Don’t trust me?" }, { "code": null, "e": 6449, "s": 6341, "text": "Check for yourself by running this code, which does the same using your favorite category_encoders library:" }, { "code": null, "e": 6652, "s": 6449, "text": "!pip install category_encodersimport category_encoders as cex=['Male','Male','Female','Female','Female','Female','Other','Other','Other']y=[1,0,0,0,0,1,1,1,0]print(ce.TargetEncoder().fit_transform(x,y))" }, { "code": null, "e": 6913, "s": 6652, "text": "In this article, I introduced a shortcoming of the TargetEncoder class of category_encoders library. I explained and summarized the paper that introduced target encoding. I explained through an example how the categories can be replaced with a numerical value." }, { "code": null, "e": 7014, "s": 6913, "text": "My next article will focus completely on how we can do the same for multi-class targets. Stay tuned!" }, { "code": null, "e": 7109, "s": 7014, "text": "Edit: Published the next one, demonstrating and implementing multi-class target encoding here." }, { "code": null, "e": 7137, "s": 7109, "text": "Connect with me on LinkedIn" } ]
How to create a database in MongoDB using Java?
There is no separate method to create a MongoDB database in Java, you can create a database by invoking the getDatabase() method of the com.mongodb.MongoClient class. import com.mongodb.MongoClient; public class CreatingDatabase { public static void main( String args[] ) { //Creating a MongoDB client @SuppressWarnings("resource") MongoClient mongo = new MongoClient( "localhost" , 27017 ); //Accessing the database mongo.getDatabase("myDatabase1"); mongo.getDatabase("myDatabase2"); mongo.getDatabase("myDatabase3"); System.out.println("Databases created successfully"); } } Databases created successfully
[ { "code": null, "e": 1229, "s": 1062, "text": "There is no separate method to create a MongoDB database in Java, you can create a database by invoking the getDatabase() method of the com.mongodb.MongoClient class." }, { "code": null, "e": 1693, "s": 1229, "text": "import com.mongodb.MongoClient;\npublic class CreatingDatabase {\n public static void main( String args[] ) {\n //Creating a MongoDB client\n @SuppressWarnings(\"resource\")\n MongoClient mongo = new MongoClient( \"localhost\" , 27017 );\n //Accessing the database\n mongo.getDatabase(\"myDatabase1\");\n mongo.getDatabase(\"myDatabase2\");\n mongo.getDatabase(\"myDatabase3\");\n System.out.println(\"Databases created successfully\");\n }\n}" }, { "code": null, "e": 1724, "s": 1693, "text": "Databases created successfully" } ]
Topic Modeling on PyCaret. A beginner’s guide to PyCaret’s natural... | by Ednalyn C. De Dios | Towards Data Science
I remember a brief conversation with my boss’ boss a while back. He said that he wouldn’t be impressed if somebody in the company built a face recognition tool from scratch because, and I quote, “Guess what? There’s an API for that.” He then goes on about the futility of doing something that’s already been done instead of just using it. This gave me an insight into how an executive thinks. Not that they don’t care about the coolness factor of a project, but at the end of that day, they’re most concerned about how a project will add value to the business and even more importantly, how quickly it can be done. In the real world, the time it takes to build prototype matters. And the quicker we get from data to insights, the better off we will be. These help us stay agile. And this brings me to PyCaret. PyCaret is an open source, low-code machine learning library in Python that allows you to go from preparing your data to deploying your model within seconds in your choice of notebook environment. Pycaret is basically a wrapper for some of the most popular machine learning libraries and frameworks scikit-learn and spaCy. Here are the things that PyCaret can do: Classification Regression Clustering Anomaly Detection Natural Language Processing Associate Rule Mining If you’re interested in reading about the difference between traditional NLP approach vs. PyCaret’s NLP module, check out Prateek Baghel’s article: towardsdatascience.com In just a few lines of code, PyCaret makes natural language processing so easy that it’s almost criminal. Like most of its other modules, PyCaret’s NLP module streamlined pipeline cuts the time from data to insights in more than half the time. For example, with only one line, it performs text processing automatically, with the ability to customize stop words. Add another line or two, and you got yourself a language model. With yet another line, it gives you a properly formatted plotly graph. And finally, adding another line gives you the option to evaluate the model. You can even tune the model with, guess what, one line of code! Instead of just telling you all about the wonderful features of PyCaret, maybe it’s be better if we do a little show and tell instead. For this post, we’ll create an NLP pipeline that involves the following 6 glorious steps: Getting the DataSetting up the EnvironmentCreating the ModelAssigning the ModelPlotting the ModelEvaluating the Model Getting the Data Setting up the Environment Creating the Model Assigning the Model Plotting the Model Evaluating the Model We will be going through an end-to-end demonstration of this pipeline with a brief explanation of the functions involved and their parameters. Let’s get started. Let us begin by installing PyCaret. If this is your first time installing it, just type the following into your terminal: pip install pycaret However, if you have a previously installed version of PyCaret, you can upgrade using the following command: pip install —-upgrade pycaret Beware: PyCaret is a big library so it’s going to take a few minutes to download and install. We’ll also need to download the English language model because it is not included in the PyCaret installation. python -m spacy download en_core_web_smpython -m textblob.download_corpora Next, let’s fire up a Jupyter notebook and import PyCaret’s NLP module: Importing the pycaret.nlp automatically sets up your environment to perform NLP tasks only. Before setup, we need to decide first how we’re going to ingest data. There are two methods of getting the data into the pipeline. One is by using a Pandas dataframe and another is by using a simple list of textual data. Above, we’re simply loading the data into a dataframe. Above, we’re opening the file 'list.txt' and reading it. We assign the resulting list into the lines. From the rest of this experiment, we’ll just use a dataframe to pass textual data to thesetup() function of the NLP module. And for the sake of expediency, we’ll sample the dataframe to only select a thousand tweets. Let’s take a quick look at our dataframe with df.head() and df.shape. In the line below, we’ll initialize the setup by calling the setup() function and assign it to nlp. With data and target, we’re telling PyCaret that we’d like to use the values in the 'text' column of df. Also, we’re setting the session_id to an arbitrary number of 493 so that we can reproduce the experiment over and over again and get the same result. Finally, we added custom_stopwords so that PyCaret will exclude the specified list of words in the analysis. Note that if we want to use a list instead, we could replace df with lines and get rid of target = ‘text’ because a list has no columns for the PyCaret to target! Here’s the output of nlp: The output table above confirms our session id, number of documents (rows or records), and vocabulary size. It also shows up if we used custom stopwords or not. Below, we’ll create the model by calling the create_model() function and assign it to lda. The function already knows to use the dataset that we specified during setup(). In our case, the PyCaret knows we want to create a model based on the 'text' in df. In the line above, notice that w param used 'lda' as the parameter. LDA stands for Latent Dirichlet Allocation. We could’ve just as easily opted for other types of models. Here’s the list of models that PyCaret currently supports: ‘lda’: Latent Dirichlet Allocation ‘lsi’: Latent Semantic Indexing ‘hdp’: Hierarchical Dirichlet Process ‘rp’: Random Projections ‘nmf’: Non-Negative Matrix Factorization I encourage you to research the difference between the models above, To start, check out Lettier’s awesome guide on LDA. medium.com The next parameter we used is num_topics = 6. This tells PyCaret to use six topics in the results ranging from 0 to 5. If num_topic is not set, the default number is 4. Lastly, we set multi_core to tell PyCaret to use all available CPUs for parallel processing. This saves a lot of computational time. By calling assign_model(), we’re going to label our data so that we’ll get a dataframe (based on our original dataframe: df) with additional columns that include the following information: Topic percent value for each topic The dominant topic The percent value of the dominant topic Let’s take a look at df_lda. Calling the plot_model() function will give us some visualization about frequency, distribution, polarity, et cetera. The plot_model() function takes three parameters: model, plot, and topic_num. The model instructs PyCaret what model to use and must be preceded by a create_model() function. topic_num designates which topic number (from 0 to 5) will the visualization be based on. PyCarets offers a variety of plots. The type of graph generated will depend on the plot parameter. Here is the list of currently available visualizations: ‘frequency’: Word Token Frequency (default) ‘distribution’: Word Distribution Plot ‘bigram’: Bigram Frequency Plot ‘trigram’: Trigram Frequency Plot ‘sentiment’: Sentiment Polarity Plot ‘pos’: Part of Speech Frequency ‘tsne’: t-SNE (3d) Dimension Plot ‘topic_model’ : Topic Model (pyLDAvis) ‘topic_distribution’ : Topic Infer Distribution ‘wordcloud’: Word cloud ‘umap’: UMAP Dimensionality Plot Evaluating the models involves calling the evaluate_model() function. It takes only one parameter: the model to be used. In our case, the model is stored is lda that was created with the create_model() function in an earlier step. The function returns a visual user interface for plotting. And voilà, we’re done! Using PyCaret’s NLP module, we were able to quickly from getting the data to evaluating the model in just a few lines of code. We covered the functions involved in each step and examined the parameters of those functions. Thank you for reading! PyCaret’s NLP module has a lot more features and I encourage you to read their documentation to further familiarize yourself with the module and maybe even the whole library! In the next post, I’ll continue to explore PyCaret’s functionalities. If you want to learn more about my journey from slacker to data scientist, check out the article below: towardsdatascience.com Stay tuned! You can reach me on Twitter or LinkedIn. [1] PyCaret. (June 4, 2020). Why PyCaret. https://pycaret.org/
[ { "code": null, "e": 510, "s": 171, "text": "I remember a brief conversation with my boss’ boss a while back. He said that he wouldn’t be impressed if somebody in the company built a face recognition tool from scratch because, and I quote, “Guess what? There’s an API for that.” He then goes on about the futility of doing something that’s already been done instead of just using it." }, { "code": null, "e": 786, "s": 510, "text": "This gave me an insight into how an executive thinks. Not that they don’t care about the coolness factor of a project, but at the end of that day, they’re most concerned about how a project will add value to the business and even more importantly, how quickly it can be done." }, { "code": null, "e": 950, "s": 786, "text": "In the real world, the time it takes to build prototype matters. And the quicker we get from data to insights, the better off we will be. These help us stay agile." }, { "code": null, "e": 981, "s": 950, "text": "And this brings me to PyCaret." }, { "code": null, "e": 1178, "s": 981, "text": "PyCaret is an open source, low-code machine learning library in Python that allows you to go from preparing your data to deploying your model within seconds in your choice of notebook environment." }, { "code": null, "e": 1345, "s": 1178, "text": "Pycaret is basically a wrapper for some of the most popular machine learning libraries and frameworks scikit-learn and spaCy. Here are the things that PyCaret can do:" }, { "code": null, "e": 1360, "s": 1345, "text": "Classification" }, { "code": null, "e": 1371, "s": 1360, "text": "Regression" }, { "code": null, "e": 1382, "s": 1371, "text": "Clustering" }, { "code": null, "e": 1400, "s": 1382, "text": "Anomaly Detection" }, { "code": null, "e": 1428, "s": 1400, "text": "Natural Language Processing" }, { "code": null, "e": 1450, "s": 1428, "text": "Associate Rule Mining" }, { "code": null, "e": 1598, "s": 1450, "text": "If you’re interested in reading about the difference between traditional NLP approach vs. PyCaret’s NLP module, check out Prateek Baghel’s article:" }, { "code": null, "e": 1621, "s": 1598, "text": "towardsdatascience.com" }, { "code": null, "e": 1865, "s": 1621, "text": "In just a few lines of code, PyCaret makes natural language processing so easy that it’s almost criminal. Like most of its other modules, PyCaret’s NLP module streamlined pipeline cuts the time from data to insights in more than half the time." }, { "code": null, "e": 2259, "s": 1865, "text": "For example, with only one line, it performs text processing automatically, with the ability to customize stop words. Add another line or two, and you got yourself a language model. With yet another line, it gives you a properly formatted plotly graph. And finally, adding another line gives you the option to evaluate the model. You can even tune the model with, guess what, one line of code!" }, { "code": null, "e": 2394, "s": 2259, "text": "Instead of just telling you all about the wonderful features of PyCaret, maybe it’s be better if we do a little show and tell instead." }, { "code": null, "e": 2484, "s": 2394, "text": "For this post, we’ll create an NLP pipeline that involves the following 6 glorious steps:" }, { "code": null, "e": 2602, "s": 2484, "text": "Getting the DataSetting up the EnvironmentCreating the ModelAssigning the ModelPlotting the ModelEvaluating the Model" }, { "code": null, "e": 2619, "s": 2602, "text": "Getting the Data" }, { "code": null, "e": 2646, "s": 2619, "text": "Setting up the Environment" }, { "code": null, "e": 2665, "s": 2646, "text": "Creating the Model" }, { "code": null, "e": 2685, "s": 2665, "text": "Assigning the Model" }, { "code": null, "e": 2704, "s": 2685, "text": "Plotting the Model" }, { "code": null, "e": 2725, "s": 2704, "text": "Evaluating the Model" }, { "code": null, "e": 2868, "s": 2725, "text": "We will be going through an end-to-end demonstration of this pipeline with a brief explanation of the functions involved and their parameters." }, { "code": null, "e": 2887, "s": 2868, "text": "Let’s get started." }, { "code": null, "e": 3009, "s": 2887, "text": "Let us begin by installing PyCaret. If this is your first time installing it, just type the following into your terminal:" }, { "code": null, "e": 3029, "s": 3009, "text": "pip install pycaret" }, { "code": null, "e": 3138, "s": 3029, "text": "However, if you have a previously installed version of PyCaret, you can upgrade using the following command:" }, { "code": null, "e": 3168, "s": 3138, "text": "pip install —-upgrade pycaret" }, { "code": null, "e": 3262, "s": 3168, "text": "Beware: PyCaret is a big library so it’s going to take a few minutes to download and install." }, { "code": null, "e": 3373, "s": 3262, "text": "We’ll also need to download the English language model because it is not included in the PyCaret installation." }, { "code": null, "e": 3448, "s": 3373, "text": "python -m spacy download en_core_web_smpython -m textblob.download_corpora" }, { "code": null, "e": 3520, "s": 3448, "text": "Next, let’s fire up a Jupyter notebook and import PyCaret’s NLP module:" }, { "code": null, "e": 3612, "s": 3520, "text": "Importing the pycaret.nlp automatically sets up your environment to perform NLP tasks only." }, { "code": null, "e": 3833, "s": 3612, "text": "Before setup, we need to decide first how we’re going to ingest data. There are two methods of getting the data into the pipeline. One is by using a Pandas dataframe and another is by using a simple list of textual data." }, { "code": null, "e": 3888, "s": 3833, "text": "Above, we’re simply loading the data into a dataframe." }, { "code": null, "e": 3990, "s": 3888, "text": "Above, we’re opening the file 'list.txt' and reading it. We assign the resulting list into the lines." }, { "code": null, "e": 4207, "s": 3990, "text": "From the rest of this experiment, we’ll just use a dataframe to pass textual data to thesetup() function of the NLP module. And for the sake of expediency, we’ll sample the dataframe to only select a thousand tweets." }, { "code": null, "e": 4277, "s": 4207, "text": "Let’s take a quick look at our dataframe with df.head() and df.shape." }, { "code": null, "e": 4377, "s": 4277, "text": "In the line below, we’ll initialize the setup by calling the setup() function and assign it to nlp." }, { "code": null, "e": 4741, "s": 4377, "text": "With data and target, we’re telling PyCaret that we’d like to use the values in the 'text' column of df. Also, we’re setting the session_id to an arbitrary number of 493 so that we can reproduce the experiment over and over again and get the same result. Finally, we added custom_stopwords so that PyCaret will exclude the specified list of words in the analysis." }, { "code": null, "e": 4904, "s": 4741, "text": "Note that if we want to use a list instead, we could replace df with lines and get rid of target = ‘text’ because a list has no columns for the PyCaret to target!" }, { "code": null, "e": 4930, "s": 4904, "text": "Here’s the output of nlp:" }, { "code": null, "e": 5091, "s": 4930, "text": "The output table above confirms our session id, number of documents (rows or records), and vocabulary size. It also shows up if we used custom stopwords or not." }, { "code": null, "e": 5346, "s": 5091, "text": "Below, we’ll create the model by calling the create_model() function and assign it to lda. The function already knows to use the dataset that we specified during setup(). In our case, the PyCaret knows we want to create a model based on the 'text' in df." }, { "code": null, "e": 5518, "s": 5346, "text": "In the line above, notice that w param used 'lda' as the parameter. LDA stands for Latent Dirichlet Allocation. We could’ve just as easily opted for other types of models." }, { "code": null, "e": 5577, "s": 5518, "text": "Here’s the list of models that PyCaret currently supports:" }, { "code": null, "e": 5612, "s": 5577, "text": "‘lda’: Latent Dirichlet Allocation" }, { "code": null, "e": 5644, "s": 5612, "text": "‘lsi’: Latent Semantic Indexing" }, { "code": null, "e": 5682, "s": 5644, "text": "‘hdp’: Hierarchical Dirichlet Process" }, { "code": null, "e": 5707, "s": 5682, "text": "‘rp’: Random Projections" }, { "code": null, "e": 5748, "s": 5707, "text": "‘nmf’: Non-Negative Matrix Factorization" }, { "code": null, "e": 5869, "s": 5748, "text": "I encourage you to research the difference between the models above, To start, check out Lettier’s awesome guide on LDA." }, { "code": null, "e": 5880, "s": 5869, "text": "medium.com" }, { "code": null, "e": 6182, "s": 5880, "text": "The next parameter we used is num_topics = 6. This tells PyCaret to use six topics in the results ranging from 0 to 5. If num_topic is not set, the default number is 4. Lastly, we set multi_core to tell PyCaret to use all available CPUs for parallel processing. This saves a lot of computational time." }, { "code": null, "e": 6371, "s": 6182, "text": "By calling assign_model(), we’re going to label our data so that we’ll get a dataframe (based on our original dataframe: df) with additional columns that include the following information:" }, { "code": null, "e": 6406, "s": 6371, "text": "Topic percent value for each topic" }, { "code": null, "e": 6425, "s": 6406, "text": "The dominant topic" }, { "code": null, "e": 6465, "s": 6425, "text": "The percent value of the dominant topic" }, { "code": null, "e": 6494, "s": 6465, "text": "Let’s take a look at df_lda." }, { "code": null, "e": 6877, "s": 6494, "text": "Calling the plot_model() function will give us some visualization about frequency, distribution, polarity, et cetera. The plot_model() function takes three parameters: model, plot, and topic_num. The model instructs PyCaret what model to use and must be preceded by a create_model() function. topic_num designates which topic number (from 0 to 5) will the visualization be based on." }, { "code": null, "e": 7032, "s": 6877, "text": "PyCarets offers a variety of plots. The type of graph generated will depend on the plot parameter. Here is the list of currently available visualizations:" }, { "code": null, "e": 7076, "s": 7032, "text": "‘frequency’: Word Token Frequency (default)" }, { "code": null, "e": 7115, "s": 7076, "text": "‘distribution’: Word Distribution Plot" }, { "code": null, "e": 7147, "s": 7115, "text": "‘bigram’: Bigram Frequency Plot" }, { "code": null, "e": 7181, "s": 7147, "text": "‘trigram’: Trigram Frequency Plot" }, { "code": null, "e": 7218, "s": 7181, "text": "‘sentiment’: Sentiment Polarity Plot" }, { "code": null, "e": 7250, "s": 7218, "text": "‘pos’: Part of Speech Frequency" }, { "code": null, "e": 7284, "s": 7250, "text": "‘tsne’: t-SNE (3d) Dimension Plot" }, { "code": null, "e": 7323, "s": 7284, "text": "‘topic_model’ : Topic Model (pyLDAvis)" }, { "code": null, "e": 7371, "s": 7323, "text": "‘topic_distribution’ : Topic Infer Distribution" }, { "code": null, "e": 7395, "s": 7371, "text": "‘wordcloud’: Word cloud" }, { "code": null, "e": 7428, "s": 7395, "text": "‘umap’: UMAP Dimensionality Plot" }, { "code": null, "e": 7659, "s": 7428, "text": "Evaluating the models involves calling the evaluate_model() function. It takes only one parameter: the model to be used. In our case, the model is stored is lda that was created with the create_model() function in an earlier step." }, { "code": null, "e": 7718, "s": 7659, "text": "The function returns a visual user interface for plotting." }, { "code": null, "e": 7742, "s": 7718, "text": "And voilà, we’re done!" }, { "code": null, "e": 7964, "s": 7742, "text": "Using PyCaret’s NLP module, we were able to quickly from getting the data to evaluating the model in just a few lines of code. We covered the functions involved in each step and examined the parameters of those functions." }, { "code": null, "e": 8162, "s": 7964, "text": "Thank you for reading! PyCaret’s NLP module has a lot more features and I encourage you to read their documentation to further familiarize yourself with the module and maybe even the whole library!" }, { "code": null, "e": 8232, "s": 8162, "text": "In the next post, I’ll continue to explore PyCaret’s functionalities." }, { "code": null, "e": 8336, "s": 8232, "text": "If you want to learn more about my journey from slacker to data scientist, check out the article below:" }, { "code": null, "e": 8359, "s": 8336, "text": "towardsdatascience.com" }, { "code": null, "e": 8371, "s": 8359, "text": "Stay tuned!" }, { "code": null, "e": 8412, "s": 8371, "text": "You can reach me on Twitter or LinkedIn." } ]
Angle between hour and minute hand | Practice | GeeksforGeeks
Calculate the angle between the hour hand and minute hand. Note: There can be two angles between hands; we need to print a minimum of two. Also, we need to print the floor of the final result angle. For example, if the final angle is 10.61, we need to print 10. Example 1: Input: H = 9 , M = 0 Output: 90 Explanation: The minimum angle between hour and minute hand when the time is 9 is 90 degress. Example 2: Input: H = 3 , M = 30 Output: 75 Explanation: The minimum angle between hour and minute hand when the time is 3:30 is 75 degress. Your Task: You don't need to read, input, or print anything. Your task is to complete the function getAngle(), which takes 2 Integers H and M as input and returns the answer. Expected Time Complexity: O(1) Expected Auxiliary Space: O(1) Constraints: 1 ≤ H ≤ 12 0 ≤ M < 60 H and M are Integers 0 harshilrpanchal19982 weeks ago complete java solution class Solution { static int getAngle(int H , int M) { // code here float a = (float) Math.abs(6*(5*H-M) + 0.5*M); if (a > 180){ return (int) (360- a); } return (int) a; }}; enjoy!!!!! 0 mayank20212 months ago C++ int getAngle(int H , int M) { if (abs(H*30 - M*6 + M*6/12.0) > 180 ) return 360-abs(H*30 - M*6 + M*6/12.0); else return abs(H*30 - M*6 + M*6/12.0); } 0 tharabhai2 months ago C++ solution: int getAngle(int H , int M) { //hr is the angle covered by hr hand float hr = ((H*60+M)*0.5); //mi is the angle covered by minute hand float mi = (M*6); //absolute difference b/w them hr = abs(hr-mi); //checking which side of the circle is smaller hr = hr>(360-hr)?360-hr:hr; //floor of that value as asked for int ans = floor(hr); return ans; } Drop suggestions if any :) 0 taiphanvan24032 months ago int getAngle(int H , int M) { float a=abs(6*(5*H-M)+0.5*M); if(a>180) return 360-a; return a; } 0 ramyan18143 months ago class Solution { public: int getAngle(int H , int M) { float ans=abs(30*H+0.5*M-6*M); return (int)(ans<=180?ans:360-ans); 0 hasanshaikh19990 This comment was deleted. +2 Deyyala Srinivas Kumar8 months ago Deyyala Srinivas Kumar spoilerint getAngle(int H , int M) { // code here int a= abs(((60*H)-(11*M))/2); if((((60*H)-(11*M))%2)==0) return min(a,360-a); else return min(a,359-a); } 0 Aditya Raj Singh Gour8 months ago Aditya Raj Singh Gour Example is wrong !For H = 9 and M = 0 correct answer is 90 0 Aayush Kumar9 months ago Aayush Kumar Is 12:60 equal to 12:00 or 1:00? There's a problem with this question. 0 Ayush9 months ago Ayush How the angle between minute and hour hand at 9:60 which mean 10 is 90 degree, ideally isn't it should have to be 60 degree? 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": 298, "s": 238, "text": "Calculate the angle between the hour hand and minute hand. " }, { "code": null, "e": 501, "s": 298, "text": "Note: There can be two angles between hands; we need to print a minimum of two. Also, we need to print the floor of the final result angle. For example, if the final angle is 10.61, we need to print 10." }, { "code": null, "e": 513, "s": 501, "text": "\nExample 1:" }, { "code": null, "e": 639, "s": 513, "text": "Input:\nH = 9 , M = 0\nOutput:\n90\nExplanation:\nThe minimum angle between hour and minute\nhand when the time is 9 is 90 degress." }, { "code": null, "e": 650, "s": 639, "text": "Example 2:" }, { "code": null, "e": 780, "s": 650, "text": "Input:\nH = 3 , M = 30\nOutput:\n75\nExplanation:\nThe minimum angle between hour and minute\nhand when the time is 3:30 is 75 degress." }, { "code": null, "e": 956, "s": 780, "text": "\nYour Task:\nYou don't need to read, input, or print anything. Your task is to complete the function getAngle(), which takes 2 Integers H and M as input and returns the answer." }, { "code": null, "e": 1019, "s": 956, "text": "\nExpected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 1076, "s": 1019, "text": "\nConstraints:\n1 ≤ H ≤ 12\n0 ≤ M < 60\nH and M are Integers" }, { "code": null, "e": 1078, "s": 1076, "text": "0" }, { "code": null, "e": 1109, "s": 1078, "text": "harshilrpanchal19982 weeks ago" }, { "code": null, "e": 1132, "s": 1109, "text": "complete java solution" }, { "code": null, "e": 1350, "s": 1134, "text": "class Solution { static int getAngle(int H , int M) { // code here float a = (float) Math.abs(6*(5*H-M) + 0.5*M); if (a > 180){ return (int) (360- a); } return (int) a; }};" }, { "code": null, "e": 1363, "s": 1352, "text": "enjoy!!!!!" }, { "code": null, "e": 1365, "s": 1363, "text": "0" }, { "code": null, "e": 1388, "s": 1365, "text": "mayank20212 months ago" }, { "code": null, "e": 1392, "s": 1388, "text": "C++" }, { "code": null, "e": 1582, "s": 1394, "text": "int getAngle(int H , int M) { if (abs(H*30 - M*6 + M*6/12.0) > 180 ) return 360-abs(H*30 - M*6 + M*6/12.0); else return abs(H*30 - M*6 + M*6/12.0); }" }, { "code": null, "e": 1584, "s": 1582, "text": "0" }, { "code": null, "e": 1606, "s": 1584, "text": "tharabhai2 months ago" }, { "code": null, "e": 1620, "s": 1606, "text": "C++ solution:" }, { "code": null, "e": 2074, "s": 1622, "text": "int getAngle(int H , int M) { //hr is the angle covered by hr hand float hr = ((H*60+M)*0.5); //mi is the angle covered by minute hand float mi = (M*6); //absolute difference b/w them hr = abs(hr-mi); //checking which side of the circle is smaller hr = hr>(360-hr)?360-hr:hr; //floor of that value as asked for int ans = floor(hr); return ans; }" }, { "code": null, "e": 2103, "s": 2076, "text": "Drop suggestions if any :)" }, { "code": null, "e": 2105, "s": 2103, "text": "0" }, { "code": null, "e": 2132, "s": 2105, "text": "taiphanvan24032 months ago" }, { "code": null, "e": 2252, "s": 2132, "text": "int getAngle(int H , int M) {\n float a=abs(6*(5*H-M)+0.5*M);\n if(a>180) return 360-a;\n return a;\n }" }, { "code": null, "e": 2254, "s": 2252, "text": "0" }, { "code": null, "e": 2277, "s": 2254, "text": "ramyan18143 months ago" }, { "code": null, "e": 2436, "s": 2277, "text": "class Solution { public: int getAngle(int H , int M) { float ans=abs(30*H+0.5*M-6*M); return (int)(ans<=180?ans:360-ans); " }, { "code": null, "e": 2438, "s": 2436, "text": "0" }, { "code": null, "e": 2455, "s": 2438, "text": "hasanshaikh19990" }, { "code": null, "e": 2481, "s": 2455, "text": "This comment was deleted." }, { "code": null, "e": 2484, "s": 2481, "text": "+2" }, { "code": null, "e": 2519, "s": 2484, "text": "Deyyala Srinivas Kumar8 months ago" }, { "code": null, "e": 2542, "s": 2519, "text": "Deyyala Srinivas Kumar" }, { "code": null, "e": 2744, "s": 2542, "text": "spoilerint getAngle(int H , int M) { // code here int a= abs(((60*H)-(11*M))/2); if((((60*H)-(11*M))%2)==0) return min(a,360-a); else return min(a,359-a); }" }, { "code": null, "e": 2746, "s": 2744, "text": "0" }, { "code": null, "e": 2780, "s": 2746, "text": "Aditya Raj Singh Gour8 months ago" }, { "code": null, "e": 2802, "s": 2780, "text": "Aditya Raj Singh Gour" }, { "code": null, "e": 2861, "s": 2802, "text": "Example is wrong !For H = 9 and M = 0 correct answer is 90" }, { "code": null, "e": 2863, "s": 2861, "text": "0" }, { "code": null, "e": 2888, "s": 2863, "text": "Aayush Kumar9 months ago" }, { "code": null, "e": 2901, "s": 2888, "text": "Aayush Kumar" }, { "code": null, "e": 2972, "s": 2901, "text": "Is 12:60 equal to 12:00 or 1:00? There's a problem with this question." }, { "code": null, "e": 2974, "s": 2972, "text": "0" }, { "code": null, "e": 2992, "s": 2974, "text": "Ayush9 months ago" }, { "code": null, "e": 2998, "s": 2992, "text": "Ayush" }, { "code": null, "e": 3123, "s": 2998, "text": "How the angle between minute and hour hand at 9:60 which mean 10 is 90 degree, ideally isn't it should have to be 60 degree?" }, { "code": null, "e": 3269, "s": 3123, "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": 3305, "s": 3269, "text": " Login to access your submissions. " }, { "code": null, "e": 3315, "s": 3305, "text": "\nProblem\n" }, { "code": null, "e": 3325, "s": 3315, "text": "\nContest\n" }, { "code": null, "e": 3388, "s": 3325, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3536, "s": 3388, "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": 3744, "s": 3536, "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": 3850, "s": 3744, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to apply a CNN from PyTorch to your images. | by Alexey Khrustalev | Towards Data Science
Hello everyone! Today I’d like to talk about uploading your images into your PyTorch CNN. Today we will cover the following: How to store images properly, so that you can easily get your data labeled. How to access the data using PyTorch and make some preprocessing on the way. In the end, we will use a very simple CNN to classify our images. I will use this data set, which contains the images of cats and dogs. The easiest way to store your images is to create a folder for each class, naming the folder with the name of the class. Let me show an example: By simply naming your folders properly, you’ll let PyTorch know to which class to assert an image. import matplotlib.pyplot as pltfrom torchvision import datasets, transformsfrom torch.utils.data import DataLoaderimport torch.nn as nnimport torch.nn.functional as Fimport torch.optim as optimimport torchdef get_data(): data_dir = '/your_path/Data/' train_set = datasets.ImageFolder(data_dir + '/training_set') test_set = datasets.ImageFolder(data_dir + '/test_set') return train_set, test_set The function above gets the data from the directory. You have to simply specify the path to your Train Set and Test Set folders. PyTorch will then automatically assign the labels to images, using the names of the folders in the specified directory. However, you might want to make some preprocessing before using the images, so let’s do it and, furthermore, let’s create a DataLoader right away. To do so, let’s add some new lines to the code above. def get_data(): data_dir = '/your_path/Data/' transform = transforms.Compose([ #transforms.RandomRotation(20), transforms.RandomResizedCrop(128), #transforms.RandomHorizontalFlip(), transforms.ToTensor()]) train_set = datasets.ImageFolder(data_dir + '/training_set', transform=transform) test_set = datasets.ImageFolder(data_dir + '/test_set', transform=transform) train = DataLoader(train_set, batch_size=32, shuffle=True) test = DataLoader(test_set, batch_size=32, shuffle=True) return train, test As the transformations, you may want to crop, flip, resize, rotate, etc the images. To do so you can specify all the things you need in one place, using transforms. Then you can create the DataLoader with your images uploaded. Now, when you have the data ready, you might want to take a quick look at it. To do so, you can use this simple function, which will show the first 5 images. def train_imshow(): classes = ('cat', 'dog') # Defining the classes we have dataiter = iter(train) images, labels = dataiter.next() fig, axes = plt.subplots(figsize=(10, 4), ncols=5) for i in range(5): ax = axes[i] ax.imshow(images[i].permute(1, 2, 0)) ax.title.set_text(' '.join('%5s' % classes[labels[i]])) plt.show() Let’s define our Convolutional Neural Network: class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 6, 5) self.pool = nn.MaxPool2d(8, 8) self.conv2 = nn.Conv2d(6, 16, 5) self.fc1 = nn.Linear(16, 100) self.fc2 = nn.Linear(100, 50) self.fc3 = nn.Linear(50, 2) def forward(self, x): x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv2(x))) x = x.view(-1, 16) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return x I used the network defined here and modified it a bit so that now it can work with my images. Now we can specify the criterion, optimizer, learning rate, and train the network. criterion = nn.CrossEntropyLoss()optimizer = optim.SGD(net.parameters(), lr=0.01, momentum=0.9)if torch.cuda.is_available(): # Checking if we can use GPU model = net.cuda() criterion = criterion.cuda()def train_net(n_epoch): # Training our network losses = [] for epoch in range(n_epoch): # loop over the dataset multiple times running_loss = 0.0 for i, data in enumerate(train, 0): # get the inputs; data is a list of [inputs, labels] inputs, labels = data # zero the parameter gradients optimizer.zero_grad() # forward + backward + optimize outputs = net(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step() # print statistics losses.append(loss) running_loss += loss.item() if i % 100 == 99: # print every 2000 mini-batches print('[%d, %5d] loss: %.10f' % (epoch + 1, i + 1, running_loss / 2000)) running_loss = 0.0 plt.plot(losses, label='Training loss') plt.show() print('Finished Training') You can save and load your trained network. PATH = './cat_dog_net.pth'torch.save(net.state_dict(), PATH)# Loading the trained networknet.load_state_dict(torch.load(PATH)) Let’s feed our test images into the network. correct = 0total = 0with torch.no_grad(): for data in test: images, labels = data outputs = net(images) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum().item()print('Accuracy of the network on the %d test images: %d %%' % (len(test), 100 * correct / total)) The test set error is 66%, which is not bad, though getting the best possible accuracy is not the goal of this article. Here you can find the complete code. Well done! Now you are ready to practice in deep learning using your images! Thank you for reading!
[ { "code": null, "e": 262, "s": 172, "text": "Hello everyone! Today I’d like to talk about uploading your images into your PyTorch CNN." }, { "code": null, "e": 297, "s": 262, "text": "Today we will cover the following:" }, { "code": null, "e": 373, "s": 297, "text": "How to store images properly, so that you can easily get your data labeled." }, { "code": null, "e": 450, "s": 373, "text": "How to access the data using PyTorch and make some preprocessing on the way." }, { "code": null, "e": 516, "s": 450, "text": "In the end, we will use a very simple CNN to classify our images." }, { "code": null, "e": 586, "s": 516, "text": "I will use this data set, which contains the images of cats and dogs." }, { "code": null, "e": 707, "s": 586, "text": "The easiest way to store your images is to create a folder for each class, naming the folder with the name of the class." }, { "code": null, "e": 731, "s": 707, "text": "Let me show an example:" }, { "code": null, "e": 830, "s": 731, "text": "By simply naming your folders properly, you’ll let PyTorch know to which class to assert an image." }, { "code": null, "e": 1237, "s": 830, "text": "import matplotlib.pyplot as pltfrom torchvision import datasets, transformsfrom torch.utils.data import DataLoaderimport torch.nn as nnimport torch.nn.functional as Fimport torch.optim as optimimport torchdef get_data(): data_dir = '/your_path/Data/' train_set = datasets.ImageFolder(data_dir + '/training_set') test_set = datasets.ImageFolder(data_dir + '/test_set') return train_set, test_set" }, { "code": null, "e": 1486, "s": 1237, "text": "The function above gets the data from the directory. You have to simply specify the path to your Train Set and Test Set folders. PyTorch will then automatically assign the labels to images, using the names of the folders in the specified directory." }, { "code": null, "e": 1687, "s": 1486, "text": "However, you might want to make some preprocessing before using the images, so let’s do it and, furthermore, let’s create a DataLoader right away. To do so, let’s add some new lines to the code above." }, { "code": null, "e": 2239, "s": 1687, "text": "def get_data(): data_dir = '/your_path/Data/' transform = transforms.Compose([ #transforms.RandomRotation(20), transforms.RandomResizedCrop(128), #transforms.RandomHorizontalFlip(), transforms.ToTensor()]) train_set = datasets.ImageFolder(data_dir + '/training_set', transform=transform) test_set = datasets.ImageFolder(data_dir + '/test_set', transform=transform) train = DataLoader(train_set, batch_size=32, shuffle=True) test = DataLoader(test_set, batch_size=32, shuffle=True) return train, test" }, { "code": null, "e": 2466, "s": 2239, "text": "As the transformations, you may want to crop, flip, resize, rotate, etc the images. To do so you can specify all the things you need in one place, using transforms. Then you can create the DataLoader with your images uploaded." }, { "code": null, "e": 2624, "s": 2466, "text": "Now, when you have the data ready, you might want to take a quick look at it. To do so, you can use this simple function, which will show the first 5 images." }, { "code": null, "e": 2984, "s": 2624, "text": "def train_imshow(): classes = ('cat', 'dog') # Defining the classes we have dataiter = iter(train) images, labels = dataiter.next() fig, axes = plt.subplots(figsize=(10, 4), ncols=5) for i in range(5): ax = axes[i] ax.imshow(images[i].permute(1, 2, 0)) ax.title.set_text(' '.join('%5s' % classes[labels[i]])) plt.show()" }, { "code": null, "e": 3031, "s": 2984, "text": "Let’s define our Convolutional Neural Network:" }, { "code": null, "e": 3577, "s": 3031, "text": "class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 6, 5) self.pool = nn.MaxPool2d(8, 8) self.conv2 = nn.Conv2d(6, 16, 5) self.fc1 = nn.Linear(16, 100) self.fc2 = nn.Linear(100, 50) self.fc3 = nn.Linear(50, 2) def forward(self, x): x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv2(x))) x = x.view(-1, 16) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return x" }, { "code": null, "e": 3671, "s": 3577, "text": "I used the network defined here and modified it a bit so that now it can work with my images." }, { "code": null, "e": 3754, "s": 3671, "text": "Now we can specify the criterion, optimizer, learning rate, and train the network." }, { "code": null, "e": 4904, "s": 3754, "text": "criterion = nn.CrossEntropyLoss()optimizer = optim.SGD(net.parameters(), lr=0.01, momentum=0.9)if torch.cuda.is_available(): # Checking if we can use GPU model = net.cuda() criterion = criterion.cuda()def train_net(n_epoch): # Training our network losses = [] for epoch in range(n_epoch): # loop over the dataset multiple times running_loss = 0.0 for i, data in enumerate(train, 0): # get the inputs; data is a list of [inputs, labels] inputs, labels = data # zero the parameter gradients optimizer.zero_grad() # forward + backward + optimize outputs = net(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step() # print statistics losses.append(loss) running_loss += loss.item() if i % 100 == 99: # print every 2000 mini-batches print('[%d, %5d] loss: %.10f' % (epoch + 1, i + 1, running_loss / 2000)) running_loss = 0.0 plt.plot(losses, label='Training loss') plt.show() print('Finished Training')" }, { "code": null, "e": 4948, "s": 4904, "text": "You can save and load your trained network." }, { "code": null, "e": 5075, "s": 4948, "text": "PATH = './cat_dog_net.pth'torch.save(net.state_dict(), PATH)# Loading the trained networknet.load_state_dict(torch.load(PATH))" }, { "code": null, "e": 5120, "s": 5075, "text": "Let’s feed our test images into the network." }, { "code": null, "e": 5475, "s": 5120, "text": "correct = 0total = 0with torch.no_grad(): for data in test: images, labels = data outputs = net(images) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum().item()print('Accuracy of the network on the %d test images: %d %%' % (len(test), 100 * correct / total))" }, { "code": null, "e": 5595, "s": 5475, "text": "The test set error is 66%, which is not bad, though getting the best possible accuracy is not the goal of this article." }, { "code": null, "e": 5632, "s": 5595, "text": "Here you can find the complete code." }, { "code": null, "e": 5709, "s": 5632, "text": "Well done! Now you are ready to practice in deep learning using your images!" } ]
PHP date() Function
The date() function accepts a format string as a parameter, formats the local date/time in the specified format and returns the result. date($format, $timestamp) format (Mandatory) This is a format string specifying the format in which you want the output date string to be. timestamp (Optional) This is an integer value representing the timestamp of the required date PHP date() function returns the current local time/date in the specified format. This function was first introduced in PHP Version 4 and, works with all the later versions. Try out following demonstrates the usage of the date() function − <?php $date = date("D M d Y"); print("Date: ".$date); ?> This will produce following result − Date: Fri May 08 2020 You can escape characters in a date format as shown below − <?php $date = date("jS F l \t"); print("Date: ".$date); ?> This will produce following result − Date: 18th May Monday Following example invokes the date() function by passing the timestamp parameter − <?php $ts = 1022555568; $date = date("D M d Y", $ts); print($date); ?> This will produce following result − Tue May 28 2002 <?php date_default_timezone_set('UTC'); echo date("l"); echo ""; echo date('l dS \of F Y h:i:s A'); echo ""; ?> This produces the following result − Monday Monday 05th of December 2016 10:27:13 AM 45 Lectures 9 hours Malhar Lathkar 34 Lectures 4 hours Syed Raza 84 Lectures 5.5 hours Frahaan Hussain 17 Lectures 1 hours Nivedita Jain 100 Lectures 34 hours Azaz Patel 43 Lectures 5.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2893, "s": 2757, "text": "The date() function accepts a format string as a parameter, formats the local date/time in the specified format and returns the result." }, { "code": null, "e": 2920, "s": 2893, "text": "date($format, $timestamp)\n" }, { "code": null, "e": 2939, "s": 2920, "text": "format (Mandatory)" }, { "code": null, "e": 3033, "s": 2939, "text": "This is a format string specifying the format in which you want the output date string to be." }, { "code": null, "e": 3054, "s": 3033, "text": "timestamp (Optional)" }, { "code": null, "e": 3128, "s": 3054, "text": " This is an integer value representing the timestamp of the required date" }, { "code": null, "e": 3209, "s": 3128, "text": "PHP date() function returns the current local time/date in the specified format." }, { "code": null, "e": 3301, "s": 3209, "text": "This function was first introduced in PHP Version 4 and, works with all the later versions." }, { "code": null, "e": 3367, "s": 3301, "text": "Try out following demonstrates the usage of the date() function −" }, { "code": null, "e": 3430, "s": 3367, "text": "<?php\n $date = date(\"D M d Y\");\n print(\"Date: \".$date);\n?>" }, { "code": null, "e": 3467, "s": 3430, "text": "This will produce following result −" }, { "code": null, "e": 3490, "s": 3467, "text": "Date: Fri May 08 2020\n" }, { "code": null, "e": 3550, "s": 3490, "text": "You can escape characters in a date format as shown below −" }, { "code": null, "e": 3615, "s": 3550, "text": "<?php\n $date = date(\"jS F l \\t\");\n print(\"Date: \".$date);\n?>" }, { "code": null, "e": 3652, "s": 3615, "text": "This will produce following result −" }, { "code": null, "e": 3675, "s": 3652, "text": "Date: 18th May Monday\n" }, { "code": null, "e": 3758, "s": 3675, "text": "Following example invokes the date() function by passing the timestamp parameter −" }, { "code": null, "e": 3838, "s": 3758, "text": "<?php\n $ts = 1022555568;\n $date = date(\"D M d Y\", $ts);\n print($date);\n?>" }, { "code": null, "e": 3875, "s": 3838, "text": "This will produce following result −" }, { "code": null, "e": 3892, "s": 3875, "text": "Tue May 28 2002\n" }, { "code": null, "e": 4027, "s": 3892, "text": "<?php\n date_default_timezone_set('UTC');\n \n echo date(\"l\");\n echo \"\";\n \n echo date('l dS \\of F Y h:i:s A');\n echo \"\";\n?>" }, { "code": null, "e": 4064, "s": 4027, "text": "This produces the following result −" }, { "code": null, "e": 4112, "s": 4064, "text": "Monday\nMonday 05th of December 2016 10:27:13 AM" }, { "code": null, "e": 4145, "s": 4112, "text": "\n 45 Lectures \n 9 hours \n" }, { "code": null, "e": 4161, "s": 4145, "text": " Malhar Lathkar" }, { "code": null, "e": 4194, "s": 4161, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 4205, "s": 4194, "text": " Syed Raza" }, { "code": null, "e": 4240, "s": 4205, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4257, "s": 4240, "text": " Frahaan Hussain" }, { "code": null, "e": 4290, "s": 4257, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 4305, "s": 4290, "text": " Nivedita Jain" }, { "code": null, "e": 4340, "s": 4305, "text": "\n 100 Lectures \n 34 hours \n" }, { "code": null, "e": 4352, "s": 4340, "text": " Azaz Patel" }, { "code": null, "e": 4387, "s": 4352, "text": "\n 43 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4415, "s": 4387, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 4422, "s": 4415, "text": " Print" }, { "code": null, "e": 4433, "s": 4422, "text": " Add Notes" } ]
How to Sort/Order keys in JavaScript objects ?
31 Dec, 2019 Given an object and the task is to sort the JavaScript Object on the basis of keys. Here are a few of the most used techniques discussed with the help of JavaScript. Approach 1: By using .sort() method to sort the keys according to the conditions specified in the function and get the sorted keys in the array. To copy the whole object to that temporary variable in the order of keys in a key array(in sorted fashion) and delete the original object will make a temporary variable. After that, we just need to copy the temporary object to the original object and return it. Example 1: This example implements the above approach.<!DOCTYPE HTML><html> <head> <title> How to Sort/Order keys in JavaScript objects ? </title> <style> body { text-align: center; } h1 { color: green; } #geeks { font-size: 20px; font-weight: bold; } </style></head> <body> <h1>GeeksforGeeks</h1> <b> Click on the button to sort the Object on Keys. <br> <pre>Object = { CSS: '1', JavaScript: '2', HTML: '3', Python: '4' } </pre> </b> <button onclick="gfg_Run()"> Click Here </button> <p id="geeks"></p> <script> var el_down = document.getElementById("geeks"); var GFG_Object = { CSS: '1', JavaScript: '2', HTML: '3', Python: '4' }; // Sorted keys are obtained in 'key' array function sortKeys(obj_1) { var key = Object.keys(obj_1) .sort(function order(key1, key2) { if (key1 < key2) return -1; else if (key1 > key2) return +1; else return 0; }); // Taking the object in 'temp' object // and deleting the original object. var temp = {}; for (var i = 0; i < key.length; i++) { temp[key[i]] = obj_1[key[i]]; delete obj_1[key[i]]; } // Copying the object from 'temp' to // 'original object'. for (var i = 0; i < key.length; i++) { obj_1[key[i]] = temp[key[i]]; } return obj_1; } function gfg_Run() { el_down.innerHTML = JSON .stringify(sortKeys(GFG_Object)); } </script></body> </html> <!DOCTYPE HTML><html> <head> <title> How to Sort/Order keys in JavaScript objects ? </title> <style> body { text-align: center; } h1 { color: green; } #geeks { font-size: 20px; font-weight: bold; } </style></head> <body> <h1>GeeksforGeeks</h1> <b> Click on the button to sort the Object on Keys. <br> <pre>Object = { CSS: '1', JavaScript: '2', HTML: '3', Python: '4' } </pre> </b> <button onclick="gfg_Run()"> Click Here </button> <p id="geeks"></p> <script> var el_down = document.getElementById("geeks"); var GFG_Object = { CSS: '1', JavaScript: '2', HTML: '3', Python: '4' }; // Sorted keys are obtained in 'key' array function sortKeys(obj_1) { var key = Object.keys(obj_1) .sort(function order(key1, key2) { if (key1 < key2) return -1; else if (key1 > key2) return +1; else return 0; }); // Taking the object in 'temp' object // and deleting the original object. var temp = {}; for (var i = 0; i < key.length; i++) { temp[key[i]] = obj_1[key[i]]; delete obj_1[key[i]]; } // Copying the object from 'temp' to // 'original object'. for (var i = 0; i < key.length; i++) { obj_1[key[i]] = temp[key[i]]; } return obj_1; } function gfg_Run() { el_down.innerHTML = JSON .stringify(sortKeys(GFG_Object)); } </script></body> </html> Output: Approach 2: In this approach .sort() method sort the keys alphabetically then we have to use .reduce() method on these sorted keys. Then call an anonymous function inside reduce() method with 2 variables(emptyObject and key). Now one by one put the key and value pair in the emptyObject and return it. Example 2: This example implements the above approach.<!DOCTYPE HTML><html> <head> <title> How to Sort/Order keys in JavaScript objects ? </title> <style> body { text-align: center; } h1 { color: green; } #geeks { font-size: 20px; font-weight: bold; } </style></head> <body> <h1>GeeksforGeeks</h1> <b> Click on the button to sort the Object on Keys.<br> <pre>Object = { CSS: '1', JavaScript: '2', HTML: '3', Python: '4' } </pre> </b> <button onclick="gfg_Run()"> Click Here </button> <p id="geeks"></p> <script> var el_down = document.getElementById("geeks"); var GFG_Object = { CSS: '1', JavaScript: '2', HTML: '3', Python: '4' }; function gfg_Run() { // Getting the keys of JavaScript Object. Modified_Object = Object.keys(GFG_Object) // Sort and calling a method on // keys on sorted fashion. .sort().reduce(function(Obj, key) { // Adding the key-value pair to the // new object in sorted keys manner Obj[key] = GFG_Object[key]; return Obj; }, {}); el_down.innerHTML = JSON.stringify(Modified_Object); } </script></body> </html> <!DOCTYPE HTML><html> <head> <title> How to Sort/Order keys in JavaScript objects ? </title> <style> body { text-align: center; } h1 { color: green; } #geeks { font-size: 20px; font-weight: bold; } </style></head> <body> <h1>GeeksforGeeks</h1> <b> Click on the button to sort the Object on Keys.<br> <pre>Object = { CSS: '1', JavaScript: '2', HTML: '3', Python: '4' } </pre> </b> <button onclick="gfg_Run()"> Click Here </button> <p id="geeks"></p> <script> var el_down = document.getElementById("geeks"); var GFG_Object = { CSS: '1', JavaScript: '2', HTML: '3', Python: '4' }; function gfg_Run() { // Getting the keys of JavaScript Object. Modified_Object = Object.keys(GFG_Object) // Sort and calling a method on // keys on sorted fashion. .sort().reduce(function(Obj, key) { // Adding the key-value pair to the // new object in sorted keys manner Obj[key] = GFG_Object[key]; return Obj; }, {}); el_down.innerHTML = JSON.stringify(Modified_Object); } </script></body> </html> Output: JavaScript-Misc 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": "\n31 Dec, 2019" }, { "code": null, "e": 194, "s": 28, "text": "Given an object and the task is to sort the JavaScript Object on the basis of keys. Here are a few of the most used techniques discussed with the help of JavaScript." }, { "code": null, "e": 601, "s": 194, "text": "Approach 1: By using .sort() method to sort the keys according to the conditions specified in the function and get the sorted keys in the array. To copy the whole object to that temporary variable in the order of keys in a key array(in sorted fashion) and delete the original object will make a temporary variable. After that, we just need to copy the temporary object to the original object and return it." }, { "code": null, "e": 2595, "s": 601, "text": "Example 1: This example implements the above approach.<!DOCTYPE HTML><html> <head> <title> How to Sort/Order keys in JavaScript objects ? </title> <style> body { text-align: center; } h1 { color: green; } #geeks { font-size: 20px; font-weight: bold; } </style></head> <body> <h1>GeeksforGeeks</h1> <b> Click on the button to sort the Object on Keys. <br> <pre>Object = { CSS: '1', JavaScript: '2', HTML: '3', Python: '4' } </pre> </b> <button onclick=\"gfg_Run()\"> Click Here </button> <p id=\"geeks\"></p> <script> var el_down = document.getElementById(\"geeks\"); var GFG_Object = { CSS: '1', JavaScript: '2', HTML: '3', Python: '4' }; // Sorted keys are obtained in 'key' array function sortKeys(obj_1) { var key = Object.keys(obj_1) .sort(function order(key1, key2) { if (key1 < key2) return -1; else if (key1 > key2) return +1; else return 0; }); // Taking the object in 'temp' object // and deleting the original object. var temp = {}; for (var i = 0; i < key.length; i++) { temp[key[i]] = obj_1[key[i]]; delete obj_1[key[i]]; } // Copying the object from 'temp' to // 'original object'. for (var i = 0; i < key.length; i++) { obj_1[key[i]] = temp[key[i]]; } return obj_1; } function gfg_Run() { el_down.innerHTML = JSON .stringify(sortKeys(GFG_Object)); } </script></body> </html>" }, { "code": "<!DOCTYPE HTML><html> <head> <title> How to Sort/Order keys in JavaScript objects ? </title> <style> body { text-align: center; } h1 { color: green; } #geeks { font-size: 20px; font-weight: bold; } </style></head> <body> <h1>GeeksforGeeks</h1> <b> Click on the button to sort the Object on Keys. <br> <pre>Object = { CSS: '1', JavaScript: '2', HTML: '3', Python: '4' } </pre> </b> <button onclick=\"gfg_Run()\"> Click Here </button> <p id=\"geeks\"></p> <script> var el_down = document.getElementById(\"geeks\"); var GFG_Object = { CSS: '1', JavaScript: '2', HTML: '3', Python: '4' }; // Sorted keys are obtained in 'key' array function sortKeys(obj_1) { var key = Object.keys(obj_1) .sort(function order(key1, key2) { if (key1 < key2) return -1; else if (key1 > key2) return +1; else return 0; }); // Taking the object in 'temp' object // and deleting the original object. var temp = {}; for (var i = 0; i < key.length; i++) { temp[key[i]] = obj_1[key[i]]; delete obj_1[key[i]]; } // Copying the object from 'temp' to // 'original object'. for (var i = 0; i < key.length; i++) { obj_1[key[i]] = temp[key[i]]; } return obj_1; } function gfg_Run() { el_down.innerHTML = JSON .stringify(sortKeys(GFG_Object)); } </script></body> </html>", "e": 4535, "s": 2595, "text": null }, { "code": null, "e": 4543, "s": 4535, "text": "Output:" }, { "code": null, "e": 4845, "s": 4543, "text": "Approach 2: In this approach .sort() method sort the keys alphabetically then we have to use .reduce() method on these sorted keys. Then call an anonymous function inside reduce() method with 2 variables(emptyObject and key). Now one by one put the key and value pair in the emptyObject and return it." }, { "code": null, "e": 6452, "s": 4845, "text": "Example 2: This example implements the above approach.<!DOCTYPE HTML><html> <head> <title> How to Sort/Order keys in JavaScript objects ? </title> <style> body { text-align: center; } h1 { color: green; } #geeks { font-size: 20px; font-weight: bold; } </style></head> <body> <h1>GeeksforGeeks</h1> <b> Click on the button to sort the Object on Keys.<br> <pre>Object = { CSS: '1', JavaScript: '2', HTML: '3', Python: '4' } </pre> </b> <button onclick=\"gfg_Run()\"> Click Here </button> <p id=\"geeks\"></p> <script> var el_down = document.getElementById(\"geeks\"); var GFG_Object = { CSS: '1', JavaScript: '2', HTML: '3', Python: '4' }; function gfg_Run() { // Getting the keys of JavaScript Object. Modified_Object = Object.keys(GFG_Object) // Sort and calling a method on // keys on sorted fashion. .sort().reduce(function(Obj, key) { // Adding the key-value pair to the // new object in sorted keys manner Obj[key] = GFG_Object[key]; return Obj; }, {}); el_down.innerHTML = JSON.stringify(Modified_Object); } </script></body> </html>" }, { "code": "<!DOCTYPE HTML><html> <head> <title> How to Sort/Order keys in JavaScript objects ? </title> <style> body { text-align: center; } h1 { color: green; } #geeks { font-size: 20px; font-weight: bold; } </style></head> <body> <h1>GeeksforGeeks</h1> <b> Click on the button to sort the Object on Keys.<br> <pre>Object = { CSS: '1', JavaScript: '2', HTML: '3', Python: '4' } </pre> </b> <button onclick=\"gfg_Run()\"> Click Here </button> <p id=\"geeks\"></p> <script> var el_down = document.getElementById(\"geeks\"); var GFG_Object = { CSS: '1', JavaScript: '2', HTML: '3', Python: '4' }; function gfg_Run() { // Getting the keys of JavaScript Object. Modified_Object = Object.keys(GFG_Object) // Sort and calling a method on // keys on sorted fashion. .sort().reduce(function(Obj, key) { // Adding the key-value pair to the // new object in sorted keys manner Obj[key] = GFG_Object[key]; return Obj; }, {}); el_down.innerHTML = JSON.stringify(Modified_Object); } </script></body> </html>", "e": 8005, "s": 6452, "text": null }, { "code": null, "e": 8013, "s": 8005, "text": "Output:" }, { "code": null, "e": 8029, "s": 8013, "text": "JavaScript-Misc" }, { "code": null, "e": 8040, "s": 8029, "text": "JavaScript" }, { "code": null, "e": 8057, "s": 8040, "text": "Web Technologies" }, { "code": null, "e": 8084, "s": 8057, "text": "Web technologies Questions" } ]
Python | Custom sorting in list of tuples
11 May, 2020 Sometimes, while working with list of tuples, we can have a problem in which we need to perform it’s sorting. Naive sorting is easier, but sometimes, we have to perform custom sorting, i.e by decreasing order of first element and increasing order of 2nd element. And these can also be in cases of different types of tuples. Let’s discuss certain cases and solutions to perform this kind of custom sorting. Method #1 : Using sorted() + lambdaThis task can be performed using the combination of above functions. In this, we just perform the normal sort, but in addition we feed a lambda function which handles the case of custom sorting discussed above. # Python3 code to demonstrate working of# Custom sorting in list of tuples# Using sorted() + lambda # Initializing listtest_list = [(7, 8), (5, 6), (7, 5), (10, 4), (10, 1)] # printing original listprint("The original list is : " + str(test_list)) # Custom sorting in list of tuples# Using sorted() + lambdares = sorted(test_list, key = lambda sub: (-sub[0], sub[1])) # printing resultprint("The tuple after custom sorting is : " + str(res)) The original list is : [(7, 8), (5, 6), (7, 5), (10, 4), (10, 1)] The tuple after custom sorting is : [(10, 1), (10, 4), (7, 5), (7, 8), (5, 6)] Method #2 : Using sorted() + lambda() + sum() ( With sum of tuple condition)In this method, similar solution sustains. But the case here is that we have tuple as the 2nd element of tuple and its sum has to considered for sort order. Other functions than summation can be extended in similar solution. # Python3 code to demonstrate working of# Custom sorting in list of tuples# Using sorted() + lambda() + sum() # Initializing listtest_list = [(7, (8, 4)), (5, (6, 1)), (7, (5, 3)), (10, (5, 4)), (10, (1, 3))] # printing original listprint("The original list is : " + str(test_list)) # Custom sorting in list of tuples# Using sorted() + lambda() + sum()res = sorted(test_list, key = lambda sub: (-sub[0], sum(sub[1]))) # printing resultprint("The tuple after custom sorting is : " + str(res)) The original list is : [(7, (8, 4)), (5, (6, 1)), (7, (5, 3)), (10, (5, 4)), (10, (1, 3))] The tuple after custom sorting is : [(10, (1, 3)), (10, (5, 4)), (7, (5, 3)), (7, (8, 4)), (5, (6, 1))] Python list-programs Python tuple-programs Python-sort Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 May, 2020" }, { "code": null, "e": 434, "s": 28, "text": "Sometimes, while working with list of tuples, we can have a problem in which we need to perform it’s sorting. Naive sorting is easier, but sometimes, we have to perform custom sorting, i.e by decreasing order of first element and increasing order of 2nd element. And these can also be in cases of different types of tuples. Let’s discuss certain cases and solutions to perform this kind of custom sorting." }, { "code": null, "e": 680, "s": 434, "text": "Method #1 : Using sorted() + lambdaThis task can be performed using the combination of above functions. In this, we just perform the normal sort, but in addition we feed a lambda function which handles the case of custom sorting discussed above." }, { "code": "# Python3 code to demonstrate working of# Custom sorting in list of tuples# Using sorted() + lambda # Initializing listtest_list = [(7, 8), (5, 6), (7, 5), (10, 4), (10, 1)] # printing original listprint(\"The original list is : \" + str(test_list)) # Custom sorting in list of tuples# Using sorted() + lambdares = sorted(test_list, key = lambda sub: (-sub[0], sub[1])) # printing resultprint(\"The tuple after custom sorting is : \" + str(res))", "e": 1126, "s": 680, "text": null }, { "code": null, "e": 1272, "s": 1126, "text": "The original list is : [(7, 8), (5, 6), (7, 5), (10, 4), (10, 1)]\nThe tuple after custom sorting is : [(10, 1), (10, 4), (7, 5), (7, 8), (5, 6)]\n" }, { "code": null, "e": 1575, "s": 1274, "text": "Method #2 : Using sorted() + lambda() + sum() ( With sum of tuple condition)In this method, similar solution sustains. But the case here is that we have tuple as the 2nd element of tuple and its sum has to considered for sort order. Other functions than summation can be extended in similar solution." }, { "code": "# Python3 code to demonstrate working of# Custom sorting in list of tuples# Using sorted() + lambda() + sum() # Initializing listtest_list = [(7, (8, 4)), (5, (6, 1)), (7, (5, 3)), (10, (5, 4)), (10, (1, 3))] # printing original listprint(\"The original list is : \" + str(test_list)) # Custom sorting in list of tuples# Using sorted() + lambda() + sum()res = sorted(test_list, key = lambda sub: (-sub[0], sum(sub[1]))) # printing resultprint(\"The tuple after custom sorting is : \" + str(res))", "e": 2071, "s": 1575, "text": null }, { "code": null, "e": 2267, "s": 2071, "text": "The original list is : [(7, (8, 4)), (5, (6, 1)), (7, (5, 3)), (10, (5, 4)), (10, (1, 3))]\nThe tuple after custom sorting is : [(10, (1, 3)), (10, (5, 4)), (7, (5, 3)), (7, (8, 4)), (5, (6, 1))]\n" }, { "code": null, "e": 2288, "s": 2267, "text": "Python list-programs" }, { "code": null, "e": 2310, "s": 2288, "text": "Python tuple-programs" }, { "code": null, "e": 2322, "s": 2310, "text": "Python-sort" }, { "code": null, "e": 2329, "s": 2322, "text": "Python" }, { "code": null, "e": 2345, "s": 2329, "text": "Python Programs" } ]
How Change the vertical spacing between legend entries in Matplotlib?
13 Jan, 2021 Prerequisites: Matplotlib In this article, we will see how can we can change vertical space between labels of a legend in our graph using matplotlib, Here we will take two different examples to showcase our graph. Approach: Import required module. Create data. Change the vertical spacing between labels. Normally plot the data. Display plot. Implementation: Example 1: In this example, we will draw different lines with the help of matplotlib and Use the labelspacing argument to plt.legend() to change the vertical space between labels. Python3 # importing packageimport matplotlib.pyplot as pltimport numpy as np # create dataX = [1, 2, 3, 4, 5]Y = [3, 3, 3, 3, 3] # plot linesplt.plot(X, Y, label = "Line-1")plt.plot(Y, X, label = "Line-2")plt.plot(X, np.sin(X), label = "Curve-1")plt.plot(X, np.cos(X), label = "Curve-2") # Change the label spacing hereplt.legend(labelspacing = 3)plt.title("Line Graph - Geeksforgeeks") plt.show() Output: Example 2: In this example, we will draw a Vertical line with the help of matplotlib and Use the labelspacing argument to plt.legend() to change the vertical space between labels. Python3 # importing packageimport matplotlib.pyplot as plt #Create data and plot lines.plt.plot([0, 1], [0, 2.0], label = 'Label-1')plt.plot([1, 2], [0, 2.1], label = 'Label-2')plt.plot([2, 3], [0, 2.2], label = 'Label-3') # Change the label spacing hereplt.legend(labelspacing = 2)plt.title("Line Graph - Geeksforgeeks") plt.show() Output: Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Jan, 2021" }, { "code": null, "e": 54, "s": 28, "text": "Prerequisites: Matplotlib" }, { "code": null, "e": 242, "s": 54, "text": "In this article, we will see how can we can change vertical space between labels of a legend in our graph using matplotlib, Here we will take two different examples to showcase our graph." }, { "code": null, "e": 252, "s": 242, "text": "Approach:" }, { "code": null, "e": 276, "s": 252, "text": "Import required module." }, { "code": null, "e": 289, "s": 276, "text": "Create data." }, { "code": null, "e": 333, "s": 289, "text": "Change the vertical spacing between labels." }, { "code": null, "e": 357, "s": 333, "text": "Normally plot the data." }, { "code": null, "e": 371, "s": 357, "text": "Display plot." }, { "code": null, "e": 387, "s": 371, "text": "Implementation:" }, { "code": null, "e": 398, "s": 387, "text": "Example 1:" }, { "code": null, "e": 567, "s": 398, "text": "In this example, we will draw different lines with the help of matplotlib and Use the labelspacing argument to plt.legend() to change the vertical space between labels." }, { "code": null, "e": 575, "s": 567, "text": "Python3" }, { "code": "# importing packageimport matplotlib.pyplot as pltimport numpy as np # create dataX = [1, 2, 3, 4, 5]Y = [3, 3, 3, 3, 3] # plot linesplt.plot(X, Y, label = \"Line-1\")plt.plot(Y, X, label = \"Line-2\")plt.plot(X, np.sin(X), label = \"Curve-1\")plt.plot(X, np.cos(X), label = \"Curve-2\") # Change the label spacing hereplt.legend(labelspacing = 3)plt.title(\"Line Graph - Geeksforgeeks\") plt.show()", "e": 969, "s": 575, "text": null }, { "code": null, "e": 977, "s": 969, "text": "Output:" }, { "code": null, "e": 988, "s": 977, "text": "Example 2:" }, { "code": null, "e": 1157, "s": 988, "text": "In this example, we will draw a Vertical line with the help of matplotlib and Use the labelspacing argument to plt.legend() to change the vertical space between labels." }, { "code": null, "e": 1165, "s": 1157, "text": "Python3" }, { "code": "# importing packageimport matplotlib.pyplot as plt #Create data and plot lines.plt.plot([0, 1], [0, 2.0], label = 'Label-1')plt.plot([1, 2], [0, 2.1], label = 'Label-2')plt.plot([2, 3], [0, 2.2], label = 'Label-3') # Change the label spacing hereplt.legend(labelspacing = 2)plt.title(\"Line Graph - Geeksforgeeks\") plt.show()", "e": 1493, "s": 1165, "text": null }, { "code": null, "e": 1501, "s": 1493, "text": "Output:" }, { "code": null, "e": 1519, "s": 1501, "text": "Python-matplotlib" }, { "code": null, "e": 1526, "s": 1519, "text": "Python" } ]
SVG <feFlood> Element
31 Mar, 2022 SVG stands for Scalable Vector Graphic. It can be used to make graphics and animations like in HTML canvas. SVG <feFlood> element generates a layer of continuous color that completely fills this element’s filter primitive region. Syntax: <feFlood x="" y="" width="" height="" flood-color="" flood-opacity=""/> Syntax: x, y – It defines the x-axis, and y-axis coordinate in the user coordinate system. width – The width of the foreignObject. height – The height of the foreignObject. flood-color – It tells the color of the new layer. flood-opacity – It tells the opacity value of the new layer. Example 1: <!DOCTYPE html><html> <body> <svg width="200" height="200"> <defs> <filter id="filter1" filterUnits="userSpaceOnUse"> <feFlood x="5%" y="5%" width="198" height="118" flood-color="shadow" flood-opacity="0.3" /> </filter> </defs> <rect x="1" y="1" width="198" height="118" style="stroke: #000000; fill: red; filter: url(#filter1);" /> <g fill="#FFFFFF" stroke="Green" font-size="20" font-family="Verdana"> <text x="28" y="70">GeeksForGeeks</text> </g> </svg></body> </html> Output: Example 2: <!DOCTYPE html><html><title>SVG Filter</title> <body> <svg width="200" height="200"> <defs> <filter id="filter1" filterUnits="userSpaceOnUse"> <feFlood x="5%" y="5%" width="198" height="118" flood-color="green" flood-opacity="0.7" /> <feDiffuseLighting in="BackgroundImage" surfaceScale="14" diffuseConstant="2" kernelUnitLength="2"> <feSpotLight x="30" y="20" z="30" limitingConeAngle="40" pointsAtX="200" pointsAtY="200" pointsAtZ="0" /> <fePointLight x="100" y="80" z="40" /> </feDiffuseLighting> </filter> </defs> <rect x="2" y="1" width="198" height="118" style="stroke: #000000; fill: green; filter: url(#filter1);" /> <circle cx="108" cy="68" r="55" stroke="black" stroke-width="3" fill="lightgreen" filter: url(#filter1) /> <g fill="#FFFFFF" stroke="darkGreen" font-size="12" font-family="Verdana"> <text x="60" y="70">GeeksForGeeks</text> </g> </svg></body> </html> Output: HTML-SVG SVG-Element HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? 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 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Mar, 2022" }, { "code": null, "e": 258, "s": 28, "text": "SVG stands for Scalable Vector Graphic. It can be used to make graphics and animations like in HTML canvas. SVG <feFlood> element generates a layer of continuous color that completely fills this element’s filter primitive region." }, { "code": null, "e": 266, "s": 258, "text": "Syntax:" }, { "code": null, "e": 339, "s": 266, "text": "<feFlood x=\"\" y=\"\" width=\"\" height=\"\"\n flood-color=\"\" flood-opacity=\"\"/>" }, { "code": null, "e": 347, "s": 339, "text": "Syntax:" }, { "code": null, "e": 430, "s": 347, "text": "x, y – It defines the x-axis, and y-axis coordinate in the user coordinate system." }, { "code": null, "e": 470, "s": 430, "text": "width – The width of the foreignObject." }, { "code": null, "e": 512, "s": 470, "text": "height – The height of the foreignObject." }, { "code": null, "e": 563, "s": 512, "text": "flood-color – It tells the color of the new layer." }, { "code": null, "e": 624, "s": 563, "text": "flood-opacity – It tells the opacity value of the new layer." }, { "code": null, "e": 635, "s": 624, "text": "Example 1:" }, { "code": "<!DOCTYPE html><html> <body> <svg width=\"200\" height=\"200\"> <defs> <filter id=\"filter1\" filterUnits=\"userSpaceOnUse\"> <feFlood x=\"5%\" y=\"5%\" width=\"198\" height=\"118\" flood-color=\"shadow\" flood-opacity=\"0.3\" /> </filter> </defs> <rect x=\"1\" y=\"1\" width=\"198\" height=\"118\" style=\"stroke: #000000; fill: red; filter: url(#filter1);\" /> <g fill=\"#FFFFFF\" stroke=\"Green\" font-size=\"20\" font-family=\"Verdana\"> <text x=\"28\" y=\"70\">GeeksForGeeks</text> </g> </svg></body> </html>", "e": 1341, "s": 635, "text": null }, { "code": null, "e": 1349, "s": 1341, "text": "Output:" }, { "code": null, "e": 1360, "s": 1349, "text": "Example 2:" }, { "code": "<!DOCTYPE html><html><title>SVG Filter</title> <body> <svg width=\"200\" height=\"200\"> <defs> <filter id=\"filter1\" filterUnits=\"userSpaceOnUse\"> <feFlood x=\"5%\" y=\"5%\" width=\"198\" height=\"118\" flood-color=\"green\" flood-opacity=\"0.7\" /> <feDiffuseLighting in=\"BackgroundImage\" surfaceScale=\"14\" diffuseConstant=\"2\" kernelUnitLength=\"2\"> <feSpotLight x=\"30\" y=\"20\" z=\"30\" limitingConeAngle=\"40\" pointsAtX=\"200\" pointsAtY=\"200\" pointsAtZ=\"0\" /> <fePointLight x=\"100\" y=\"80\" z=\"40\" /> </feDiffuseLighting> </filter> </defs> <rect x=\"2\" y=\"1\" width=\"198\" height=\"118\" style=\"stroke: #000000; fill: green; filter: url(#filter1);\" /> <circle cx=\"108\" cy=\"68\" r=\"55\" stroke=\"black\" stroke-width=\"3\" fill=\"lightgreen\" filter: url(#filter1) /> <g fill=\"#FFFFFF\" stroke=\"darkGreen\" font-size=\"12\" font-family=\"Verdana\"> <text x=\"60\" y=\"70\">GeeksForGeeks</text> </g> </svg></body> </html>", "e": 2705, "s": 1360, "text": null }, { "code": null, "e": 2713, "s": 2705, "text": "Output:" }, { "code": null, "e": 2722, "s": 2713, "text": "HTML-SVG" }, { "code": null, "e": 2734, "s": 2722, "text": "SVG-Element" }, { "code": null, "e": 2739, "s": 2734, "text": "HTML" }, { "code": null, "e": 2756, "s": 2739, "text": "Web Technologies" }, { "code": null, "e": 2761, "s": 2756, "text": "HTML" }, { "code": null, "e": 2859, "s": 2761, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2907, "s": 2859, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 2969, "s": 2907, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3019, "s": 2969, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 3043, "s": 3019, "text": "REST API (Introduction)" }, { "code": null, "e": 3096, "s": 3043, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 3129, "s": 3096, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3191, "s": 3129, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3252, "s": 3191, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3302, "s": 3252, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Create an Online Payment UI design using HTML/CSS
31 Mar, 2021 For anyone who is running an online business, checkout becomes an important part of the selling process to maintain the convenience for online sales and Fast transactions. An appealing User-Interface(UI) will help us in bringing in potential visitors and facilitates the user experience. In this article, we will be creating a payment page for transaction purposes. The simple project is a perfect example of how easily we can make a User Interface design using HTML and CSS. Creating Structure for our web-page: We will be starting out with creating a structural aspect of our website by using simple HTML, and later on, we will style it by using Cascading Style Sheets(CSS), which will be describing the style of our HTML document and its elements. HTML Code: In this HTML file we have mainly divided our webpage into several <div> tags, and we have use several classes as well like “main-content”, “centre-content”, “last-content” etc. This CSS classes are to stylize our HTML elements. 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"/> <link rel="stylesheet" href="style.css" class="css" /> </head> <body> <div class="container"> <div class="main-content"> <p class="text">GeeksforGeeks</p> </div> <div class="centre-content"> <h1 class="price">2499<span>/-</span></h1> <p class="course"> Buy DSA Self-Paced Course Now ! </p> </div> <div class="last-content"> <button type="button" class="pay-now-btn"> Apply Coupons </button> <button type="button" class="pay-now-btn"> Pay with Netbanking </button> <!-- <button type="button" class="pay-now-btn"> Netbanking options </button> --> </div> <div class="card-details"> <p>Pay using Credit or Debit card</p> <div class="card-number"> <label> Card Number </label> <input type="text" class="card-number-field" placeholder="###-###-###"/> </div> <br /> <div class="date-number"> <label> Expiry Date </label> <input type="text" class="date-number-field" placeholder="DD-MM-YY" /> </div> <div class="cvv-number"> <label> CVV number </label> <input type="text" class="cvv-number-field" placeholder="xxx" /> </div> <div class="nameholder-number"> <label> Card Holder name </label> <input type="text" class="card-name-field" placeholder="Enter your Name"/> </div> <button type="submit" class="submit-now-btn"> submit </button> </div> </div> </body></html> Designing Our Payment Page: Using CSS, we can store all the style information that our page would share. Whenever a user will visit the web page, the browser will load all the related information along with the proper styling related to the contents of the page. In CSS, a class is an element group that is the same or similar. You can have the elements that you want in a class. And each element can be a member of multiple classes. Every class has CSS attributes (like color and font-size) that are specific to that class. CSS Code: CSS allows us to create unique and interactive websites. style.css * { margin: 0; padding: 0;} body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; font-weight: bold;} .container { height: 900px; width: 400px; background-image: linear-gradient(#1e6b30, #308d46); top: 50%; left: 50%; position: absolute; transform: translate(-50%, -50%); position: absolute; border-bottom-left-radius: 180px; border-top-right-radius: 150px;} .main-content { height: 235px; background-color: #1b9236; border-bottom-left-radius: 90px; border-bottom-right-radius: 80px; border-top: #1e6b30;} .text { text-align: center; font-size: 300%; text-decoration: aliceblue; color: aliceblue;} .course { color: black; font-size: 25px; font-weight: bolder;} .centre-content { height: 180px; margin: -70px 30px 20px; color: aliceblue; text-align: center; font-size: 20px; border-radius: 25px; padding-top: 0.5px; background-image: linear-gradient(#1e6b30, #308d46);} .centre-content-h1 { padding-top: 30px; padding-bottom: 30px; font-weight: normal;} .price { font-size: 60px; margin-left: 5px; bottom: 15px; position: relative;} .pay-now-btn { cursor: pointer; color: #fff; height: 50px; width: 290px; border: none; margin: 5px 30px; background-color: rgb(71, 177, 61); position: relative;} .card-details { background: rgb(8, 49, 14); color: rgb(225, 223, 233); margin: 10px 30px; padding: 10px; /* border-bottom-left-radius: 80px; */} .card-details p { font-size: 15px;} .card-details label { font-size: 15px; line-height: 35px;} .submit-now-btn { cursor: pointer; color: #fff; height: 30px; width: 240px; border: none; margin: 5px 30px; background-color: rgb(71, 177, 61);} Final Code: Combine above two section, will give you final representation of our online payment page. Output: CSS-Properties HTML-Questions HTML-Tags CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n31 Mar, 2021" }, { "code": null, "e": 341, "s": 53, "text": "For anyone who is running an online business, checkout becomes an important part of the selling process to maintain the convenience for online sales and Fast transactions. An appealing User-Interface(UI) will help us in bringing in potential visitors and facilitates the user experience." }, { "code": null, "e": 529, "s": 341, "text": "In this article, we will be creating a payment page for transaction purposes. The simple project is a perfect example of how easily we can make a User Interface design using HTML and CSS." }, { "code": null, "e": 804, "s": 529, "text": "Creating Structure for our web-page: We will be starting out with creating a structural aspect of our website by using simple HTML, and later on, we will style it by using Cascading Style Sheets(CSS), which will be describing the style of our HTML document and its elements." }, { "code": null, "e": 1043, "s": 804, "text": "HTML Code: In this HTML file we have mainly divided our webpage into several <div> tags, and we have use several classes as well like “main-content”, “centre-content”, “last-content” etc. This CSS classes are to stylize our HTML elements." }, { "code": null, "e": 1048, "s": 1043, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"/> <link rel=\"stylesheet\" href=\"style.css\" class=\"css\" /> </head> <body> <div class=\"container\"> <div class=\"main-content\"> <p class=\"text\">GeeksforGeeks</p> </div> <div class=\"centre-content\"> <h1 class=\"price\">2499<span>/-</span></h1> <p class=\"course\"> Buy DSA Self-Paced Course Now ! </p> </div> <div class=\"last-content\"> <button type=\"button\" class=\"pay-now-btn\"> Apply Coupons </button> <button type=\"button\" class=\"pay-now-btn\"> Pay with Netbanking </button> <!-- <button type=\"button\" class=\"pay-now-btn\"> Netbanking options </button> --> </div> <div class=\"card-details\"> <p>Pay using Credit or Debit card</p> <div class=\"card-number\"> <label> Card Number </label> <input type=\"text\" class=\"card-number-field\" placeholder=\"###-###-###\"/> </div> <br /> <div class=\"date-number\"> <label> Expiry Date </label> <input type=\"text\" class=\"date-number-field\" placeholder=\"DD-MM-YY\" /> </div> <div class=\"cvv-number\"> <label> CVV number </label> <input type=\"text\" class=\"cvv-number-field\" placeholder=\"xxx\" /> </div> <div class=\"nameholder-number\"> <label> Card Holder name </label> <input type=\"text\" class=\"card-name-field\" placeholder=\"Enter your Name\"/> </div> <button type=\"submit\" class=\"submit-now-btn\"> submit </button> </div> </div> </body></html>", "e": 2993, "s": 1048, "text": null }, { "code": null, "e": 3518, "s": 2993, "text": "Designing Our Payment Page: Using CSS, we can store all the style information that our page would share. Whenever a user will visit the web page, the browser will load all the related information along with the proper styling related to the contents of the page. In CSS, a class is an element group that is the same or similar. You can have the elements that you want in a class. And each element can be a member of multiple classes. Every class has CSS attributes (like color and font-size) that are specific to that class." }, { "code": null, "e": 3585, "s": 3518, "text": "CSS Code: CSS allows us to create unique and interactive websites." }, { "code": null, "e": 3595, "s": 3585, "text": "style.css" }, { "code": "* { margin: 0; padding: 0;} body { font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif; font-weight: bold;} .container { height: 900px; width: 400px; background-image: linear-gradient(#1e6b30, #308d46); top: 50%; left: 50%; position: absolute; transform: translate(-50%, -50%); position: absolute; border-bottom-left-radius: 180px; border-top-right-radius: 150px;} .main-content { height: 235px; background-color: #1b9236; border-bottom-left-radius: 90px; border-bottom-right-radius: 80px; border-top: #1e6b30;} .text { text-align: center; font-size: 300%; text-decoration: aliceblue; color: aliceblue;} .course { color: black; font-size: 25px; font-weight: bolder;} .centre-content { height: 180px; margin: -70px 30px 20px; color: aliceblue; text-align: center; font-size: 20px; border-radius: 25px; padding-top: 0.5px; background-image: linear-gradient(#1e6b30, #308d46);} .centre-content-h1 { padding-top: 30px; padding-bottom: 30px; font-weight: normal;} .price { font-size: 60px; margin-left: 5px; bottom: 15px; position: relative;} .pay-now-btn { cursor: pointer; color: #fff; height: 50px; width: 290px; border: none; margin: 5px 30px; background-color: rgb(71, 177, 61); position: relative;} .card-details { background: rgb(8, 49, 14); color: rgb(225, 223, 233); margin: 10px 30px; padding: 10px; /* border-bottom-left-radius: 80px; */} .card-details p { font-size: 15px;} .card-details label { font-size: 15px; line-height: 35px;} .submit-now-btn { cursor: pointer; color: #fff; height: 30px; width: 240px; border: none; margin: 5px 30px; background-color: rgb(71, 177, 61);}", "e": 5266, "s": 3595, "text": null }, { "code": null, "e": 5368, "s": 5266, "text": "Final Code: Combine above two section, will give you final representation of our online payment page." }, { "code": null, "e": 5376, "s": 5368, "text": "Output:" }, { "code": null, "e": 5391, "s": 5376, "text": "CSS-Properties" }, { "code": null, "e": 5406, "s": 5391, "text": "HTML-Questions" }, { "code": null, "e": 5416, "s": 5406, "text": "HTML-Tags" }, { "code": null, "e": 5420, "s": 5416, "text": "CSS" }, { "code": null, "e": 5425, "s": 5420, "text": "HTML" }, { "code": null, "e": 5442, "s": 5425, "text": "Web Technologies" }, { "code": null, "e": 5447, "s": 5442, "text": "HTML" } ]