title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How to declare a variable in Python without assigning a value to it?
Python is dynamic, so you don't need to declare things; they exist automatically in the first scope where they're assigned. So, all you need is a regular old assignment statement that assigns None to the variable. my_var = None If you use this, you'll never end up with an uninitialized variable. But this doesn't mean that you won't end up with incorrectly initialized variables. If you init something to None, make sure that's what you really want, and assign something more meaningful when you use it.
[ { "code": null, "e": 1402, "s": 1187, "text": "Python is dynamic, so you don't need to declare things; they exist automatically in the first scope where they're assigned. So, all you need is a regular old assignment statement that assigns None to the variable. " }, { "code": null, "e": 1416, "s": 1402, "text": "my_var = None" }, { "code": null, "e": 1693, "s": 1416, "text": "If you use this, you'll never end up with an uninitialized variable. But this doesn't mean that you won't end up with incorrectly initialized variables. If you init something to None, make sure that's what you really want, and assign something more meaningful when you use it." } ]
HTML <body> bgcolor Attribute
06 Jan, 2022 The HTML <body> bgcolor Attribute is used to define a Background color of a Document. Note: It is not supported by HTML5 Syntax: <body bgcolor="color_name | hex_number | rgb_number"> Attribute Values: color_name: It specifies the name of the Background color of the Document. hex_number: It specifies the hex code of the Background color in the Document. rgb_number: It specifies the rgb value of the Background color in the Document Example: In this example, we simply set the bg color of the body to green. HTML <!DOCTYPE html><html><!-- body tag starts here --> <body bgcolor="green"> <h2>GeeksforGeeks</h2> <p> It is a Computer Science portal For Geeks </p> </body><!-- body tag ends here --> </html> Output: HTML <body> bgcolor Attribute Example: This example describes the HTML <body> bgcolor Attribute by specifying the text as green & background as orange color. HTML <!DOCTYPE html><html> <head> <title> HTML body Bgcolor Attribute </title></head><!-- body tag starts here --> <body text="green" bgcolor="orange"> <center> <h1>GeeksforGeeks</h1> <h2> HTML <body> bgcolor Attribute </h2> <p> It is a Computer Science portal For Geeks </p> </center></body><!-- body tag ends here --> </html> Output: HTML <body> bgcolor Attribute Supported Browsers: Google Chrome Internet Explorer Firefox Safari Opera Microsoft Edge ManasChhabra2 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 Types of CSS (Cascading Style Sheet) Design a Tribute Page using HTML & CSS Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Jan, 2022" }, { "code": null, "e": 114, "s": 28, "text": "The HTML <body> bgcolor Attribute is used to define a Background color of a Document." }, { "code": null, "e": 149, "s": 114, "text": "Note: It is not supported by HTML5" }, { "code": null, "e": 157, "s": 149, "text": "Syntax:" }, { "code": null, "e": 211, "s": 157, "text": "<body bgcolor=\"color_name | hex_number | rgb_number\">" }, { "code": null, "e": 229, "s": 211, "text": "Attribute Values:" }, { "code": null, "e": 304, "s": 229, "text": "color_name: It specifies the name of the Background color of the Document." }, { "code": null, "e": 383, "s": 304, "text": "hex_number: It specifies the hex code of the Background color in the Document." }, { "code": null, "e": 462, "s": 383, "text": "rgb_number: It specifies the rgb value of the Background color in the Document" }, { "code": null, "e": 537, "s": 462, "text": "Example: In this example, we simply set the bg color of the body to green." }, { "code": null, "e": 542, "s": 537, "text": "HTML" }, { "code": "<!DOCTYPE html><html><!-- body tag starts here --> <body bgcolor=\"green\"> <h2>GeeksforGeeks</h2> <p> It is a Computer Science portal For Geeks </p> </body><!-- body tag ends here --> </html>", "e": 744, "s": 542, "text": null }, { "code": null, "e": 752, "s": 744, "text": "Output:" }, { "code": null, "e": 784, "s": 752, "text": " HTML <body> bgcolor Attribute " }, { "code": null, "e": 913, "s": 784, "text": "Example: This example describes the HTML <body> bgcolor Attribute by specifying the text as green & background as orange color." }, { "code": null, "e": 918, "s": 913, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML body Bgcolor Attribute </title></head><!-- body tag starts here --> <body text=\"green\" bgcolor=\"orange\"> <center> <h1>GeeksforGeeks</h1> <h2> HTML <body> bgcolor Attribute </h2> <p> It is a Computer Science portal For Geeks </p> </center></body><!-- body tag ends here --> </html>", "e": 1286, "s": 918, "text": null }, { "code": null, "e": 1294, "s": 1286, "text": "Output:" }, { "code": null, "e": 1326, "s": 1294, "text": " HTML <body> bgcolor Attribute " }, { "code": null, "e": 1346, "s": 1326, "text": "Supported Browsers:" }, { "code": null, "e": 1360, "s": 1346, "text": "Google Chrome" }, { "code": null, "e": 1378, "s": 1360, "text": "Internet Explorer" }, { "code": null, "e": 1386, "s": 1378, "text": "Firefox" }, { "code": null, "e": 1393, "s": 1386, "text": "Safari" }, { "code": null, "e": 1399, "s": 1393, "text": "Opera" }, { "code": null, "e": 1414, "s": 1399, "text": "Microsoft Edge" }, { "code": null, "e": 1428, "s": 1414, "text": "ManasChhabra2" }, { "code": null, "e": 1442, "s": 1428, "text": "shubhamyadav4" }, { "code": null, "e": 1463, "s": 1442, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 1479, "s": 1463, "text": "HTML-Attributes" }, { "code": null, "e": 1484, "s": 1479, "text": "HTML" }, { "code": null, "e": 1501, "s": 1484, "text": "Web Technologies" }, { "code": null, "e": 1506, "s": 1501, "text": "HTML" }, { "code": null, "e": 1604, "s": 1506, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1652, "s": 1604, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 1676, "s": 1652, "text": "REST API (Introduction)" }, { "code": null, "e": 1726, "s": 1676, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 1763, "s": 1726, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 1802, "s": 1763, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 1835, "s": 1802, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1896, "s": 1835, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1939, "s": 1896, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 2011, "s": 1939, "text": "Differences between Functional Components and Class Components in React" } ]
Python | Generate random string of given length
22 May, 2019 The issue of generation of random numbers is quite common, but sometimes, we have applications that require us to better that and provide some functionality of generating a random string of digits and alphabets for applications such as passwords. Let’s discuss certain ways in which this can be performed. Method #1 : Using random.choices() This function of random module can help us achieve this task, and provides a one liner alternative to a whole loop that might be required for this particular task. Works with Python > v3.6 . # Python3 code to demonstrate# generating random strings # using random.choices()import stringimport random # initializing size of string N = 7 # using random.choices()# generating random strings res = ''.join(random.choices(string.ascii_uppercase + string.digits, k = N)) # print resultprint("The generated random string : " + str(res)) The generated random string : 0D5YE91 Method #2 : Using secrets.choice() For Cryptographically more secure random numbers, this function of secret module can be used as it’s internal algorithm is framed in a way to generate less predictable random numbers. Works with Python > v3.6 . # Python3 code to demonstrate# generating random strings # using secrets.choice()import secretsimport string # initializing size of string N = 7 # using random.choices()# generating random strings res = ''.join(secrets.choice(string.ascii_uppercase + string.digits) for i in range(N)) # print resultprint("The generated random string : " + str(res)) The generated random string : T7HPKVR Python string-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 How to Install PIP on Windows ? Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary
[ { "code": null, "e": 53, "s": 25, "text": "\n22 May, 2019" }, { "code": null, "e": 359, "s": 53, "text": "The issue of generation of random numbers is quite common, but sometimes, we have applications that require us to better that and provide some functionality of generating a random string of digits and alphabets for applications such as passwords. Let’s discuss certain ways in which this can be performed." }, { "code": null, "e": 394, "s": 359, "text": "Method #1 : Using random.choices()" }, { "code": null, "e": 585, "s": 394, "text": "This function of random module can help us achieve this task, and provides a one liner alternative to a whole loop that might be required for this particular task. Works with Python > v3.6 ." }, { "code": "# Python3 code to demonstrate# generating random strings # using random.choices()import stringimport random # initializing size of string N = 7 # using random.choices()# generating random strings res = ''.join(random.choices(string.ascii_uppercase + string.digits, k = N)) # print resultprint(\"The generated random string : \" + str(res))", "e": 954, "s": 585, "text": null }, { "code": null, "e": 993, "s": 954, "text": "The generated random string : 0D5YE91\n" }, { "code": null, "e": 1030, "s": 995, "text": "Method #2 : Using secrets.choice()" }, { "code": null, "e": 1241, "s": 1030, "text": "For Cryptographically more secure random numbers, this function of secret module can be used as it’s internal algorithm is framed in a way to generate less predictable random numbers. Works with Python > v3.6 ." }, { "code": "# Python3 code to demonstrate# generating random strings # using secrets.choice()import secretsimport string # initializing size of string N = 7 # using random.choices()# generating random strings res = ''.join(secrets.choice(string.ascii_uppercase + string.digits) for i in range(N)) # print resultprint(\"The generated random string : \" + str(res))", "e": 1643, "s": 1241, "text": null }, { "code": null, "e": 1682, "s": 1643, "text": "The generated random string : T7HPKVR\n" }, { "code": null, "e": 1705, "s": 1682, "text": "Python string-programs" }, { "code": null, "e": 1712, "s": 1705, "text": "Python" }, { "code": null, "e": 1728, "s": 1712, "text": "Python Programs" }, { "code": null, "e": 1826, "s": 1728, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1844, "s": 1826, "text": "Python Dictionary" }, { "code": null, "e": 1886, "s": 1844, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1908, "s": 1886, "text": "Enumerate() in Python" }, { "code": null, "e": 1943, "s": 1908, "text": "Read a file line by line in Python" }, { "code": null, "e": 1975, "s": 1943, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2018, "s": 1975, "text": "Python program to convert a list to string" }, { "code": null, "e": 2040, "s": 2018, "text": "Defaultdict in Python" }, { "code": null, "e": 2079, "s": 2040, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2117, "s": 2079, "text": "Python | Convert a list to dictionary" } ]
Word Wrap problem ( Space optimized solution )
23 Apr, 2021 Given a sequence of words, and a limit on the number of characters that can be put in one line (line width). Put line breaks in the given sequence such that the lines are printed neatly. Assume that the length of each word is smaller than the line width. When line breaks are inserted there is a possibility that extra spaces are present in each line. The extra spaces includes spaces put at the end of every line except the last one. The problem is to minimize the following total cost. Total cost = Sum of cost of all lines, where cost of line is = (Number of extra spaces in the line)^2. For example, consider the following string and line width M = 15 “Geeks for Geeks presents word wrap problem” Following is the optimized arrangement of words in 3 lines Geeks for Geeks presents word wrap problem The total extra spaces in line 1 and line 2 are 0 and 2. Space for line 3 is not considered as it is not extra space as described above. So optimal value of total cost is 0 + 2*2 = 4.Examples: Input format: Input will consists of array of integers where each array element represents length of each word of string. For example, for string S = "Geeks for Geeks", input array will be arr[] = {5, 3, 5}. Output format: Output consists of a series of integers where two consecutive integers represent starting word and ending word of each line. Input : arr[] = {3, 2, 2, 5} Output : 1 1 2 3 4 4 Line number 1: From word no. 1 to 1 Line number 2: From word no. 2 to 3 Line number 3: From word no. 4 to 4 Input : arr[] = {3, 2, 2} Output : 1 1 2 2 3 3 Line number 1: From word no. 1 to 1 Line number 2: From word no. 2 to 2 Line number 3: From word no. 3 to 3 Approach: We have discussed a Dynamic Programming based solution of word wrap problem. The solution discussed used O(n^2) auxiliary space. The auxiliary space used can be reduced to O(n). The idea is to use two 1-D arrays dp[] and ans[], where dp[i] represents minimum cost of the line in which arr[i] is the first word and ans[i] represents index of last word present in line in which word arr[i] is the first word. Let k represents limit on number of characters in each line. Suppose for any line l the first word in that line is at index i in arr[]. The minimum cost of that line is stored in dp[i]. The last word in that line is at index j in arr[], where j can vary from i to n. Iterate over all values of j and keep track of number of characters added so far in line l. If number of characters are less than k then find cost of current line with these number of characters. Compare this cost with minimum cost find so far for this line in dp[i] and update dp[i] and ans[i] accordingly. Repeat above procedure for each value of i, 1 <= i <= n. The starting and ending words of each line will be at index i and index ans[i], where next value of i for line l+1 is ans[i] + 1.Implementation: C++ Java Python 3 C# PHP Javascript // C++ program for space optimized// solution of Word Wrap problem. #include <bits/stdc++.h>using namespace std; // Function to find space optimized// solution of Word Wrap problem.void solveWordWrap(int arr[], int n, int k){ int i, j; // Variable to store number of // characters in given line. int currlen; // Variable to store possible // minimum cost of line. int cost; // DP table in which dp[i] represents // cost of line starting with word // arr[i]. int dp[n]; // Array in which ans[i] store index // of last word in line starting with // word arr[i]. int ans[n]; // If only one word is present then // only one line is required. Cost // of last line is zero. Hence cost // of this line is zero. Ending point // is also n-1 as single word is // present. dp[n - 1] = 0; ans[n - 1] = n - 1; // Make each word first word of line // by iterating over each index in arr. for (i = n - 2; i >= 0; i--) { currlen = -1; dp[i] = INT_MAX; // Keep on adding words in current // line by iterating from starting // word upto last word in arr. for (j = i; j < n; j++) { // Update number of characters // in current line. arr[j] is // number of characters in // current word and 1 // represents space character // between two words. currlen += (arr[j] + 1); // If limit of characters // is violated then no more // words can be added to // current line. if (currlen > k) break; // If current word that is // added to line is last // word of arr then current // line is last line. Cost of // last line is 0. Else cost // is square of extra spaces // plus cost of putting line // breaks in rest of words // from j+1 to n-1. if (j == n - 1) cost = 0; else cost = (k - currlen) * (k - currlen) + dp[j + 1]; // Check if this arrangement gives // minimum cost for line starting // with word arr[i]. if (cost < dp[i]) { dp[i] = cost; ans[i] = j; } } } // Print starting index and ending index // of words present in each line. i = 0; while (i < n) { cout << i + 1 << " " << ans[i] + 1 << " "; i = ans[i] + 1; }} // Driver functionint main(){ int arr[] = { 3, 2, 2, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int M = 6; solveWordWrap(arr, n, M); return 0;} // Java program for space// optimized solution of// Word Wrap problem.import java.io.*; class GFG{ // Function to find space// optimized solution of// Word Wrap problem.static void solveWordWrap(int arr[], int n, int k){ int i, j; // Variable to store // number of characters // in given line. int currlen; // Variable to store // possible minimum // cost of line. int cost; // DP table in which // dp[i] represents // cost of line starting // with word arr[i]. int dp[] = new int[n]; // Array in which ans[i] // store index of last // word in line starting // with word arr[i]. int ans[] = new int[n]; // If only one word is present // then only one line is required. // Cost of last line is zero. // Hence cost of this line is zero. // Ending point is also n-1 as // single word is present. dp[n - 1] = 0; ans[n - 1] = n - 1; // Make each word first // word of line by iterating // over each index in arr. for (i = n - 2; i >= 0; i--) { currlen = -1; dp[i] = Integer.MAX_VALUE; // Keep on adding words in // current line by iterating // from starting word upto // last word in arr. for (j = i; j < n; j++) { // Update number of characters // in current line. arr[j] is // number of characters in // current word and 1 // represents space character // between two words. currlen += (arr[j] + 1); // If limit of characters // is violated then no more // words can be added to // current line. if (currlen > k) break; // If current word that is // added to line is last // word of arr then current // line is last line. Cost of // last line is 0. Else cost // is square of extra spaces // plus cost of putting line // breaks in rest of words // from j+1 to n-1. if (j == n - 1) cost = 0; else cost = (k - currlen) * (k - currlen) + dp[j + 1]; // Check if this arrangement // gives minimum cost for // line starting with word // arr[i]. if (cost < dp[i]) { dp[i] = cost; ans[i] = j; } } } // Print starting index // and ending index of // words present in each line. i = 0; while (i < n) { System.out.print((i + 1) + " " + (ans[i] + 1) + " "); i = ans[i] + 1; }} // Driver Codepublic static void main (String[] args){ int arr[] = {3, 2, 2, 5}; int n = arr.length; int M = 6; solveWordWrap(arr, n, M);}} // This code is contributed// by anuj_67. # Python 3 program for space optimized# solution of Word Wrap problem.import sys # Function to find space optimized# solution of Word Wrap problem.def solveWordWrap(arr, n, k): dp = [0] * n # Array in which ans[i] store index # of last word in line starting with # word arr[i]. ans = [0] * n # If only one word is present then # only one line is required. Cost # of last line is zero. Hence cost # of this line is zero. Ending point # is also n-1 as single word is # present. dp[n - 1] = 0 ans[n - 1] = n - 1 # Make each word first word of line # by iterating over each index in arr. for i in range(n - 2, -1, -1): currlen = -1 dp[i] = sys.maxsize # Keep on adding words in current # line by iterating from starting # word upto last word in arr. for j in range(i, n): # Update number of characters # in current line. arr[j] is # number of characters in # current word and 1 # represents space character # between two words. currlen += (arr[j] + 1) # If limit of characters # is violated then no more # words can be added to # current line. if (currlen > k): break # If current word that is # added to line is last # word of arr then current # line is last line. Cost of # last line is 0. Else cost # is square of extra spaces # plus cost of putting line # breaks in rest of words # from j+1 to n-1. if (j == n - 1): cost = 0 else: cost = ((k - currlen) * (k - currlen) + dp[j + 1]) # Check if this arrangement gives # minimum cost for line starting # with word arr[i]. if (cost < dp[i]): dp[i] = cost ans[i] = j # Print starting index and ending index # of words present in each line. i = 0 while (i < n): print(i + 1 , ans[i] + 1, end = " ") i = ans[i] + 1 # Driver Codeif __name__ == "__main__": arr = [3, 2, 2, 5 ] n = len(arr) M = 6 solveWordWrap(arr, n, M) # This code is contributed by ita_c // C# program for space// optimized solution of// Word Wrap problem.using System; class GFG{ // Function to find space optimized// solution of Word Wrap problem.public static void solveWordWrap(int[] arr, int n, int k){ int i, j; // Variable to store number of // characters in given line. int currlen; // Variable to store possible // minimum cost of line. int cost; // DP table in which dp[i] // represents cost of line // starting with word arr[i]. int[] dp = new int[n]; // Array in which ans[i] store // index of last word in line // starting with word arr[i]. int[] ans = new int[n]; // If only one word is present // then only one line is required. // Cost of last line is zero. // Hence cost of this line is zero. // Ending point is also n-1 as // single word is present. dp[n - 1] = 0; ans[n - 1] = n - 1; // Make each word first // word of line by iterating // over each index in arr. for (i = n - 2; i >= 0; i--) { currlen = -1; dp[i] = int.MaxValue; // Keep on adding words in // current line by iterating // from starting word upto // last word in arr. for (j = i; j < n; j++) { // Update number of characters // in current line. arr[j] is // number of characters in // current word and 1 // represents space character // between two words. currlen += (arr[j] + 1); // If limit of characters // is violated then no more // words can be added to // current line. if (currlen > k) { break; } // If current word that is // added to line is last // word of arr then current // line is last line. Cost of // last line is 0. Else cost // is square of extra spaces // plus cost of putting line // breaks in rest of words // from j+1 to n-1. if (j == n - 1) { cost = 0; } else { cost = (k - currlen) * (k - currlen) + dp[j + 1]; } // Check if this arrangement // gives minimum cost for // line starting with word // arr[i]. if (cost < dp[i]) { dp[i] = cost; ans[i] = j; } } } // Print starting index // and ending index of // words present in each line. i = 0; while (i < n) { Console.Write((i + 1) + " " + (ans[i] + 1) + " "); i = ans[i] + 1; }} // Driver Codepublic static void Main(string[] args){ int[] arr = new int[] {3, 2, 2, 5}; int n = arr.Length; int M = 6; solveWordWrap(arr, n, M);}} // This code is contributed// by Shrikant13 <?php// PHP program for space optimized// solution of Word Wrap problem. // Function to find space optimized// solution of Word Wrap problem.function solveWordWrap($arr, $n, $k){ // Variable to store number of // characters in given line. $currlen; // Variable to store possible // minimum cost of line. $cost; // DP table in which dp[i] represents // cost of line starting with word // arr[i]. $dp = array(); // Array in which ans[i] store index // of last word in line starting with // word arr[i]. $ans = array(); // If only one word is present then // only one line is required. Cost // of last line is zero. Hence cost // of this line is zero. Ending point // is also n-1 as single word is // present. $dp[$n - 1] = 0; $ans[$n - 1] = $n - 1; // Make each word first word of line // by iterating over each index in arr. for ($i = $n - 2; $i >= 0; $i--) { $currlen = -1; $dp[$i] = PHP_INT_MAX; // Keep on adding words in current // line by iterating from starting // word upto last word in arr. for ($j = $i; $j < $n; $j++) { // Update number of characters // in current line. arr[j] is // number of characters in // current word and 1 // represents space character // between two words. $currlen += ($arr[$j] + 1); // If limit of characters // is violated then no more // words can be added to // current line. if ($currlen > $k) break; // If current word that is // added to line is last // word of arr then current // line is last line. Cost of // last line is 0. Else cost // is square of extra spaces // plus cost of putting line // breaks in rest of words // from j+1 to n-1. if ($j == $n - 1) $cost = 0; else $cost = ($k - $currlen) * ($k - $currlen) + $dp[$j + 1]; // Check if this arrangement gives // minimum cost for line starting // with word arr[i]. if ($cost < $dp[$i]) { $dp[$i] = $cost; $ans[$i] = $j; } } } // Print starting index and ending index // of words present in each line. $i = 0; while ($i < $n) { echo ($i + 1) . " " . ($ans[$i] + 1) . " "; $i = $ans[$i] + 1; }} // Driver function$arr = array(3, 2, 2, 5);$n = sizeof($arr);$M = 6;solveWordWrap($arr, $n, $M); // This code is contributed// by Akanksha Rai?> <script>// Javascript program for space optimized// solution of Word Wrap problem. // Function to find space optimized// solution of Word Wrap problem.function solveWordWrap(arr, n, k){ var i, j; // Variable to store number of // characters in given line. var currlen; // Variable to store possible // minimum cost of line. var cost; // DP table in which dp[i] represents // cost of line starting with word // arr[i]. var dp = Array(n); // Array in which ans[i] store index // of last word in line starting with // word arr[i]. var ans = Array(n); // If only one word is present then // only one line is required. Cost // of last line is zero. Hence cost // of this line is zero. Ending point // is also n-1 as single word is // present. dp[n - 1] = 0; ans[n - 1] = n - 1; // Make each word first word of line // by iterating over each index in arr. for (i = n - 2; i >= 0; i--) { currlen = -1; dp[i] = 1000000000; // Keep on adding words in current // line by iterating from starting // word upto last word in arr. for (j = i; j < n; j++) { // Update number of characters // in current line. arr[j] is // number of characters in // current word and 1 // represents space character // between two words. currlen += (arr[j] + 1); // If limit of characters // is violated then no more // words can be added to // current line. if (currlen > k) break; // If current word that is // added to line is last // word of arr then current // line is last line. Cost of // last line is 0. Else cost // is square of extra spaces // plus cost of putting line // breaks in rest of words // from j+1 to n-1. if (j == n - 1) cost = 0; else cost = (k - currlen) * (k - currlen) + dp[j + 1]; // Check if this arrangement gives // minimum cost for line starting // with word arr[i]. if (cost < dp[i]) { dp[i] = cost; ans[i] = j; } } } // Print starting index and ending index // of words present in each line. i = 0; while (i < n) { document.write( i + 1 + " " + (ans[i] + 1) + " "); i = ans[i] + 1; }} // Driver functionvar arr = [ 3, 2, 2, 5 ];var n = arr.length;var M = 6;solveWordWrap(arr, n, M); // This code is contributed by itsok.</script> 1 1 2 3 4 4 Time Complexity: O(n^2) Auxiliary Space: O(n) vt_m shrikanth13 ukasp Akanksha_Rai itsok Dynamic Programming Strings Strings Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Largest Sum Contiguous Subarray Program for Fibonacci numbers 0-1 Knapsack Problem | DP-10 Longest Common Subsequence | DP-4 Subset Sum Problem | DP-25 Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Different Methods to Reverse a String in C++
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Apr, 2021" }, { "code": null, "e": 1051, "s": 54, "text": "Given a sequence of words, and a limit on the number of characters that can be put in one line (line width). Put line breaks in the given sequence such that the lines are printed neatly. Assume that the length of each word is smaller than the line width. When line breaks are inserted there is a possibility that extra spaces are present in each line. The extra spaces includes spaces put at the end of every line except the last one. The problem is to minimize the following total cost. Total cost = Sum of cost of all lines, where cost of line is = (Number of extra spaces in the line)^2. For example, consider the following string and line width M = 15 “Geeks for Geeks presents word wrap problem” Following is the optimized arrangement of words in 3 lines Geeks for Geeks presents word wrap problem The total extra spaces in line 1 and line 2 are 0 and 2. Space for line 3 is not considered as it is not extra space as described above. So optimal value of total cost is 0 + 2*2 = 4.Examples: " }, { "code": null, "e": 1717, "s": 1051, "text": "Input format: Input will consists of array of integers where each array element represents length of each word of string. For example, for string S = \"Geeks for Geeks\", input array will be arr[] = {5, 3, 5}.\nOutput format: Output consists of a series of integers where two consecutive integers represent \nstarting word and ending word of each line.\n\nInput : arr[] = {3, 2, 2, 5}\nOutput : 1 1 2 3 4 4\nLine number 1: From word no. 1 to 1\nLine number 2: From word no. 2 to 3\nLine number 3: From word no. 4 to 4 \n\nInput : arr[] = {3, 2, 2}\nOutput : 1 1 2 2 3 3\nLine number 1: From word no. 1 to 1\nLine number 2: From word no. 2 to 2\nLine number 3: From word no. 3 to 3 " }, { "code": null, "e": 2915, "s": 1719, "text": "Approach: We have discussed a Dynamic Programming based solution of word wrap problem. The solution discussed used O(n^2) auxiliary space. The auxiliary space used can be reduced to O(n). The idea is to use two 1-D arrays dp[] and ans[], where dp[i] represents minimum cost of the line in which arr[i] is the first word and ans[i] represents index of last word present in line in which word arr[i] is the first word. Let k represents limit on number of characters in each line. Suppose for any line l the first word in that line is at index i in arr[]. The minimum cost of that line is stored in dp[i]. The last word in that line is at index j in arr[], where j can vary from i to n. Iterate over all values of j and keep track of number of characters added so far in line l. If number of characters are less than k then find cost of current line with these number of characters. Compare this cost with minimum cost find so far for this line in dp[i] and update dp[i] and ans[i] accordingly. Repeat above procedure for each value of i, 1 <= i <= n. The starting and ending words of each line will be at index i and index ans[i], where next value of i for line l+1 is ans[i] + 1.Implementation: " }, { "code": null, "e": 2919, "s": 2915, "text": "C++" }, { "code": null, "e": 2924, "s": 2919, "text": "Java" }, { "code": null, "e": 2933, "s": 2924, "text": "Python 3" }, { "code": null, "e": 2936, "s": 2933, "text": "C#" }, { "code": null, "e": 2940, "s": 2936, "text": "PHP" }, { "code": null, "e": 2951, "s": 2940, "text": "Javascript" }, { "code": "// C++ program for space optimized// solution of Word Wrap problem. #include <bits/stdc++.h>using namespace std; // Function to find space optimized// solution of Word Wrap problem.void solveWordWrap(int arr[], int n, int k){ int i, j; // Variable to store number of // characters in given line. int currlen; // Variable to store possible // minimum cost of line. int cost; // DP table in which dp[i] represents // cost of line starting with word // arr[i]. int dp[n]; // Array in which ans[i] store index // of last word in line starting with // word arr[i]. int ans[n]; // If only one word is present then // only one line is required. Cost // of last line is zero. Hence cost // of this line is zero. Ending point // is also n-1 as single word is // present. dp[n - 1] = 0; ans[n - 1] = n - 1; // Make each word first word of line // by iterating over each index in arr. for (i = n - 2; i >= 0; i--) { currlen = -1; dp[i] = INT_MAX; // Keep on adding words in current // line by iterating from starting // word upto last word in arr. for (j = i; j < n; j++) { // Update number of characters // in current line. arr[j] is // number of characters in // current word and 1 // represents space character // between two words. currlen += (arr[j] + 1); // If limit of characters // is violated then no more // words can be added to // current line. if (currlen > k) break; // If current word that is // added to line is last // word of arr then current // line is last line. Cost of // last line is 0. Else cost // is square of extra spaces // plus cost of putting line // breaks in rest of words // from j+1 to n-1. if (j == n - 1) cost = 0; else cost = (k - currlen) * (k - currlen) + dp[j + 1]; // Check if this arrangement gives // minimum cost for line starting // with word arr[i]. if (cost < dp[i]) { dp[i] = cost; ans[i] = j; } } } // Print starting index and ending index // of words present in each line. i = 0; while (i < n) { cout << i + 1 << \" \" << ans[i] + 1 << \" \"; i = ans[i] + 1; }} // Driver functionint main(){ int arr[] = { 3, 2, 2, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int M = 6; solveWordWrap(arr, n, M); return 0;}", "e": 5661, "s": 2951, "text": null }, { "code": "// Java program for space// optimized solution of// Word Wrap problem.import java.io.*; class GFG{ // Function to find space// optimized solution of// Word Wrap problem.static void solveWordWrap(int arr[], int n, int k){ int i, j; // Variable to store // number of characters // in given line. int currlen; // Variable to store // possible minimum // cost of line. int cost; // DP table in which // dp[i] represents // cost of line starting // with word arr[i]. int dp[] = new int[n]; // Array in which ans[i] // store index of last // word in line starting // with word arr[i]. int ans[] = new int[n]; // If only one word is present // then only one line is required. // Cost of last line is zero. // Hence cost of this line is zero. // Ending point is also n-1 as // single word is present. dp[n - 1] = 0; ans[n - 1] = n - 1; // Make each word first // word of line by iterating // over each index in arr. for (i = n - 2; i >= 0; i--) { currlen = -1; dp[i] = Integer.MAX_VALUE; // Keep on adding words in // current line by iterating // from starting word upto // last word in arr. for (j = i; j < n; j++) { // Update number of characters // in current line. arr[j] is // number of characters in // current word and 1 // represents space character // between two words. currlen += (arr[j] + 1); // If limit of characters // is violated then no more // words can be added to // current line. if (currlen > k) break; // If current word that is // added to line is last // word of arr then current // line is last line. Cost of // last line is 0. Else cost // is square of extra spaces // plus cost of putting line // breaks in rest of words // from j+1 to n-1. if (j == n - 1) cost = 0; else cost = (k - currlen) * (k - currlen) + dp[j + 1]; // Check if this arrangement // gives minimum cost for // line starting with word // arr[i]. if (cost < dp[i]) { dp[i] = cost; ans[i] = j; } } } // Print starting index // and ending index of // words present in each line. i = 0; while (i < n) { System.out.print((i + 1) + \" \" + (ans[i] + 1) + \" \"); i = ans[i] + 1; }} // Driver Codepublic static void main (String[] args){ int arr[] = {3, 2, 2, 5}; int n = arr.length; int M = 6; solveWordWrap(arr, n, M);}} // This code is contributed// by anuj_67.", "e": 8627, "s": 5661, "text": null }, { "code": "# Python 3 program for space optimized# solution of Word Wrap problem.import sys # Function to find space optimized# solution of Word Wrap problem.def solveWordWrap(arr, n, k): dp = [0] * n # Array in which ans[i] store index # of last word in line starting with # word arr[i]. ans = [0] * n # If only one word is present then # only one line is required. Cost # of last line is zero. Hence cost # of this line is zero. Ending point # is also n-1 as single word is # present. dp[n - 1] = 0 ans[n - 1] = n - 1 # Make each word first word of line # by iterating over each index in arr. for i in range(n - 2, -1, -1): currlen = -1 dp[i] = sys.maxsize # Keep on adding words in current # line by iterating from starting # word upto last word in arr. for j in range(i, n): # Update number of characters # in current line. arr[j] is # number of characters in # current word and 1 # represents space character # between two words. currlen += (arr[j] + 1) # If limit of characters # is violated then no more # words can be added to # current line. if (currlen > k): break # If current word that is # added to line is last # word of arr then current # line is last line. Cost of # last line is 0. Else cost # is square of extra spaces # plus cost of putting line # breaks in rest of words # from j+1 to n-1. if (j == n - 1): cost = 0 else: cost = ((k - currlen) * (k - currlen) + dp[j + 1]) # Check if this arrangement gives # minimum cost for line starting # with word arr[i]. if (cost < dp[i]): dp[i] = cost ans[i] = j # Print starting index and ending index # of words present in each line. i = 0 while (i < n): print(i + 1 , ans[i] + 1, end = \" \") i = ans[i] + 1 # Driver Codeif __name__ == \"__main__\": arr = [3, 2, 2, 5 ] n = len(arr) M = 6 solveWordWrap(arr, n, M) # This code is contributed by ita_c", "e": 10963, "s": 8627, "text": null }, { "code": "// C# program for space// optimized solution of// Word Wrap problem.using System; class GFG{ // Function to find space optimized// solution of Word Wrap problem.public static void solveWordWrap(int[] arr, int n, int k){ int i, j; // Variable to store number of // characters in given line. int currlen; // Variable to store possible // minimum cost of line. int cost; // DP table in which dp[i] // represents cost of line // starting with word arr[i]. int[] dp = new int[n]; // Array in which ans[i] store // index of last word in line // starting with word arr[i]. int[] ans = new int[n]; // If only one word is present // then only one line is required. // Cost of last line is zero. // Hence cost of this line is zero. // Ending point is also n-1 as // single word is present. dp[n - 1] = 0; ans[n - 1] = n - 1; // Make each word first // word of line by iterating // over each index in arr. for (i = n - 2; i >= 0; i--) { currlen = -1; dp[i] = int.MaxValue; // Keep on adding words in // current line by iterating // from starting word upto // last word in arr. for (j = i; j < n; j++) { // Update number of characters // in current line. arr[j] is // number of characters in // current word and 1 // represents space character // between two words. currlen += (arr[j] + 1); // If limit of characters // is violated then no more // words can be added to // current line. if (currlen > k) { break; } // If current word that is // added to line is last // word of arr then current // line is last line. Cost of // last line is 0. Else cost // is square of extra spaces // plus cost of putting line // breaks in rest of words // from j+1 to n-1. if (j == n - 1) { cost = 0; } else { cost = (k - currlen) * (k - currlen) + dp[j + 1]; } // Check if this arrangement // gives minimum cost for // line starting with word // arr[i]. if (cost < dp[i]) { dp[i] = cost; ans[i] = j; } } } // Print starting index // and ending index of // words present in each line. i = 0; while (i < n) { Console.Write((i + 1) + \" \" + (ans[i] + 1) + \" \"); i = ans[i] + 1; }} // Driver Codepublic static void Main(string[] args){ int[] arr = new int[] {3, 2, 2, 5}; int n = arr.Length; int M = 6; solveWordWrap(arr, n, M);}} // This code is contributed// by Shrikant13", "e": 13963, "s": 10963, "text": null }, { "code": "<?php// PHP program for space optimized// solution of Word Wrap problem. // Function to find space optimized// solution of Word Wrap problem.function solveWordWrap($arr, $n, $k){ // Variable to store number of // characters in given line. $currlen; // Variable to store possible // minimum cost of line. $cost; // DP table in which dp[i] represents // cost of line starting with word // arr[i]. $dp = array(); // Array in which ans[i] store index // of last word in line starting with // word arr[i]. $ans = array(); // If only one word is present then // only one line is required. Cost // of last line is zero. Hence cost // of this line is zero. Ending point // is also n-1 as single word is // present. $dp[$n - 1] = 0; $ans[$n - 1] = $n - 1; // Make each word first word of line // by iterating over each index in arr. for ($i = $n - 2; $i >= 0; $i--) { $currlen = -1; $dp[$i] = PHP_INT_MAX; // Keep on adding words in current // line by iterating from starting // word upto last word in arr. for ($j = $i; $j < $n; $j++) { // Update number of characters // in current line. arr[j] is // number of characters in // current word and 1 // represents space character // between two words. $currlen += ($arr[$j] + 1); // If limit of characters // is violated then no more // words can be added to // current line. if ($currlen > $k) break; // If current word that is // added to line is last // word of arr then current // line is last line. Cost of // last line is 0. Else cost // is square of extra spaces // plus cost of putting line // breaks in rest of words // from j+1 to n-1. if ($j == $n - 1) $cost = 0; else $cost = ($k - $currlen) * ($k - $currlen) + $dp[$j + 1]; // Check if this arrangement gives // minimum cost for line starting // with word arr[i]. if ($cost < $dp[$i]) { $dp[$i] = $cost; $ans[$i] = $j; } } } // Print starting index and ending index // of words present in each line. $i = 0; while ($i < $n) { echo ($i + 1) . \" \" . ($ans[$i] + 1) . \" \"; $i = $ans[$i] + 1; }} // Driver function$arr = array(3, 2, 2, 5);$n = sizeof($arr);$M = 6;solveWordWrap($arr, $n, $M); // This code is contributed// by Akanksha Rai?>", "e": 16712, "s": 13963, "text": null }, { "code": "<script>// Javascript program for space optimized// solution of Word Wrap problem. // Function to find space optimized// solution of Word Wrap problem.function solveWordWrap(arr, n, k){ var i, j; // Variable to store number of // characters in given line. var currlen; // Variable to store possible // minimum cost of line. var cost; // DP table in which dp[i] represents // cost of line starting with word // arr[i]. var dp = Array(n); // Array in which ans[i] store index // of last word in line starting with // word arr[i]. var ans = Array(n); // If only one word is present then // only one line is required. Cost // of last line is zero. Hence cost // of this line is zero. Ending point // is also n-1 as single word is // present. dp[n - 1] = 0; ans[n - 1] = n - 1; // Make each word first word of line // by iterating over each index in arr. for (i = n - 2; i >= 0; i--) { currlen = -1; dp[i] = 1000000000; // Keep on adding words in current // line by iterating from starting // word upto last word in arr. for (j = i; j < n; j++) { // Update number of characters // in current line. arr[j] is // number of characters in // current word and 1 // represents space character // between two words. currlen += (arr[j] + 1); // If limit of characters // is violated then no more // words can be added to // current line. if (currlen > k) break; // If current word that is // added to line is last // word of arr then current // line is last line. Cost of // last line is 0. Else cost // is square of extra spaces // plus cost of putting line // breaks in rest of words // from j+1 to n-1. if (j == n - 1) cost = 0; else cost = (k - currlen) * (k - currlen) + dp[j + 1]; // Check if this arrangement gives // minimum cost for line starting // with word arr[i]. if (cost < dp[i]) { dp[i] = cost; ans[i] = j; } } } // Print starting index and ending index // of words present in each line. i = 0; while (i < n) { document.write( i + 1 + \" \" + (ans[i] + 1) + \" \"); i = ans[i] + 1; }} // Driver functionvar arr = [ 3, 2, 2, 5 ];var n = arr.length;var M = 6;solveWordWrap(arr, n, M); // This code is contributed by itsok.</script>", "e": 19408, "s": 16712, "text": null }, { "code": null, "e": 19420, "s": 19408, "text": "1 1 2 3 4 4" }, { "code": null, "e": 19469, "s": 19422, "text": "Time Complexity: O(n^2) Auxiliary Space: O(n) " }, { "code": null, "e": 19474, "s": 19469, "text": "vt_m" }, { "code": null, "e": 19486, "s": 19474, "text": "shrikanth13" }, { "code": null, "e": 19492, "s": 19486, "text": "ukasp" }, { "code": null, "e": 19505, "s": 19492, "text": "Akanksha_Rai" }, { "code": null, "e": 19511, "s": 19505, "text": "itsok" }, { "code": null, "e": 19531, "s": 19511, "text": "Dynamic Programming" }, { "code": null, "e": 19539, "s": 19531, "text": "Strings" }, { "code": null, "e": 19547, "s": 19539, "text": "Strings" }, { "code": null, "e": 19567, "s": 19547, "text": "Dynamic Programming" }, { "code": null, "e": 19665, "s": 19567, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 19697, "s": 19665, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 19727, "s": 19697, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 19756, "s": 19727, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 19790, "s": 19756, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 19817, "s": 19790, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 19863, "s": 19817, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 19888, "s": 19863, "text": "Reverse a string in Java" }, { "code": null, "e": 19948, "s": 19888, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 19963, "s": 19948, "text": "C++ Data Types" } ]
Android progress notifications in Kotlin
29 Dec, 2019 In this tutorial you’ll learn how to create a basic Progress Notification (Indeterminate progress indicator and Fixed-duration progress indicator) for Android using Kotlin. Before we begin, let us first understand the components of a Notification in Android. Small Icon – Required, can be set with setSmallIcon().Application Name – Provided by the system.Time Stamp – Provided by the system but can be overridden.Large Icon – Optional, can be set with setLargeIcon().Title – Optional, can be set with setContentTitle().Text – Optional, can be set with setContentText(). Small Icon – Required, can be set with setSmallIcon(). Application Name – Provided by the system. Time Stamp – Provided by the system but can be overridden. Large Icon – Optional, can be set with setLargeIcon(). Title – Optional, can be set with setContentTitle(). Text – Optional, can be set with setContentText(). Note : Notification ChannelsSince the introduction of Android version 8 (Android Oreo), it is now compulsory to categorize all the notifications into categories called ‘channels’, this is for the convenience of users and also developers.The image below shows us a notification channel named ‘Progress Notification’. Since we only need to create a channel once, we’ll use a helper class ‘App.kt’ to get the job done. package com.gfg.progressnotificationdemo import android.app.Applicationimport android.app.NotificationChannelimport android.app.NotificationManagerimport android.os.Build class App : Application(){ val channelId = "Progress Notification" as String override fun onCreate(){ super.onCreate() createNotificationChannels() } //Check if the Android version is greater than 8. (Android Oreo) private fun createNotificationChannels(){ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channel1 = NotificationChannel( channelId, "Progress Notification", //IMPORTANCE_HIGH = shows a notification as peek notification. //IMPORTANCE_LOW = shows the notification in the status bar. NotificationManager.IMPORTANCE_HIGH ) channel1.description = "Progress Notification Channel" val manager = getSystemService( NotificationManager::class.java ) manager.createNotificationChannel(channel1) } }} Now, in the main activity we'll use a thread to invoke the notification. package com.gfg.progressnotificationdemo import android.app.PendingIntentimport android.content.Intentimport android.os.Bundleimport android.os.SystemClockimport android.view.Viewimport androidx.appcompat.app.AppCompatActivityimport androidx.core.app.NotificationCompatimport androidx.core.app.NotificationManagerCompatimport com.gfg.progressnotificationdemo.R.drawable class MainActivity : AppCompatActivity(){ private lateinit var notificationManager: NotificationManagerCompat val channelId = "Progress Notification" as String override fun onCreate(savedInstanceState: Bundle?){ super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //Create a Notification Manager notificationManager = NotificationManagerCompat.from(this) } //Start() is called when the buttons is pressed. public fun start(view: View){ val intent = Intent(this, MainActivity::class.java).apply{ flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK } val pendingIntent: PendingIntent = PendingIntent.getActivity( this, 0, intent, 0) //Sets the maximum progress as 100 val progressMax = 100 //Creating a notification and setting its various attributes val notification = NotificationCompat.Builder(this, channelId) .setSmallIcon(drawable.ic_file_download) .setContentTitle("GeeksforGeeks") .setContentText("Downloading") .setPriority(NotificationCompat.PRIORITY_LOW) .setOngoing(true) .setOnlyAlertOnce(true) .setProgress(progressMax, 0, true) .setContentIntent(pendingIntent) .setAutoCancel(true) //Initial Alert notificationManager.notify(1, notification.build()) Thread(Runnable{ SystemClock.sleep(2000) var progress = 0 while (progress <= progressMax) { SystemClock.sleep( 1000 ) progress += 20 //Use this to make it a Fixed-duration progress indicator notification //notification.setContentText(progress.toString()+"%") //.setProgress(progressMax, progress, false) //notificationManager.notify(1, notification.build()) } notification.setContentText("Download complete") .setProgress(0, 0, false) .setOngoing(false) notificationManager.notify(1, notification.build()) }).start() }} Layout consists of a single button. <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" android:orientation="vertical"> <Button android:layout_width="wrap_content" android:layout_height="75dp" android:onClick="start" android:text="Show Notification" android:textSize="22sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> Fixed-duration progress indicator : (after adding code in comments at line 67 of MainActivity.kt) Indeterminate progress indicator : After Download : That’s how easy and simple it is to add progress indicator to a notification in Android using Kotlin. Kotlin Android Picked Kotlin Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android RecyclerView in Kotlin Broadcast Receiver in Android With Example How to Communicate Between Fragments in Android? Content Providers in Android with Example Retrofit with Kotlin Coroutine in Android Kotlin constructor Kotlin Setters and Getters How to Add and Customize Back Button of Action Bar in Android? Kotlin Higher-Order Functions
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Dec, 2019" }, { "code": null, "e": 201, "s": 28, "text": "In this tutorial you’ll learn how to create a basic Progress Notification (Indeterminate progress indicator and Fixed-duration progress indicator) for Android using Kotlin." }, { "code": null, "e": 287, "s": 201, "text": "Before we begin, let us first understand the components of a Notification in Android." }, { "code": null, "e": 598, "s": 287, "text": "Small Icon – Required, can be set with setSmallIcon().Application Name – Provided by the system.Time Stamp – Provided by the system but can be overridden.Large Icon – Optional, can be set with setLargeIcon().Title – Optional, can be set with setContentTitle().Text – Optional, can be set with setContentText()." }, { "code": null, "e": 653, "s": 598, "text": "Small Icon – Required, can be set with setSmallIcon()." }, { "code": null, "e": 696, "s": 653, "text": "Application Name – Provided by the system." }, { "code": null, "e": 755, "s": 696, "text": "Time Stamp – Provided by the system but can be overridden." }, { "code": null, "e": 810, "s": 755, "text": "Large Icon – Optional, can be set with setLargeIcon()." }, { "code": null, "e": 863, "s": 810, "text": "Title – Optional, can be set with setContentTitle()." }, { "code": null, "e": 914, "s": 863, "text": "Text – Optional, can be set with setContentText()." }, { "code": null, "e": 1230, "s": 914, "text": "Note : Notification ChannelsSince the introduction of Android version 8 (Android Oreo), it is now compulsory to categorize all the notifications into categories called ‘channels’, this is for the convenience of users and also developers.The image below shows us a notification channel named ‘Progress Notification’." }, { "code": null, "e": 1330, "s": 1230, "text": "Since we only need to create a channel once, we’ll use a helper class ‘App.kt’ to get the job done." }, { "code": "package com.gfg.progressnotificationdemo import android.app.Applicationimport android.app.NotificationChannelimport android.app.NotificationManagerimport android.os.Build class App : Application(){ val channelId = \"Progress Notification\" as String override fun onCreate(){ super.onCreate() createNotificationChannels() } //Check if the Android version is greater than 8. (Android Oreo) private fun createNotificationChannels(){ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channel1 = NotificationChannel( channelId, \"Progress Notification\", //IMPORTANCE_HIGH = shows a notification as peek notification. //IMPORTANCE_LOW = shows the notification in the status bar. NotificationManager.IMPORTANCE_HIGH ) channel1.description = \"Progress Notification Channel\" val manager = getSystemService( NotificationManager::class.java ) manager.createNotificationChannel(channel1) } }}", "e": 2408, "s": 1330, "text": null }, { "code": null, "e": 2481, "s": 2408, "text": "Now, in the main activity we'll use a thread to invoke the notification." }, { "code": "package com.gfg.progressnotificationdemo import android.app.PendingIntentimport android.content.Intentimport android.os.Bundleimport android.os.SystemClockimport android.view.Viewimport androidx.appcompat.app.AppCompatActivityimport androidx.core.app.NotificationCompatimport androidx.core.app.NotificationManagerCompatimport com.gfg.progressnotificationdemo.R.drawable class MainActivity : AppCompatActivity(){ private lateinit var notificationManager: NotificationManagerCompat val channelId = \"Progress Notification\" as String override fun onCreate(savedInstanceState: Bundle?){ super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //Create a Notification Manager notificationManager = NotificationManagerCompat.from(this) } //Start() is called when the buttons is pressed. public fun start(view: View){ val intent = Intent(this, MainActivity::class.java).apply{ flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK } val pendingIntent: PendingIntent = PendingIntent.getActivity( this, 0, intent, 0) //Sets the maximum progress as 100 val progressMax = 100 //Creating a notification and setting its various attributes val notification = NotificationCompat.Builder(this, channelId) .setSmallIcon(drawable.ic_file_download) .setContentTitle(\"GeeksforGeeks\") .setContentText(\"Downloading\") .setPriority(NotificationCompat.PRIORITY_LOW) .setOngoing(true) .setOnlyAlertOnce(true) .setProgress(progressMax, 0, true) .setContentIntent(pendingIntent) .setAutoCancel(true) //Initial Alert notificationManager.notify(1, notification.build()) Thread(Runnable{ SystemClock.sleep(2000) var progress = 0 while (progress <= progressMax) { SystemClock.sleep( 1000 ) progress += 20 //Use this to make it a Fixed-duration progress indicator notification //notification.setContentText(progress.toString()+\"%\") //.setProgress(progressMax, progress, false) //notificationManager.notify(1, notification.build()) } notification.setContentText(\"Download complete\") .setProgress(0, 0, false) .setOngoing(false) notificationManager.notify(1, notification.build()) }).start() }}", "e": 5085, "s": 2481, "text": null }, { "code": null, "e": 5121, "s": 5085, "text": "Layout consists of a single button." }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\" android:orientation=\"vertical\"> <Button android:layout_width=\"wrap_content\" android:layout_height=\"75dp\" android:onClick=\"start\" android:text=\"Show Notification\" android:textSize=\"22sp\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 5984, "s": 5121, "text": null }, { "code": null, "e": 6082, "s": 5984, "text": "Fixed-duration progress indicator : (after adding code in comments at line 67 of MainActivity.kt)" }, { "code": null, "e": 6117, "s": 6082, "text": "Indeterminate progress indicator :" }, { "code": null, "e": 6134, "s": 6117, "text": "After Download :" }, { "code": null, "e": 6236, "s": 6134, "text": "That’s how easy and simple it is to add progress indicator to a notification in Android using Kotlin." }, { "code": null, "e": 6251, "s": 6236, "text": "Kotlin Android" }, { "code": null, "e": 6258, "s": 6251, "text": "Picked" }, { "code": null, "e": 6265, "s": 6258, "text": "Kotlin" }, { "code": null, "e": 6363, "s": 6265, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6432, "s": 6363, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 6463, "s": 6432, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 6506, "s": 6463, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 6555, "s": 6506, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 6597, "s": 6555, "text": "Content Providers in Android with Example" }, { "code": null, "e": 6639, "s": 6597, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 6658, "s": 6639, "text": "Kotlin constructor" }, { "code": null, "e": 6685, "s": 6658, "text": "Kotlin Setters and Getters" }, { "code": null, "e": 6748, "s": 6685, "text": "How to Add and Customize Back Button of Action Bar in Android?" } ]
Print all integers that are sum of powers of two given numbers
09 Jun, 2021 Given three non-negative integers x, y and bound, the task is to print all the powerful integer ? bound in sorted order. A powerful integer is of the form xi + yj for all i, j ? 0. Examples: Input: x = 3, y = 5, bound = 10 Output: 2 4 6 8 10 30 + 50 = 1 + 1 = 2 30 + 51 = 1 + 5 = 6 31 + 50 = 3 + 1 = 4 31 + 51 = 3 + 5 = 8 32 + 50 = 9 + 1 = 10 Input: x = 2, y = 3, bound = 10 Output: 2 3 4 5 7 9 10 Approach: Initialize i = 0 for outer loop and j = 0 for inner loop, if xi = bound then break out of the outer loop (as adding any power of y to it will make it out of the bound). If xi + yj > bound then break out of the inner loop and in every other iteration of the inner loop, save xi + yj in a set to maintain a distinct and sorted list of the powerful integers. Print the contents of the set in the end. To avoid calculating the powers of y again and again, all the powers of y can be pre-calculated and stored in a vector. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to print powerful integersvoid powerfulIntegers(int x, int y, int bound){ // Set is used to store distinct numbers // in sorted order set<int> s; vector<int> powersOfY; int i; // Store all the powers of y < bound in a vector // to avoid calculating them again and again powersOfY.push_back(1); for (i = y; i < bound && y!= 1; i = i * y) powersOfY.push_back(i); i = 0; while (true) { // x^i int xPowI = pow(x, i); for (auto j = powersOfY.begin(); j != powersOfY.end(); ++j) { int num = xPowI + *j; // If num is within limits // insert it into the set if (num <= bound) s.insert(num); // Break out of the inner loop else break; } // Adding any number to it // will be out of bounds if (xPowI >= bound || x == 1) break; // Increment i i++; } // Print the contents of the set set<int>::iterator itr; for (itr = s.begin(); itr != s.end(); itr++) { cout << *itr << " "; }} // Driver codeint main(){ int x = 2, y = 3, bound = 10; // Print powerful integers powerfulIntegers(x, y, bound); return 0;} // Java implementation of the approachimport java.util.*;import java.lang.Math; class GfG{ // Function to print powerful integers static void powerfulIntegers(int x, int y, int bound) { // Set is used to store distinct numbers // in sorted order Set<Integer> s = new HashSet<>(); ArrayList<Integer> powersOfY = new ArrayList<>(); int i; // Store all the powers of y < bound in a vector // to avoid calculating them again and again powersOfY.add(1); for (i = y; i < bound && y != 1; i = i * y) powersOfY.add(i); i = 0; while (true) { // x^i int xPowI = (int)Math.pow((double)x, (double)i); for (int j = 0; j < powersOfY.size(); ++j) { int num = xPowI + powersOfY.get(j); // If num is within limits // insert it into the set if (num <= bound) s.add(num); // Break out of the inner loop else break; } // Adding any number to it // will be out of bounds if (xPowI >= bound || x == 1) break; // Increment i i++; } // Print the contents of the set Iterator itr = s.iterator(); while(itr.hasNext()) { System.out.print(itr.next() + " "); } } // Driver code public static void main(String []args) { int x = 2, y = 1, bound = 10; // Print powerful integers powerfulIntegers(x, y, bound); }} # Python3 implementation of the approach # Function to print powerful integersdef powerfulIntegers(x, y, bound) : # Set is used to store distinct # numbers in sorted order s = set() powersOfY = [] # Store all the powers of y < bound # in a vector to avoid calculating # them again and again powersOfY.append(1) i = y while i < bound and y!=1 : powersOfY.append(i) i *= y i = 0 while (True) : # x^i xPowI = pow(x, i) for j in powersOfY : num = xPowI + j # If num is within limits # insert it into the set if (num <= bound) : s.add(num) # Break out of the inner loop else : break # Adding any number to it # will be out of bounds if (xPowI >= bound or x == 1) : break # Increment i i += 1 # Print the contents of the set for itr in s : print(itr, end = " ") # Driver codeif __name__ == "__main__" : x = 2 y = 3 bound = 10 # Print powerful integers powerfulIntegers(x, y, bound) # This code is contributed by Ryuga // C# implementation of the approachusing System; using System.Linq;using System.Collections.Generic; using System.Collections; class GFG{ // Function to print powerful integersstatic void powerfulIntegers(int x, int y, int bound){ // Set is used to store distinct numbers // in sorted order HashSet<int> s = new HashSet<int>(); ArrayList powersOfY = new ArrayList(); int i; // Store all the powers of y < bound in a vector // to avoid calculating them again and again powersOfY.Add(1); for (i = y; i < bound && y != 1; i = i * y) powersOfY.Add(i); i = 0; while (true) { // x^i int xPowI = (int)Math.Pow(x, i); for (int j = 0; j != powersOfY.Count; ++j) { int num = xPowI + (int)powersOfY[j]; // If num is within limits // insert it into the set if (num <= bound) s.Add(num); // Break out of the inner loop else break; } // Adding any number to it // will be out of bounds if (xPowI >= bound || x == 1) break; // Increment i i++; } int[] ar = s.ToArray(); Array.Sort(ar); s.Clear(); s.UnionWith(ar); // Print the contents of the set foreach (int t in s) { Console.Write( t + " "); }} // Driver codestatic void Main(){ int x = 2, y = 3, bound = 10; // Print powerful integers powerfulIntegers(x, y, bound);}} // This code is contributed by mits <?php// PHP implementation of the approach // Function to print powerful integersfunction powerfulIntegers($x, $y, $bound){ // Set is used to store distinct // numbers in sorted order $s = array(); $powersOfY = array(); // Store all the powers of y < bound // in a vector to avoid calculating // them again and again array_push($powersOfY, 1); $i = $y; while($i < $bound && $y != 1) { array_push($powersOfY, $i); $i *= $y; } $i = 0; while (true) { // x^i $xPowI = pow($x, $i); for ($j = 0; $j < count($powersOfY); $j++) { $num = $xPowI + $powersOfY[$j]; // If num is within limits // insert it into the set if ($num <= $bound) array_push($s, $num); // Break out of the inner loop else break; } // Adding any number to it // will be out of bounds if ($xPowI >= $bound || $x == 1) break; // Increment i $i += 1; } $s = array_unique($s); sort($s); // Print the contents of the set foreach ($s as &$itr) print($itr . " ");} // Driver code$x = 2;$y = 3;$bound = 10; // Print powerful integerspowerfulIntegers($x, $y, $bound); // This code is contributed by chandan_jnu?> <script> // Javascript implementation of the approach // Function to print powerful integersfunction powerfulIntegers(x, y, bound){ // Set is used to store distinct numbers // in sorted order var s = new Set(); var powersOfY = []; var i; // Store all the powers of y < bound in a vector // to avoid calculating them again and again powersOfY.push(1); for(i = y; i < bound && y!= 1; i = i * y) powersOfY.push(i); i = 0; while (true) { // x^i var xPowI = Math.pow(x, i); powersOfY.forEach(j => { var num = xPowI + j; // If num is within limits // insert it into the set if (num <= bound) s.add(num); }); // Adding any number to it // will be out of bounds if (xPowI >= bound || x == 1) break; // Increment i i++; } // Print the contents of the set [...s].sort((a, b) => a - b).forEach(itr => { document.write(itr + " ") });} // Driver codevar x = 2, y = 3, bound = 10; // Print powerful integerspowerfulIntegers(x, y, bound); // This code is contributed by itsok </script> 2 3 4 5 7 9 10 ankthon Chandan_Kumar Mithun Kumar rituraj_jain kumudgupta76 itsok cpp-set maths-power Self-Balancing-BST Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Operators in C / C++ Sieve of Eratosthenes Prime Numbers Minimum number of jumps to reach end Program to find GCD or HCF of two numbers The Knight's tour problem | Backtracking-1 Algorithm to solve Rubik's Cube Find minimum number of coins that make a given value Program for Decimal to Binary Conversion
[ { "code": null, "e": 54, "s": 26, "text": "\n09 Jun, 2021" }, { "code": null, "e": 235, "s": 54, "text": "Given three non-negative integers x, y and bound, the task is to print all the powerful integer ? bound in sorted order. A powerful integer is of the form xi + yj for all i, j ? 0." }, { "code": null, "e": 246, "s": 235, "text": "Examples: " }, { "code": null, "e": 398, "s": 246, "text": "Input: x = 3, y = 5, bound = 10 Output: 2 4 6 8 10 30 + 50 = 1 + 1 = 2 30 + 51 = 1 + 5 = 6 31 + 50 = 3 + 1 = 4 31 + 51 = 3 + 5 = 8 32 + 50 = 9 + 1 = 10" }, { "code": null, "e": 454, "s": 398, "text": "Input: x = 2, y = 3, bound = 10 Output: 2 3 4 5 7 9 10 " }, { "code": null, "e": 982, "s": 454, "text": "Approach: Initialize i = 0 for outer loop and j = 0 for inner loop, if xi = bound then break out of the outer loop (as adding any power of y to it will make it out of the bound). If xi + yj > bound then break out of the inner loop and in every other iteration of the inner loop, save xi + yj in a set to maintain a distinct and sorted list of the powerful integers. Print the contents of the set in the end. To avoid calculating the powers of y again and again, all the powers of y can be pre-calculated and stored in a vector." }, { "code": null, "e": 1035, "s": 982, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1039, "s": 1035, "text": "C++" }, { "code": null, "e": 1044, "s": 1039, "text": "Java" }, { "code": null, "e": 1052, "s": 1044, "text": "Python3" }, { "code": null, "e": 1055, "s": 1052, "text": "C#" }, { "code": null, "e": 1059, "s": 1055, "text": "PHP" }, { "code": null, "e": 1070, "s": 1059, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to print powerful integersvoid powerfulIntegers(int x, int y, int bound){ // Set is used to store distinct numbers // in sorted order set<int> s; vector<int> powersOfY; int i; // Store all the powers of y < bound in a vector // to avoid calculating them again and again powersOfY.push_back(1); for (i = y; i < bound && y!= 1; i = i * y) powersOfY.push_back(i); i = 0; while (true) { // x^i int xPowI = pow(x, i); for (auto j = powersOfY.begin(); j != powersOfY.end(); ++j) { int num = xPowI + *j; // If num is within limits // insert it into the set if (num <= bound) s.insert(num); // Break out of the inner loop else break; } // Adding any number to it // will be out of bounds if (xPowI >= bound || x == 1) break; // Increment i i++; } // Print the contents of the set set<int>::iterator itr; for (itr = s.begin(); itr != s.end(); itr++) { cout << *itr << \" \"; }} // Driver codeint main(){ int x = 2, y = 3, bound = 10; // Print powerful integers powerfulIntegers(x, y, bound); return 0;}", "e": 2447, "s": 1070, "text": null }, { "code": "// Java implementation of the approachimport java.util.*;import java.lang.Math; class GfG{ // Function to print powerful integers static void powerfulIntegers(int x, int y, int bound) { // Set is used to store distinct numbers // in sorted order Set<Integer> s = new HashSet<>(); ArrayList<Integer> powersOfY = new ArrayList<>(); int i; // Store all the powers of y < bound in a vector // to avoid calculating them again and again powersOfY.add(1); for (i = y; i < bound && y != 1; i = i * y) powersOfY.add(i); i = 0; while (true) { // x^i int xPowI = (int)Math.pow((double)x, (double)i); for (int j = 0; j < powersOfY.size(); ++j) { int num = xPowI + powersOfY.get(j); // If num is within limits // insert it into the set if (num <= bound) s.add(num); // Break out of the inner loop else break; } // Adding any number to it // will be out of bounds if (xPowI >= bound || x == 1) break; // Increment i i++; } // Print the contents of the set Iterator itr = s.iterator(); while(itr.hasNext()) { System.out.print(itr.next() + \" \"); } } // Driver code public static void main(String []args) { int x = 2, y = 1, bound = 10; // Print powerful integers powerfulIntegers(x, y, bound); }}", "e": 4166, "s": 2447, "text": null }, { "code": "# Python3 implementation of the approach # Function to print powerful integersdef powerfulIntegers(x, y, bound) : # Set is used to store distinct # numbers in sorted order s = set() powersOfY = [] # Store all the powers of y < bound # in a vector to avoid calculating # them again and again powersOfY.append(1) i = y while i < bound and y!=1 : powersOfY.append(i) i *= y i = 0 while (True) : # x^i xPowI = pow(x, i) for j in powersOfY : num = xPowI + j # If num is within limits # insert it into the set if (num <= bound) : s.add(num) # Break out of the inner loop else : break # Adding any number to it # will be out of bounds if (xPowI >= bound or x == 1) : break # Increment i i += 1 # Print the contents of the set for itr in s : print(itr, end = \" \") # Driver codeif __name__ == \"__main__\" : x = 2 y = 3 bound = 10 # Print powerful integers powerfulIntegers(x, y, bound) # This code is contributed by Ryuga", "e": 5367, "s": 4166, "text": null }, { "code": "// C# implementation of the approachusing System; using System.Linq;using System.Collections.Generic; using System.Collections; class GFG{ // Function to print powerful integersstatic void powerfulIntegers(int x, int y, int bound){ // Set is used to store distinct numbers // in sorted order HashSet<int> s = new HashSet<int>(); ArrayList powersOfY = new ArrayList(); int i; // Store all the powers of y < bound in a vector // to avoid calculating them again and again powersOfY.Add(1); for (i = y; i < bound && y != 1; i = i * y) powersOfY.Add(i); i = 0; while (true) { // x^i int xPowI = (int)Math.Pow(x, i); for (int j = 0; j != powersOfY.Count; ++j) { int num = xPowI + (int)powersOfY[j]; // If num is within limits // insert it into the set if (num <= bound) s.Add(num); // Break out of the inner loop else break; } // Adding any number to it // will be out of bounds if (xPowI >= bound || x == 1) break; // Increment i i++; } int[] ar = s.ToArray(); Array.Sort(ar); s.Clear(); s.UnionWith(ar); // Print the contents of the set foreach (int t in s) { Console.Write( t + \" \"); }} // Driver codestatic void Main(){ int x = 2, y = 3, bound = 10; // Print powerful integers powerfulIntegers(x, y, bound);}} // This code is contributed by mits", "e": 6944, "s": 5367, "text": null }, { "code": "<?php// PHP implementation of the approach // Function to print powerful integersfunction powerfulIntegers($x, $y, $bound){ // Set is used to store distinct // numbers in sorted order $s = array(); $powersOfY = array(); // Store all the powers of y < bound // in a vector to avoid calculating // them again and again array_push($powersOfY, 1); $i = $y; while($i < $bound && $y != 1) { array_push($powersOfY, $i); $i *= $y; } $i = 0; while (true) { // x^i $xPowI = pow($x, $i); for ($j = 0; $j < count($powersOfY); $j++) { $num = $xPowI + $powersOfY[$j]; // If num is within limits // insert it into the set if ($num <= $bound) array_push($s, $num); // Break out of the inner loop else break; } // Adding any number to it // will be out of bounds if ($xPowI >= $bound || $x == 1) break; // Increment i $i += 1; } $s = array_unique($s); sort($s); // Print the contents of the set foreach ($s as &$itr) print($itr . \" \");} // Driver code$x = 2;$y = 3;$bound = 10; // Print powerful integerspowerfulIntegers($x, $y, $bound); // This code is contributed by chandan_jnu?>", "e": 8304, "s": 6944, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to print powerful integersfunction powerfulIntegers(x, y, bound){ // Set is used to store distinct numbers // in sorted order var s = new Set(); var powersOfY = []; var i; // Store all the powers of y < bound in a vector // to avoid calculating them again and again powersOfY.push(1); for(i = y; i < bound && y!= 1; i = i * y) powersOfY.push(i); i = 0; while (true) { // x^i var xPowI = Math.pow(x, i); powersOfY.forEach(j => { var num = xPowI + j; // If num is within limits // insert it into the set if (num <= bound) s.add(num); }); // Adding any number to it // will be out of bounds if (xPowI >= bound || x == 1) break; // Increment i i++; } // Print the contents of the set [...s].sort((a, b) => a - b).forEach(itr => { document.write(itr + \" \") });} // Driver codevar x = 2, y = 3, bound = 10; // Print powerful integerspowerfulIntegers(x, y, bound); // This code is contributed by itsok </script>", "e": 9516, "s": 8304, "text": null }, { "code": null, "e": 9531, "s": 9516, "text": "2 3 4 5 7 9 10" }, { "code": null, "e": 9541, "s": 9533, "text": "ankthon" }, { "code": null, "e": 9555, "s": 9541, "text": "Chandan_Kumar" }, { "code": null, "e": 9568, "s": 9555, "text": "Mithun Kumar" }, { "code": null, "e": 9581, "s": 9568, "text": "rituraj_jain" }, { "code": null, "e": 9594, "s": 9581, "text": "kumudgupta76" }, { "code": null, "e": 9600, "s": 9594, "text": "itsok" }, { "code": null, "e": 9608, "s": 9600, "text": "cpp-set" }, { "code": null, "e": 9620, "s": 9608, "text": "maths-power" }, { "code": null, "e": 9639, "s": 9620, "text": "Self-Balancing-BST" }, { "code": null, "e": 9652, "s": 9639, "text": "Mathematical" }, { "code": null, "e": 9665, "s": 9652, "text": "Mathematical" }, { "code": null, "e": 9763, "s": 9665, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9787, "s": 9763, "text": "Merge two sorted arrays" }, { "code": null, "e": 9808, "s": 9787, "text": "Operators in C / C++" }, { "code": null, "e": 9830, "s": 9808, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 9844, "s": 9830, "text": "Prime Numbers" }, { "code": null, "e": 9881, "s": 9844, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 9923, "s": 9881, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 9966, "s": 9923, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 9998, "s": 9966, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 10051, "s": 9998, "text": "Find minimum number of coins that make a given value" } ]
Machine Learning - Scatter Matrix Plot
Scatter plots shows how much one variable is affected by another or the relationship between them with the help of dots in two dimensions. Scatter plots are very much like line graphs in the concept that they use horizontal and vertical axes to plot data points. In the following example, Python script will generate and plot Scatter matrix for the Pima Indian Diabetes dataset. It can be generated with the help of scatter_matrix() function on Pandas DataFrame and plotted with the help of pyplot. from matplotlib import pyplot from pandas import read_csv from pandas.tools.plotting import scatter_matrix path = r"C:\pima-indians-diabetes.csv" names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class'] data = read_csv(path, names = names)
[ { "code": null, "e": 2701, "s": 2438, "text": "Scatter plots shows how much one variable is affected by another or the relationship between them with the help of dots in two dimensions. Scatter plots are very much like line graphs in the concept that they use horizontal and vertical axes to plot data points." }, { "code": null, "e": 2937, "s": 2701, "text": "In the following example, Python script will generate and plot Scatter matrix for the Pima Indian Diabetes dataset. It can be generated with the help of scatter_matrix() function on Pandas DataFrame and plotted with the help of pyplot." } ]
Matcher matches() method in Java with Examples
26 Nov, 2018 The matches() method of Matcher Class is used to get the result whether this pattern matches with this matcher or not. It returns a boolean value showing the same. Syntax: public boolean matches() Parameters: This method do not takes any parameter. Return Value: This method returns a boolean value showing whether this pattern matches with this matcher or not. Below examples illustrate the Matcher.matches() method: Example 1: // Java code to illustrate matches() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = "Geeks"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = "GeeksForGeeks"; // Create a matcher for the input String Matcher matcher = pattern .matcher(stringToBeMatched); // Get the result state // using matches() method System.out.println("Result: " + matcher.matches()); }} Result: false Example 2: // Java code to illustrate matches() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = "GFG"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = "GFGFGFGFGFGFGFGFGFG"; // Create a matcher for the input String Matcher matcher = pattern .matcher(stringToBeMatched); // Get the result state // using matches() method System.out.println("Result: " + matcher.matches()); }} Result: false Reference: Oracle Doc Java - util package Java-Functions Java-Matcher Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Nov, 2018" }, { "code": null, "e": 192, "s": 28, "text": "The matches() method of Matcher Class is used to get the result whether this pattern matches with this matcher or not. It returns a boolean value showing the same." }, { "code": null, "e": 200, "s": 192, "text": "Syntax:" }, { "code": null, "e": 226, "s": 200, "text": "public boolean matches()\n" }, { "code": null, "e": 278, "s": 226, "text": "Parameters: This method do not takes any parameter." }, { "code": null, "e": 391, "s": 278, "text": "Return Value: This method returns a boolean value showing whether this pattern matches with this matcher or not." }, { "code": null, "e": 447, "s": 391, "text": "Below examples illustrate the Matcher.matches() method:" }, { "code": null, "e": 458, "s": 447, "text": "Example 1:" }, { "code": "// Java code to illustrate matches() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = \"Geeks\"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = \"GeeksForGeeks\"; // Create a matcher for the input String Matcher matcher = pattern .matcher(stringToBeMatched); // Get the result state // using matches() method System.out.println(\"Result: \" + matcher.matches()); }}", "e": 1167, "s": 458, "text": null }, { "code": null, "e": 1182, "s": 1167, "text": "Result: false\n" }, { "code": null, "e": 1193, "s": 1182, "text": "Example 2:" }, { "code": "// Java code to illustrate matches() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = \"GFG\"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = \"GFGFGFGFGFGFGFGFGFG\"; // Create a matcher for the input String Matcher matcher = pattern .matcher(stringToBeMatched); // Get the result state // using matches() method System.out.println(\"Result: \" + matcher.matches()); }}", "e": 1906, "s": 1193, "text": null }, { "code": null, "e": 1921, "s": 1906, "text": "Result: false\n" }, { "code": null, "e": 1943, "s": 1921, "text": "Reference: Oracle Doc" }, { "code": null, "e": 1963, "s": 1943, "text": "Java - util package" }, { "code": null, "e": 1978, "s": 1963, "text": "Java-Functions" }, { "code": null, "e": 1991, "s": 1978, "text": "Java-Matcher" }, { "code": null, "e": 1996, "s": 1991, "text": "Java" }, { "code": null, "e": 2001, "s": 1996, "text": "Java" } ]
Create a Single Page Responsive Website Using Bootstrap
31 Aug, 2021 Everyone wants to create the website which is compatible with all the devices like computer, laptops, tablets, and mobiles. So for making a website responsive the best way is to make a website using Bootstrap. Since it is a single-page website when you click on any menu on the website it will reach you towards a specific section. Code Implementation: HTML Code: In the HTML code, you have to copy the starter template from the bootstrap and just paste it into your HTML file. After that create a navbar. Then you just have to use the grid system of bootstrap, and you will be able to create a simple and responsive website like this. index.html <!DOCTYPE html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous" /> <link rel="stylesheet" href="style.css" /> <link rel="preconnect" href="https://fonts.gstatic.com" /> <link href="https://fonts.googleapis.com/css2?family=Roboto+Condensed&display=swap" rel="stylesheet" /> <title>GFG</title> </head> <body> <section id="navbar"> <nav class="navbar navbar-expand-lg navbar-light"> <div class="container-fluid"> <a class="navbar-brand" href="#"> Geeks for Geeks </a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation" > <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav m-auto"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="#">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#service">Services</a> </li> <li class="nav-item"> <a class="nav-link" href="#about">About Us</a> </li> <li class="nav-item"> <a class="nav-link" href="#product">Products</a> </li> <li class="nav-item"> <a class="nav-link" href="#social">Contact Us</a> </li> </ul> </div> </div> </nav> </section> <!-- banner --> <section id="banner"> <div class="container-fluid" id="banner-container"> <div class="row" id="banner-row"> <div class="col-md-6" id="banner-col"> <h3> BEST PROFESSIONAL WEBSITE DESIGN SOFTWARE DEVELOPMENT COMPANY </h3> <p> The fastest way to grow your business with the leader in Technology </p> <div class="d-grid gap-2 d-md-flex justify-content-center"> <a class="btn btn-primary" href="#" role="button">Contact Us</a> </div> </div> <div class="col-md-6" id="banner-col2"> <img class="img-responsive rounded mx-auto d-block" src="images/gfg.png" alt="" /> </div> </div> </div> </section> <!-- services --> <section id="service"> <h1 class="text-center">SERVICES</h1> <div class="container-fluid" id="service-container"> <div class="row" id="banner-row"> <div class="col-md-4" id="service-col1"> <img src="images/gfg.png" class="img-fluid rounded mx-auto d-block" alt="..." /> <h3>Website Design</h3> <p> User Experience Design. Website Content Strategy. Cross Browser and Platform Testing. </p> </div> <div class="col-md-4" id="service-col2"> <img src="images/gfg.png" class="img-fluid rounded mx-auto d-block" alt="..." /> <h3>Bulk SMS</h3> <p> 1.Toll Free Number 2. IVR 3. Virtual Number 4. Political or any Voice Broadcasting </p> </div> <div class="col-md-4" id="service-col3"> <img src="images/gfg.png" class="img-fluid rounded mx-auto d-block" alt="..." /> <h3>Payment Gateways</h3> <p> PayU India is the flagship company of Naspers group which is a $25 Billion internet and media conglomerate listed on London and Johannesburg stock exchanges respectively. </p> </div> </div> </div> </section> <hr /> <!-- about Us --> <section id="about"> <h1 class="text-center">About Us</h1> <div class="container-fluid" id="about-container"> <div class="row" id="banner-row"> <div class="col-md-6" id="about-col"> <h3>Why Us</h3> <ul> <li> Probuz is all about Delivering High Quality web design and development services, Cost effective and reliable solutions. </li> <li>SCHOOL/COLLEGE MANAGEMENT SOFTWARE (CAMPUS PRO)</li> <li> Let us take care of your Business needs. Customer Productivity is our Priority. </li> <li>Our expertise in Business includes</li> </ul> </div> <div class="col-md-6" id="banner-col2"> <img class="img-responsive rounded mx-auto d-block" src="images/gfg.png" alt="" /> </div> </div> </div> </section> <hr /> <!-- product --> <section id="product"> <h1 class="text-center">Our Products</h1> <div class="container-fluid" id="product-container"> <div class="row" id="banner-row"> <div class="col-md-6" id="about-col"> <img class="img-responsive rounded mx-auto d-block" src="images/gfg.png" alt="" /> </div> <div class="col-md-6" id="product-col2"> <h3>Product List</h3> <ul> <li>CLINIC MANAGMENT SYSTEM</li> <li>SCHOOL/COLLEGE MANAGEMENT SOFTWARE (CAMPUS PRO)</li> <li>SERVICE MANAGEMENT SOFTWARE</li> <li>E-COMMERCE WEBSITE</li> </ul> </div> </div> </div> </section> <hr /> <!-- social --> <section id="social"> <h1 class="text-center">Get In Touch</h1> <div class="d-grid gap-2 d-md-flex justify-content-center"> <div class="row align-items-center" id="social-row"> <div class="col-md-4 social-col"> <a href="" ><img class="img-responsive rounded mx-auto d-block" src="images/gfg.png" alt="" /></a> </div> <div class="col-md-4 social-col"> <a href="" ><img class="img-responsive rounded mx-auto d-block" src="images/icons8-instagram-64.png" alt="" /></a> </div> <div class="col-md-4 social-col"> <a href="" ><img class="img-responsive rounded mx-auto d-block" src="images/icons8-twitter-64.png" alt="" /></a> </div> </div> </div> </section> <!-- footer --> <section id="footer"> <section id="banner"> <div class="container-fluid" id="banner-container"> <div class="row" id="banner-row"> <div class="col-md-4" id="footer-col1"> <h3>My Website</h3> <p> At XYZ we believe that customers should always get easy-to-use, best in the kind and fast services.xyz has achieved standards which helps customer to achieve satisfaction and realize value for their hard earned money. </p> </div> <div class="col-md-4" id="footer-col2"> <h3>Contact Us</h3> <p>Call Us- 1800-121-6532</p> <p>Email Us- [email protected]</p> </div> <div class="col-md-4" id="footer-col2"> <h3>Subscribe To Newsletter</h3> <form> <div class="mb-3"> <input type="email" placeholder="Enter Your Email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" /> <div id="emailHelp" class="form-text"> We'll never share your email with anyone else. </div> </div> <button type="submit" class="btn btn-primary"> Submit </button> </form> </div> </div> </div> </section> </section> <!-- Optional JavaScript; choose one of the two! --> <!-- Option 1: Bootstrap Bundle with Popper --> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-b5kHyXgcpbZJO/tY9Ul7kGkf1S0CWuKcCD38l8YkeH8z8QjE0GmW1gYU5S9FOnJ0" crossorigin="anonymous" ></script> </body></html> CSS CODE: So, as you all know that bootstrap is not enough good for making the website interactive, so added some CSS over here. You can change the navbar background color according to your requirement. style.css *{ margin: 0; padding: 0; font-family: 'Roboto Condensed', sans-serif;} /* navbar */ .navbar-nav{ margin-right: 0 !important; padding-right: 100px;} .navbar{ background-color: #0a193d; color: white !important;} .nav-item a{ color: white !important;} .nav-item{ padding-left: 2px;} .navbar-brand{ color: white !important; padding-left: 100px;} #navbar button{ color: white !important;} /* banner */ #banner-container{ background-color: #0a193d; color: white !important; padding-top: 80px; padding-bottom: 80px; } #banner-row img{ max-width: 70%; height: auto; display: block; padding-left: 30px;} #banner-row h3, p{ padding-left: 20px; padding-top: 20px; text-align: center;} #banner-row a{ background-color: white !important; color: black !important; border: none; margin-left: 20px; margin-top: 20px; }#banner-col{ padding-left: 20px;}/* service */#service{ padding-top: 80px; padding-bottom: 80px;} #service h1{ padding-bottom: 70px;} /* about */ #about{ padding-top: 80px; padding-bottom: 80px;} #about h1{ padding-bottom: 70px;} #about-col ul{ padding-top: 50px; padding-left: 50px;} #about-col ul li{ padding-top: 15px; } /* product */ #product{ padding-top: 80px; padding-bottom: 80px;} #product h1{ padding-bottom: 70px;} #product-col2 ul{ padding-top: 90px;} #product-col2 ul li{ padding-top: 15px;} /* social */ #social{ padding-top: 80px; padding-bottom: 80px;} #social h1{ padding-bottom: 70px;} .social-col a:hover img{ transform: translateY(-10px);} #social-row{ flex-direction: row;} /* footer */ .mb-3{ padding-top: 10px;} /* media */@media only screen and (max-width: 987px){ .navbar-brand{ padding-left: 0px; }} @media only screen and (max-width: 768px){ #banner-row img{ padding-top: 20px; } .social-col{ width: 33%; } } Output: Supported Browser: Google Chrome Microsoft Edge Firefox Opera Safari You can check out this project at the given link – https://saurabhsonewane.github.io/gfg1.github.io/ ysachin2314 Bootstrap-4 Bootstrap-Questions CSS-Properties HTML5 Picked Bootstrap CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Show Images on Click using HTML ? How to Use Bootstrap with React? Tailwind CSS vs Bootstrap How to set vertical alignment in Bootstrap ? How to toggle password visibility in forms using Bootstrap-icons ? How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? CSS to put icon inside an input element in a form
[ { "code": null, "e": 54, "s": 26, "text": "\n31 Aug, 2021" }, { "code": null, "e": 264, "s": 54, "text": "Everyone wants to create the website which is compatible with all the devices like computer, laptops, tablets, and mobiles. So for making a website responsive the best way is to make a website using Bootstrap." }, { "code": null, "e": 386, "s": 264, "text": "Since it is a single-page website when you click on any menu on the website it will reach you towards a specific section." }, { "code": null, "e": 407, "s": 386, "text": "Code Implementation:" }, { "code": null, "e": 418, "s": 407, "text": "HTML Code:" }, { "code": null, "e": 561, "s": 418, "text": "In the HTML code, you have to copy the starter template from the bootstrap and just paste it into your HTML file. After that create a navbar. " }, { "code": null, "e": 692, "s": 561, "text": "Then you just have to use the grid system of bootstrap, and you will be able to create a simple and responsive website like this. " }, { "code": null, "e": 703, "s": 692, "text": "index.html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- Required meta tags --> <meta charset=\"utf-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" /> <!-- Bootstrap CSS --> <link href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css\" rel=\"stylesheet\" integrity=\"sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl\" crossorigin=\"anonymous\" /> <link rel=\"stylesheet\" href=\"style.css\" /> <link rel=\"preconnect\" href=\"https://fonts.gstatic.com\" /> <link href=\"https://fonts.googleapis.com/css2?family=Roboto+Condensed&display=swap\" rel=\"stylesheet\" /> <title>GFG</title> </head> <body> <section id=\"navbar\"> <nav class=\"navbar navbar-expand-lg navbar-light\"> <div class=\"container-fluid\"> <a class=\"navbar-brand\" href=\"#\"> Geeks for Geeks </a> <button class=\"navbar-toggler\" type=\"button\" data-bs-toggle=\"collapse\" data-bs-target=\"#navbarSupportedContent\" aria-controls=\"navbarSupportedContent\" aria-expanded=\"false\" aria-label=\"Toggle navigation\" > <span class=\"navbar-toggler-icon\"></span> </button> <div class=\"collapse navbar-collapse\" id=\"navbarSupportedContent\"> <ul class=\"navbar-nav m-auto\"> <li class=\"nav-item\"> <a class=\"nav-link active\" aria-current=\"page\" href=\"#\">Home</a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#service\">Services</a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#about\">About Us</a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#product\">Products</a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#social\">Contact Us</a> </li> </ul> </div> </div> </nav> </section> <!-- banner --> <section id=\"banner\"> <div class=\"container-fluid\" id=\"banner-container\"> <div class=\"row\" id=\"banner-row\"> <div class=\"col-md-6\" id=\"banner-col\"> <h3> BEST PROFESSIONAL WEBSITE DESIGN SOFTWARE DEVELOPMENT COMPANY </h3> <p> The fastest way to grow your business with the leader in Technology </p> <div class=\"d-grid gap-2 d-md-flex justify-content-center\"> <a class=\"btn btn-primary\" href=\"#\" role=\"button\">Contact Us</a> </div> </div> <div class=\"col-md-6\" id=\"banner-col2\"> <img class=\"img-responsive rounded mx-auto d-block\" src=\"images/gfg.png\" alt=\"\" /> </div> </div> </div> </section> <!-- services --> <section id=\"service\"> <h1 class=\"text-center\">SERVICES</h1> <div class=\"container-fluid\" id=\"service-container\"> <div class=\"row\" id=\"banner-row\"> <div class=\"col-md-4\" id=\"service-col1\"> <img src=\"images/gfg.png\" class=\"img-fluid rounded mx-auto d-block\" alt=\"...\" /> <h3>Website Design</h3> <p> User Experience Design. Website Content Strategy. Cross Browser and Platform Testing. </p> </div> <div class=\"col-md-4\" id=\"service-col2\"> <img src=\"images/gfg.png\" class=\"img-fluid rounded mx-auto d-block\" alt=\"...\" /> <h3>Bulk SMS</h3> <p> 1.Toll Free Number 2. IVR 3. Virtual Number 4. Political or any Voice Broadcasting </p> </div> <div class=\"col-md-4\" id=\"service-col3\"> <img src=\"images/gfg.png\" class=\"img-fluid rounded mx-auto d-block\" alt=\"...\" /> <h3>Payment Gateways</h3> <p> PayU India is the flagship company of Naspers group which is a $25 Billion internet and media conglomerate listed on London and Johannesburg stock exchanges respectively. </p> </div> </div> </div> </section> <hr /> <!-- about Us --> <section id=\"about\"> <h1 class=\"text-center\">About Us</h1> <div class=\"container-fluid\" id=\"about-container\"> <div class=\"row\" id=\"banner-row\"> <div class=\"col-md-6\" id=\"about-col\"> <h3>Why Us</h3> <ul> <li> Probuz is all about Delivering High Quality web design and development services, Cost effective and reliable solutions. </li> <li>SCHOOL/COLLEGE MANAGEMENT SOFTWARE (CAMPUS PRO)</li> <li> Let us take care of your Business needs. Customer Productivity is our Priority. </li> <li>Our expertise in Business includes</li> </ul> </div> <div class=\"col-md-6\" id=\"banner-col2\"> <img class=\"img-responsive rounded mx-auto d-block\" src=\"images/gfg.png\" alt=\"\" /> </div> </div> </div> </section> <hr /> <!-- product --> <section id=\"product\"> <h1 class=\"text-center\">Our Products</h1> <div class=\"container-fluid\" id=\"product-container\"> <div class=\"row\" id=\"banner-row\"> <div class=\"col-md-6\" id=\"about-col\"> <img class=\"img-responsive rounded mx-auto d-block\" src=\"images/gfg.png\" alt=\"\" /> </div> <div class=\"col-md-6\" id=\"product-col2\"> <h3>Product List</h3> <ul> <li>CLINIC MANAGMENT SYSTEM</li> <li>SCHOOL/COLLEGE MANAGEMENT SOFTWARE (CAMPUS PRO)</li> <li>SERVICE MANAGEMENT SOFTWARE</li> <li>E-COMMERCE WEBSITE</li> </ul> </div> </div> </div> </section> <hr /> <!-- social --> <section id=\"social\"> <h1 class=\"text-center\">Get In Touch</h1> <div class=\"d-grid gap-2 d-md-flex justify-content-center\"> <div class=\"row align-items-center\" id=\"social-row\"> <div class=\"col-md-4 social-col\"> <a href=\"\" ><img class=\"img-responsive rounded mx-auto d-block\" src=\"images/gfg.png\" alt=\"\" /></a> </div> <div class=\"col-md-4 social-col\"> <a href=\"\" ><img class=\"img-responsive rounded mx-auto d-block\" src=\"images/icons8-instagram-64.png\" alt=\"\" /></a> </div> <div class=\"col-md-4 social-col\"> <a href=\"\" ><img class=\"img-responsive rounded mx-auto d-block\" src=\"images/icons8-twitter-64.png\" alt=\"\" /></a> </div> </div> </div> </section> <!-- footer --> <section id=\"footer\"> <section id=\"banner\"> <div class=\"container-fluid\" id=\"banner-container\"> <div class=\"row\" id=\"banner-row\"> <div class=\"col-md-4\" id=\"footer-col1\"> <h3>My Website</h3> <p> At XYZ we believe that customers should always get easy-to-use, best in the kind and fast services.xyz has achieved standards which helps customer to achieve satisfaction and realize value for their hard earned money. </p> </div> <div class=\"col-md-4\" id=\"footer-col2\"> <h3>Contact Us</h3> <p>Call Us- 1800-121-6532</p> <p>Email Us- [email protected]</p> </div> <div class=\"col-md-4\" id=\"footer-col2\"> <h3>Subscribe To Newsletter</h3> <form> <div class=\"mb-3\"> <input type=\"email\" placeholder=\"Enter Your Email\" class=\"form-control\" id=\"exampleInputEmail1\" aria-describedby=\"emailHelp\" /> <div id=\"emailHelp\" class=\"form-text\"> We'll never share your email with anyone else. </div> </div> <button type=\"submit\" class=\"btn btn-primary\"> Submit </button> </form> </div> </div> </div> </section> </section> <!-- Optional JavaScript; choose one of the two! --> <!-- Option 1: Bootstrap Bundle with Popper --> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js\" integrity=\"sha384-b5kHyXgcpbZJO/tY9Ul7kGkf1S0CWuKcCD38l8YkeH8z8QjE0GmW1gYU5S9FOnJ0\" crossorigin=\"anonymous\" ></script> </body></html>", "e": 10405, "s": 703, "text": null }, { "code": null, "e": 10415, "s": 10405, "text": "CSS CODE:" }, { "code": null, "e": 10535, "s": 10415, "text": "So, as you all know that bootstrap is not enough good for making the website interactive, so added some CSS over here. " }, { "code": null, "e": 10610, "s": 10535, "text": "You can change the navbar background color according to your requirement. " }, { "code": null, "e": 10620, "s": 10610, "text": "style.css" }, { "code": "*{ margin: 0; padding: 0; font-family: 'Roboto Condensed', sans-serif;} /* navbar */ .navbar-nav{ margin-right: 0 !important; padding-right: 100px;} .navbar{ background-color: #0a193d; color: white !important;} .nav-item a{ color: white !important;} .nav-item{ padding-left: 2px;} .navbar-brand{ color: white !important; padding-left: 100px;} #navbar button{ color: white !important;} /* banner */ #banner-container{ background-color: #0a193d; color: white !important; padding-top: 80px; padding-bottom: 80px; } #banner-row img{ max-width: 70%; height: auto; display: block; padding-left: 30px;} #banner-row h3, p{ padding-left: 20px; padding-top: 20px; text-align: center;} #banner-row a{ background-color: white !important; color: black !important; border: none; margin-left: 20px; margin-top: 20px; }#banner-col{ padding-left: 20px;}/* service */#service{ padding-top: 80px; padding-bottom: 80px;} #service h1{ padding-bottom: 70px;} /* about */ #about{ padding-top: 80px; padding-bottom: 80px;} #about h1{ padding-bottom: 70px;} #about-col ul{ padding-top: 50px; padding-left: 50px;} #about-col ul li{ padding-top: 15px; } /* product */ #product{ padding-top: 80px; padding-bottom: 80px;} #product h1{ padding-bottom: 70px;} #product-col2 ul{ padding-top: 90px;} #product-col2 ul li{ padding-top: 15px;} /* social */ #social{ padding-top: 80px; padding-bottom: 80px;} #social h1{ padding-bottom: 70px;} .social-col a:hover img{ transform: translateY(-10px);} #social-row{ flex-direction: row;} /* footer */ .mb-3{ padding-top: 10px;} /* media */@media only screen and (max-width: 987px){ .navbar-brand{ padding-left: 0px; }} @media only screen and (max-width: 768px){ #banner-row img{ padding-top: 20px; } .social-col{ width: 33%; } }", "e": 12591, "s": 10620, "text": null }, { "code": null, "e": 12599, "s": 12591, "text": "Output:" }, { "code": null, "e": 12618, "s": 12599, "text": "Supported Browser:" }, { "code": null, "e": 12632, "s": 12618, "text": "Google Chrome" }, { "code": null, "e": 12647, "s": 12632, "text": "Microsoft Edge" }, { "code": null, "e": 12655, "s": 12647, "text": "Firefox" }, { "code": null, "e": 12661, "s": 12655, "text": "Opera" }, { "code": null, "e": 12669, "s": 12661, "text": "Safari " }, { "code": null, "e": 12771, "s": 12669, "text": " You can check out this project at the given link – https://saurabhsonewane.github.io/gfg1.github.io/" }, { "code": null, "e": 12783, "s": 12771, "text": "ysachin2314" }, { "code": null, "e": 12795, "s": 12783, "text": "Bootstrap-4" }, { "code": null, "e": 12815, "s": 12795, "text": "Bootstrap-Questions" }, { "code": null, "e": 12830, "s": 12815, "text": "CSS-Properties" }, { "code": null, "e": 12836, "s": 12830, "text": "HTML5" }, { "code": null, "e": 12843, "s": 12836, "text": "Picked" }, { "code": null, "e": 12853, "s": 12843, "text": "Bootstrap" }, { "code": null, "e": 12857, "s": 12853, "text": "CSS" }, { "code": null, "e": 12862, "s": 12857, "text": "HTML" }, { "code": null, "e": 12879, "s": 12862, "text": "Web Technologies" }, { "code": null, "e": 12884, "s": 12879, "text": "HTML" }, { "code": null, "e": 12982, "s": 12884, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 13023, "s": 12982, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 13056, "s": 13023, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 13082, "s": 13056, "text": "Tailwind CSS vs Bootstrap" }, { "code": null, "e": 13127, "s": 13082, "text": "How to set vertical alignment in Bootstrap ?" }, { "code": null, "e": 13194, "s": 13127, "text": "How to toggle password visibility in forms using Bootstrap-icons ?" }, { "code": null, "e": 13242, "s": 13194, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 13304, "s": 13242, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 13354, "s": 13304, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 13412, "s": 13354, "text": "How to create footer to stay at the bottom of a Web page?" } ]
ML | Logistic Regression using Tensorflow
01 Nov, 2019 Prerequisites: Understanding Logistic Regression and TensorFlow. Brief Summary of Logistic Regression:Logistic Regression is Classification algorithm commonly used in Machine Learning. It allows categorizing data into discrete classes by learning the relationship from a given set of labeled data. It learns a linear relationship from the given dataset and then introduces a non-linearity in the form of the Sigmoid function. In case of Logistic regression, the hypothesis is the Sigmoid of a straight line, i.e, where Where the vector w represents the Weights and the scalar b represents the Bias of the model.Let us visualize the Sigmoid Function – import numpy as npimport matplotlib.pyplot as plt def sigmoid(z): return 1 / (1 + np.exp( - z)) plt.plot(np.arange(-5, 5, 0.1), sigmoid(np.arange(-5, 5, 0.1)))plt.title('Visualization of the Sigmoid Function') plt.show() Output:Note that the range of the Sigmoid function is (0, 1) which means that the resultant values are in between 0 and 1. This property of Sigmoid function makes it a really good choice of Activation Function for Binary Classification. Also for z = 0, Sigmoid(z) = 0.5 which is the midpoint of the range of Sigmoid function. Just like Linear Regression, we need to find the optimal values of w and b for which the cost function J is minimum. In this case, we will be using the Sigmoid Cross Entropy cost function which is given byThis cost function will then be optimized using Gradient Descent. Implementation:We will start by importing the necessary libraries. We will use Numpy along with Tensorflow for computations, Pandas for basic Data Analysis and Matplotlib for plotting. We will also be using the preprocessing module of Scikit-Learn for One Hot Encoding the data. # importing modulesimport numpy as npimport pandas as pdimport tensorflow as tfimport matplotlib.pyplot as pltfrom sklearn.preprocessing import OneHotEncoder Next we will be importing the dataset. We will be using a subset of the famous Iris dataset. data = pd.read_csv('dataset.csv', header = None)print("Data Shape:", data.shape) print(data.head()) Output: Data Shape: (100, 4) 0 1 2 3 0 0 5.1 3.5 1 1 1 4.9 3.0 1 2 2 4.7 3.2 1 3 3 4.6 3.1 1 4 4 5.0 3.6 1 Now let’s get the feature matrix and the corresponding labels and visualize. # Feature Matrixx_orig = data.iloc[:, 1:-1].values # Data labelsy_orig = data.iloc[:, -1:].values print("Shape of Feature Matrix:", x_orig.shape)print("Shape Label Vector:", y_orig.shape) Output: Shape of Feature Matrix: (100, 2) Shape Label Vector: (100, 1) Visualize the given data. # Positive Data Pointsx_pos = np.array([x_orig[i] for i in range(len(x_orig)) if y_orig[i] == 1]) # Negative Data Pointsx_neg = np.array([x_orig[i] for i in range(len(x_orig)) if y_orig[i] == 0]) # Plotting the Positive Data Pointsplt.scatter(x_pos[:, 0], x_pos[:, 1], color = 'blue', label = 'Positive') # Plotting the Negative Data Pointsplt.scatter(x_neg[:, 0], x_neg[:, 1], color = 'red', label = 'Negative') plt.xlabel('Feature 1')plt.ylabel('Feature 2')plt.title('Plot of given data')plt.legend() plt.show() . Now we will be One Hot Encoding the data for it to work with the algorithm. One hot encoding transforms categorical features to a format that works better with classification and regression algorithms. We will also be setting the Learning Rate and the number of Epochs. # Creating the One Hot EncoderoneHot = OneHotEncoder() # Encoding x_origoneHot.fit(x_orig)x = oneHot.transform(x_orig).toarray() # Encoding y_origoneHot.fit(y_orig)y = oneHot.transform(y_orig).toarray() alpha, epochs = 0.0035, 500m, n = x.shapeprint('m =', m)print('n =', n)print('Learning Rate =', alpha)print('Number of Epochs =', epochs) Output: m = 100 n = 7 Learning Rate = 0.0035 Number of Epochs = 500 Now we will start creating the model by defining the placeholders X and Y, so that we can feed our training examples x and y into the optimizer during the training process. We will also be creating the trainable Variables W and b which can be optimized by the Gradient Descent Optimizer. # There are n columns in the feature matrix# after One Hot Encoding.X = tf.placeholder(tf.float32, [None, n]) # Since this is a binary classification problem,# Y can take only 2 values.Y = tf.placeholder(tf.float32, [None, 2]) # Trainable Variable WeightsW = tf.Variable(tf.zeros([n, 2])) # Trainable Variable Biasb = tf.Variable(tf.zeros([2])) Now declare the Hypothesis, Cost function, Optimizer and Global Variables Initializer. # HypothesisY_hat = tf.nn.sigmoid(tf.add(tf.matmul(X, W), b)) # Sigmoid Cross Entropy Cost Functioncost = tf.nn.sigmoid_cross_entropy_with_logits( logits = Y_hat, labels = Y) # Gradient Descent Optimizeroptimizer = tf.train.GradientDescentOptimizer( learning_rate = alpha).minimize(cost) # Global Variables Initializerinit = tf.global_variables_initializer() Begin the training process inside a Tensorflow Session. # Starting the Tensorflow Sessionwith tf.Session() as sess: # Initializing the Variables sess.run(init) # Lists for storing the changing Cost and Accuracy in every Epoch cost_history, accuracy_history = [], [] # Iterating through all the epochs for epoch in range(epochs): cost_per_epoch = 0 # Running the Optimizer sess.run(optimizer, feed_dict = {X : x, Y : y}) # Calculating cost on current Epoch c = sess.run(cost, feed_dict = {X : x, Y : y}) # Calculating accuracy on current Epoch correct_prediction = tf.equal(tf.argmax(Y_hat, 1), tf.argmax(Y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) # Storing Cost and Accuracy to the history cost_history.append(sum(sum(c))) accuracy_history.append(accuracy.eval({X : x, Y : y}) * 100) # Displaying result on current Epoch if epoch % 100 == 0 and epoch != 0: print("Epoch " + str(epoch) + " Cost: " + str(cost_history[-1])) Weight = sess.run(W) # Optimized Weight Bias = sess.run(b) # Optimized Bias # Final Accuracy correct_prediction = tf.equal(tf.argmax(Y_hat, 1), tf.argmax(Y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print("\nAccuracy:", accuracy_history[-1], "%") Output: Epoch 100 Cost: 125.700202942 Epoch 200 Cost: 120.647117615 Epoch 300 Cost: 118.151592255 Epoch 400 Cost: 116.549999237 Accuracy: 91.0000026226 % Let’s plot the change of cost over the epochs. plt.plot(list(range(epochs)), cost_history)plt.xlabel('Epochs')plt.ylabel('Cost')plt.title('Decrease in Cost with Epochs') plt.show() Plot the change of accuracy over the epochs. plt.plot(list(range(epochs)), accuracy_history)plt.xlabel('Epochs')plt.ylabel('Accuracy')plt.title('Increase in Accuracy with Epochs') plt.show() Now we will be plotting the Decision Boundary for our trained classifier. A decision boundary is a hypersurface that partitions the underlying vector space into two sets, one for each class. # Calculating the Decision Boundarydecision_boundary_x = np.array([np.min(x_orig[:, 0]), np.max(x_orig[:, 0])]) decision_boundary_y = (- 1.0 / Weight[0]) * (decision_boundary_x * Weight + Bias) decision_boundary_y = [sum(decision_boundary_y[:, 0]), sum(decision_boundary_y[:, 1])] # Positive Data Pointsx_pos = np.array([x_orig[i] for i in range(len(x_orig)) if y_orig[i] == 1]) # Negative Data Pointsx_neg = np.array([x_orig[i] for i in range(len(x_orig)) if y_orig[i] == 0]) # Plotting the Positive Data Pointsplt.scatter(x_pos[:, 0], x_pos[:, 1], color = 'blue', label = 'Positive') # Plotting the Negative Data Pointsplt.scatter(x_neg[:, 0], x_neg[:, 1], color = 'red', label = 'Negative') # Plotting the Decision Boundaryplt.plot(decision_boundary_x, decision_boundary_y)plt.xlabel('Feature 1')plt.ylabel('Feature 2')plt.title('Plot of Decision Boundary')plt.legend() plt.show() nidhi_biet Technical Scripter 2018 Tensorflow Machine Learning Python Technical Scripter Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Reinforcement learning Search Algorithms in AI Decision Tree Introduction with example Getting started with Machine Learning Introduction to Recurrent Neural Network Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 52, "s": 24, "text": "\n01 Nov, 2019" }, { "code": null, "e": 117, "s": 52, "text": "Prerequisites: Understanding Logistic Regression and TensorFlow." }, { "code": null, "e": 478, "s": 117, "text": "Brief Summary of Logistic Regression:Logistic Regression is Classification algorithm commonly used in Machine Learning. It allows categorizing data into discrete classes by learning the relationship from a given set of labeled data. It learns a linear relationship from the given dataset and then introduces a non-linearity in the form of the Sigmoid function." }, { "code": null, "e": 703, "s": 478, "text": "In case of Logistic regression, the hypothesis is the Sigmoid of a straight line, i.e, where Where the vector w represents the Weights and the scalar b represents the Bias of the model.Let us visualize the Sigmoid Function –" }, { "code": "import numpy as npimport matplotlib.pyplot as plt def sigmoid(z): return 1 / (1 + np.exp( - z)) plt.plot(np.arange(-5, 5, 0.1), sigmoid(np.arange(-5, 5, 0.1)))plt.title('Visualization of the Sigmoid Function') plt.show()", "e": 930, "s": 703, "text": null }, { "code": null, "e": 1256, "s": 930, "text": "Output:Note that the range of the Sigmoid function is (0, 1) which means that the resultant values are in between 0 and 1. This property of Sigmoid function makes it a really good choice of Activation Function for Binary Classification. Also for z = 0, Sigmoid(z) = 0.5 which is the midpoint of the range of Sigmoid function." }, { "code": null, "e": 1527, "s": 1256, "text": "Just like Linear Regression, we need to find the optimal values of w and b for which the cost function J is minimum. In this case, we will be using the Sigmoid Cross Entropy cost function which is given byThis cost function will then be optimized using Gradient Descent." }, { "code": null, "e": 1806, "s": 1527, "text": "Implementation:We will start by importing the necessary libraries. We will use Numpy along with Tensorflow for computations, Pandas for basic Data Analysis and Matplotlib for plotting. We will also be using the preprocessing module of Scikit-Learn for One Hot Encoding the data." }, { "code": "# importing modulesimport numpy as npimport pandas as pdimport tensorflow as tfimport matplotlib.pyplot as pltfrom sklearn.preprocessing import OneHotEncoder", "e": 1964, "s": 1806, "text": null }, { "code": null, "e": 2057, "s": 1964, "text": "Next we will be importing the dataset. We will be using a subset of the famous Iris dataset." }, { "code": "data = pd.read_csv('dataset.csv', header = None)print(\"Data Shape:\", data.shape) print(data.head())", "e": 2158, "s": 2057, "text": null }, { "code": null, "e": 2166, "s": 2158, "text": "Output:" }, { "code": null, "e": 2295, "s": 2166, "text": "Data Shape: (100, 4)\n 0 1 2 3\n0 0 5.1 3.5 1\n1 1 4.9 3.0 1\n2 2 4.7 3.2 1\n3 3 4.6 3.1 1\n4 4 5.0 3.6 1" }, { "code": null, "e": 2372, "s": 2295, "text": "Now let’s get the feature matrix and the corresponding labels and visualize." }, { "code": "# Feature Matrixx_orig = data.iloc[:, 1:-1].values # Data labelsy_orig = data.iloc[:, -1:].values print(\"Shape of Feature Matrix:\", x_orig.shape)print(\"Shape Label Vector:\", y_orig.shape)", "e": 2562, "s": 2372, "text": null }, { "code": null, "e": 2570, "s": 2562, "text": "Output:" }, { "code": null, "e": 2633, "s": 2570, "text": "Shape of Feature Matrix: (100, 2)\nShape Label Vector: (100, 1)" }, { "code": null, "e": 2659, "s": 2633, "text": "Visualize the given data." }, { "code": "# Positive Data Pointsx_pos = np.array([x_orig[i] for i in range(len(x_orig)) if y_orig[i] == 1]) # Negative Data Pointsx_neg = np.array([x_orig[i] for i in range(len(x_orig)) if y_orig[i] == 0]) # Plotting the Positive Data Pointsplt.scatter(x_pos[:, 0], x_pos[:, 1], color = 'blue', label = 'Positive') # Plotting the Negative Data Pointsplt.scatter(x_neg[:, 0], x_neg[:, 1], color = 'red', label = 'Negative') plt.xlabel('Feature 1')plt.ylabel('Feature 2')plt.title('Plot of given data')plt.legend() plt.show()", "e": 3248, "s": 2659, "text": null }, { "code": null, "e": 3250, "s": 3248, "text": "." }, { "code": null, "e": 3520, "s": 3250, "text": "Now we will be One Hot Encoding the data for it to work with the algorithm. One hot encoding transforms categorical features to a format that works better with classification and regression algorithms. We will also be setting the Learning Rate and the number of Epochs." }, { "code": "# Creating the One Hot EncoderoneHot = OneHotEncoder() # Encoding x_origoneHot.fit(x_orig)x = oneHot.transform(x_orig).toarray() # Encoding y_origoneHot.fit(y_orig)y = oneHot.transform(y_orig).toarray() alpha, epochs = 0.0035, 500m, n = x.shapeprint('m =', m)print('n =', n)print('Learning Rate =', alpha)print('Number of Epochs =', epochs)", "e": 3864, "s": 3520, "text": null }, { "code": null, "e": 3872, "s": 3864, "text": "Output:" }, { "code": null, "e": 3932, "s": 3872, "text": "m = 100\nn = 7\nLearning Rate = 0.0035\nNumber of Epochs = 500" }, { "code": null, "e": 4220, "s": 3932, "text": "Now we will start creating the model by defining the placeholders X and Y, so that we can feed our training examples x and y into the optimizer during the training process. We will also be creating the trainable Variables W and b which can be optimized by the Gradient Descent Optimizer." }, { "code": "# There are n columns in the feature matrix# after One Hot Encoding.X = tf.placeholder(tf.float32, [None, n]) # Since this is a binary classification problem,# Y can take only 2 values.Y = tf.placeholder(tf.float32, [None, 2]) # Trainable Variable WeightsW = tf.Variable(tf.zeros([n, 2])) # Trainable Variable Biasb = tf.Variable(tf.zeros([2]))", "e": 4568, "s": 4220, "text": null }, { "code": null, "e": 4656, "s": 4568, "text": " Now declare the Hypothesis, Cost function, Optimizer and Global Variables Initializer." }, { "code": "# HypothesisY_hat = tf.nn.sigmoid(tf.add(tf.matmul(X, W), b)) # Sigmoid Cross Entropy Cost Functioncost = tf.nn.sigmoid_cross_entropy_with_logits( logits = Y_hat, labels = Y) # Gradient Descent Optimizeroptimizer = tf.train.GradientDescentOptimizer( learning_rate = alpha).minimize(cost) # Global Variables Initializerinit = tf.global_variables_initializer()", "e": 5045, "s": 4656, "text": null }, { "code": null, "e": 5102, "s": 5045, "text": " Begin the training process inside a Tensorflow Session." }, { "code": "# Starting the Tensorflow Sessionwith tf.Session() as sess: # Initializing the Variables sess.run(init) # Lists for storing the changing Cost and Accuracy in every Epoch cost_history, accuracy_history = [], [] # Iterating through all the epochs for epoch in range(epochs): cost_per_epoch = 0 # Running the Optimizer sess.run(optimizer, feed_dict = {X : x, Y : y}) # Calculating cost on current Epoch c = sess.run(cost, feed_dict = {X : x, Y : y}) # Calculating accuracy on current Epoch correct_prediction = tf.equal(tf.argmax(Y_hat, 1), tf.argmax(Y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) # Storing Cost and Accuracy to the history cost_history.append(sum(sum(c))) accuracy_history.append(accuracy.eval({X : x, Y : y}) * 100) # Displaying result on current Epoch if epoch % 100 == 0 and epoch != 0: print(\"Epoch \" + str(epoch) + \" Cost: \" + str(cost_history[-1])) Weight = sess.run(W) # Optimized Weight Bias = sess.run(b) # Optimized Bias # Final Accuracy correct_prediction = tf.equal(tf.argmax(Y_hat, 1), tf.argmax(Y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print(\"\\nAccuracy:\", accuracy_history[-1], \"%\")", "e": 6693, "s": 5102, "text": null }, { "code": null, "e": 6701, "s": 6693, "text": "Output:" }, { "code": null, "e": 6848, "s": 6701, "text": "Epoch 100 Cost: 125.700202942\nEpoch 200 Cost: 120.647117615\nEpoch 300 Cost: 118.151592255\nEpoch 400 Cost: 116.549999237\n\nAccuracy: 91.0000026226 %" }, { "code": null, "e": 6895, "s": 6848, "text": "Let’s plot the change of cost over the epochs." }, { "code": "plt.plot(list(range(epochs)), cost_history)plt.xlabel('Epochs')plt.ylabel('Cost')plt.title('Decrease in Cost with Epochs') plt.show()", "e": 7030, "s": 6895, "text": null }, { "code": null, "e": 7075, "s": 7030, "text": "Plot the change of accuracy over the epochs." }, { "code": "plt.plot(list(range(epochs)), accuracy_history)plt.xlabel('Epochs')plt.ylabel('Accuracy')plt.title('Increase in Accuracy with Epochs') plt.show()", "e": 7222, "s": 7075, "text": null }, { "code": null, "e": 7413, "s": 7222, "text": "Now we will be plotting the Decision Boundary for our trained classifier. A decision boundary is a hypersurface that partitions the underlying vector space into two sets, one for each class." }, { "code": "# Calculating the Decision Boundarydecision_boundary_x = np.array([np.min(x_orig[:, 0]), np.max(x_orig[:, 0])]) decision_boundary_y = (- 1.0 / Weight[0]) * (decision_boundary_x * Weight + Bias) decision_boundary_y = [sum(decision_boundary_y[:, 0]), sum(decision_boundary_y[:, 1])] # Positive Data Pointsx_pos = np.array([x_orig[i] for i in range(len(x_orig)) if y_orig[i] == 1]) # Negative Data Pointsx_neg = np.array([x_orig[i] for i in range(len(x_orig)) if y_orig[i] == 0]) # Plotting the Positive Data Pointsplt.scatter(x_pos[:, 0], x_pos[:, 1], color = 'blue', label = 'Positive') # Plotting the Negative Data Pointsplt.scatter(x_neg[:, 0], x_neg[:, 1], color = 'red', label = 'Negative') # Plotting the Decision Boundaryplt.plot(decision_boundary_x, decision_boundary_y)plt.xlabel('Feature 1')plt.ylabel('Feature 2')plt.title('Plot of Decision Boundary')plt.legend() plt.show()", "e": 8437, "s": 7413, "text": null }, { "code": null, "e": 8448, "s": 8437, "text": "nidhi_biet" }, { "code": null, "e": 8472, "s": 8448, "text": "Technical Scripter 2018" }, { "code": null, "e": 8483, "s": 8472, "text": "Tensorflow" }, { "code": null, "e": 8500, "s": 8483, "text": "Machine Learning" }, { "code": null, "e": 8507, "s": 8500, "text": "Python" }, { "code": null, "e": 8526, "s": 8507, "text": "Technical Scripter" }, { "code": null, "e": 8543, "s": 8526, "text": "Machine Learning" }, { "code": null, "e": 8641, "s": 8543, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8664, "s": 8641, "text": "Reinforcement learning" }, { "code": null, "e": 8688, "s": 8664, "text": "Search Algorithms in AI" }, { "code": null, "e": 8728, "s": 8688, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 8766, "s": 8728, "text": "Getting started with Machine Learning" }, { "code": null, "e": 8807, "s": 8766, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 8835, "s": 8807, "text": "Read JSON file using Python" }, { "code": null, "e": 8885, "s": 8835, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 8907, "s": 8885, "text": "Python map() function" } ]
Logger getLevel() method in Java with Examples
19 Mar, 2019 The getLevel() method of the Logger class in Java is used to get the log Level that has been specified for this Logger instance. Every Logger has specific log levels and if the result is null, which means that this logger’s effective level will be inherited from its parent. Log Levels: The log levels control the logging details. They determine the extent to which depth the log files are generated. Each level is associated with a numeric value and there are 7 basic log levels and 2 special ones. We need to specify the desired level of logging every time, we seek to interact with the log system. To know more about Log Levels, refer this Log Levels in Logging Syntax: public Level getLevel() Parameters: This method accepts no parameters. Return value: This method returns Level which represents level of logger. Below programs illustrate the getLevel() method:Program 1: // Java program to demonstrate// Logger.getLevel() method import java.util.logging.Logger;import java.util.logging.Level; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // Get level of logger Level level = logger.getLevel(); // If logger level is null // then take a level of the parent of logger if (level == null && logger.getParent() != null) { level = logger.getParent().getLevel(); } System.out.println("Logger Level = " + level); }} Logger Level = INFO Program 2: // Java program to demonstrate// Logger.getLevel() method import java.util.logging.Logger;import java.util.logging.Level;import java.util.*; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( ArrayList.class.getName()); // Get level of logger Level level = logger.getLevel(); System.out.println("Logger Level = " + level); }} Logger Level = null Reference: https://docs.oracle.com/javase/10/docs/api/java/util/logging/Logger.html#getLevel() Java - util package Java-Functions Java-Logger Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Mar, 2019" }, { "code": null, "e": 303, "s": 28, "text": "The getLevel() method of the Logger class in Java is used to get the log Level that has been specified for this Logger instance. Every Logger has specific log levels and if the result is null, which means that this logger’s effective level will be inherited from its parent." }, { "code": null, "e": 693, "s": 303, "text": "Log Levels: The log levels control the logging details. They determine the extent to which depth the log files are generated. Each level is associated with a numeric value and there are 7 basic log levels and 2 special ones. We need to specify the desired level of logging every time, we seek to interact with the log system. To know more about Log Levels, refer this Log Levels in Logging" }, { "code": null, "e": 701, "s": 693, "text": "Syntax:" }, { "code": null, "e": 726, "s": 701, "text": "public Level getLevel()\n" }, { "code": null, "e": 773, "s": 726, "text": "Parameters: This method accepts no parameters." }, { "code": null, "e": 847, "s": 773, "text": "Return value: This method returns Level which represents level of logger." }, { "code": null, "e": 906, "s": 847, "text": "Below programs illustrate the getLevel() method:Program 1:" }, { "code": "// Java program to demonstrate// Logger.getLevel() method import java.util.logging.Logger;import java.util.logging.Level; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // Get level of logger Level level = logger.getLevel(); // If logger level is null // then take a level of the parent of logger if (level == null && logger.getParent() != null) { level = logger.getParent().getLevel(); } System.out.println(\"Logger Level = \" + level); }}", "e": 1567, "s": 906, "text": null }, { "code": null, "e": 1588, "s": 1567, "text": "Logger Level = INFO\n" }, { "code": null, "e": 1599, "s": 1588, "text": "Program 2:" }, { "code": "// Java program to demonstrate// Logger.getLevel() method import java.util.logging.Logger;import java.util.logging.Level;import java.util.*; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( ArrayList.class.getName()); // Get level of logger Level level = logger.getLevel(); System.out.println(\"Logger Level = \" + level); }}", "e": 2093, "s": 1599, "text": null }, { "code": null, "e": 2114, "s": 2093, "text": "Logger Level = null\n" }, { "code": null, "e": 2209, "s": 2114, "text": "Reference: https://docs.oracle.com/javase/10/docs/api/java/util/logging/Logger.html#getLevel()" }, { "code": null, "e": 2229, "s": 2209, "text": "Java - util package" }, { "code": null, "e": 2244, "s": 2229, "text": "Java-Functions" }, { "code": null, "e": 2256, "s": 2244, "text": "Java-Logger" }, { "code": null, "e": 2261, "s": 2256, "text": "Java" }, { "code": null, "e": 2266, "s": 2261, "text": "Java" } ]
What is the purpose of “role” attribute in HTML ?
18 Nov, 2019 The main purpose of role attribute is to bolster ARIA i.e. Accessible Rich Internet Applications which helps in providing richness and quality from semantic perspective. Moreover, role attribute makes a website more facilitative and using this attribute is considered as a good practice. Generally, the role is necessary for languages which do not define their own role attribute. Example: <!DOCTYPE><html lang="en"> <head> <meta charset="utf-8"> <title> Output of Role Attribute </title> <style> h1 { text-align: center; color: green; font-size: 100px; } h2 { text-align: center; } </style></head> <body role="document"> <h1>GeeksforGeeks</h1> <h2>Understanding usage of "Role" Attribute</h2></body> </html> Output: Output obtained for role attribute The output doesn’t show any significant thing to notice. This shows that even if the role attribute is not used in the code, then also it won’t affect our code and output. By using role attributes, we get to avail features like accessibility, device adaptation, server-side processing, complex data description, and many more such features. Thus role attribute is advised to be used for getting better performance of the code. HTML-Attributes HTML-Misc HTML5 Picked HTML Technical Scripter Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Nov, 2019" }, { "code": null, "e": 409, "s": 28, "text": "The main purpose of role attribute is to bolster ARIA i.e. Accessible Rich Internet Applications which helps in providing richness and quality from semantic perspective. Moreover, role attribute makes a website more facilitative and using this attribute is considered as a good practice. Generally, the role is necessary for languages which do not define their own role attribute." }, { "code": null, "e": 418, "s": 409, "text": "Example:" }, { "code": "<!DOCTYPE><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <title> Output of Role Attribute </title> <style> h1 { text-align: center; color: green; font-size: 100px; } h2 { text-align: center; } </style></head> <body role=\"document\"> <h1>GeeksforGeeks</h1> <h2>Understanding usage of \"Role\" Attribute</h2></body> </html>", "e": 850, "s": 418, "text": null }, { "code": null, "e": 858, "s": 850, "text": "Output:" }, { "code": null, "e": 893, "s": 858, "text": "Output obtained for role attribute" }, { "code": null, "e": 1065, "s": 893, "text": "The output doesn’t show any significant thing to notice. This shows that even if the role attribute is not used in the code, then also it won’t affect our code and output." }, { "code": null, "e": 1320, "s": 1065, "text": "By using role attributes, we get to avail features like accessibility, device adaptation, server-side processing, complex data description, and many more such features. Thus role attribute is advised to be used for getting better performance of the code." }, { "code": null, "e": 1336, "s": 1320, "text": "HTML-Attributes" }, { "code": null, "e": 1346, "s": 1336, "text": "HTML-Misc" }, { "code": null, "e": 1352, "s": 1346, "text": "HTML5" }, { "code": null, "e": 1359, "s": 1352, "text": "Picked" }, { "code": null, "e": 1364, "s": 1359, "text": "HTML" }, { "code": null, "e": 1383, "s": 1364, "text": "Technical Scripter" }, { "code": null, "e": 1400, "s": 1383, "text": "Web Technologies" }, { "code": null, "e": 1427, "s": 1400, "text": "Web technologies Questions" }, { "code": null, "e": 1432, "s": 1427, "text": "HTML" } ]
How to split DataFrame in R
23 Sep, 2021 In this article, we will discuss how to split the dataframe in R programming language. A subset can be split both continuously as well as randomly based on rows and columns. The rows and columns of the dataframe can be referenced using the indexes as well as names. Multiple rows and columns can be referred using the c() method in base R. The dataframe cells can be referenced using the row and column names and indexes. Syntax: data-frame[start-row-num:end-row-num,] The row numbers are retained in the final output dataframe. Example: Splitting dataframe by row R # create first dataframedata_frame1<-data.frame(col1=c(rep('Grp1',2), rep('Grp2',2), rep('Grp3',2)), col2=rep(1:3,2), col3=rep(1:2,3) ) print("Original DataFrame")print(data_frame1) # extracting first four rowsdata_frame_mod <- data_frame1[1:4,] print("Modified DataFrame")print(data_frame_mod) Output: [1] "Original DataFrame" col1 col2 col3 1 Grp1 1 1 2 Grp1 2 2 3 Grp2 3 1 4 Grp2 1 2 5 Grp3 2 1 6 Grp3 3 2 [1] "Modified DataFrame" col1 col2 col3 1 Grp1 1 1 2 Grp1 2 2 3 Grp2 3 1 4 Grp2 1 2 Example: Splitting dataframe by row R # create first dataframedata_frame1<-data.frame(col1=c(rep('Grp1',2), rep('Grp2',2), rep('Grp3',2)), col2=rep(1:3,2), col3=rep(1:2,3) ) print("Original DataFrame")print(data_frame1) # extracting first four rowsdata_frame_mod <- data_frame1[6,]print("Modified DataFrame")print(data_frame_mod) Output: [1] "Original DataFrame" col1 col2 col3 1 Grp1 1 1 2 Grp1 2 2 3 Grp2 3 1 4 Grp2 1 2 5 Grp3 2 1 6 Grp3 3 2 [1] "Modified DataFrame" col1 col2 col3 6 Grp3 3 2 The dataframe rows can also be generated randomly by using the set.seed() method. It generates a random sample, which is then fed into any arbitrary random dummy generator function. The rows can then be extracted by comparing them to a function. Example: Splitting dataframe by rows randomly R # create first dataframedata_frame1<-data.frame(col1=c(rep('Grp1',2), rep('Grp2',2), rep('Grp3',2)), col2=rep(1:3,2), col3=rep(1:2,3), col4 = letters[1:6] ) print("Original DataFrame")print(data_frame1) # extracting last two columnsset.seed(99999) rows <- nrow(data_frame1)rand <- rbinom(rows, 2, 0.5) data_frame_mod <- data_frame1[rand == 0, ] print("Modified DataFrame")print(data_frame_mod) Output: [1] "Original DataFrame" col1 col2 col3 col4 1 Grp1 1 1 a 2 Grp1 2 2 b 3 Grp2 3 1 c 4 Grp2 1 2 d 5 Grp3 2 1 e 6 Grp3 3 2 f [1] "Modified DataFrame" col1 col2 col3 col4 5 Grp3 2 1 e 6 Grp3 3 2 f The dataframe can also be referenced using the column names. Multiple column names can be specified using the c() method containing column names as strings. The column names may be contiguous or random in nature. Syntax: data-frame[,c(col1, col2,...)] Example: splitting dataframe by column names R # create first dataframedata_frame1<-data.frame(col1=c(rep('Grp1',2), rep('Grp2',2), rep('Grp3',2)), col2=rep(1:3,2), col3=rep(1:2,3), col4 = letters[1:6] ) print("Original DataFrame")print(data_frame1) # extracting sixth rowdata_frame_mod <- data_frame1[,c("col2","col4")]print("Modified DataFrame")print(data_frame_mod) Output: [1] "Original DataFrame" col1 col2 col3 col4 1 Grp1 1 1 a 2 Grp1 2 2 b 3 Grp2 3 1 c 4 Grp2 1 2 d 5 Grp3 2 1 e 6 Grp3 3 2 f [1] "Modified DataFrame" col2 col4 1 1 a 2 2 b 3 3 c 4 1 d 5 2 e 6 3 f The dataframe can also be referenced using the column indices. Individual, as well as multiple columns, can be extracted from the dataframe by specifying the column position. Syntax: data-frame[,start-col-num:end-col-num] Example: Split dataframe by column indices R # create first dataframedata_frame1<-data.frame(col1=c(rep('Grp1',2), rep('Grp2',2), rep('Grp3',2)), col2=rep(1:3,2), col3=rep(1:2,3), col4 = letters[1:6] ) print("Original DataFrame")print(data_frame1) # extracting last two columnsdata_frame_mod <- data_frame1[,c(3:4)]print("Modified DataFrame")print(data_frame_mod) Output: [1] "Original DataFrame" col1 col2 col3 col4 1 Grp1 1 1 a 2 Grp1 2 2 b 3 Grp2 3 1 c 4 Grp2 1 2 d 5 Grp3 2 1 e 6 Grp3 3 2 f [1] "Modified DataFrame" col3 col4 1 1 a 2 2 b 3 1 c 4 2 d 5 1 e 6 2 f 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": 115, "s": 28, "text": "In this article, we will discuss how to split the dataframe in R programming language." }, { "code": null, "e": 368, "s": 115, "text": "A subset can be split both continuously as well as randomly based on rows and columns. The rows and columns of the dataframe can be referenced using the indexes as well as names. Multiple rows and columns can be referred using the c() method in base R." }, { "code": null, "e": 450, "s": 368, "text": "The dataframe cells can be referenced using the row and column names and indexes." }, { "code": null, "e": 458, "s": 450, "text": "Syntax:" }, { "code": null, "e": 497, "s": 458, "text": "data-frame[start-row-num:end-row-num,]" }, { "code": null, "e": 558, "s": 497, "text": "The row numbers are retained in the final output dataframe. " }, { "code": null, "e": 594, "s": 558, "text": "Example: Splitting dataframe by row" }, { "code": null, "e": 596, "s": 594, "text": "R" }, { "code": "# create first dataframedata_frame1<-data.frame(col1=c(rep('Grp1',2), rep('Grp2',2), rep('Grp3',2)), col2=rep(1:3,2), col3=rep(1:2,3) ) print(\"Original DataFrame\")print(data_frame1) # extracting first four rowsdata_frame_mod <- data_frame1[1:4,] print(\"Modified DataFrame\")print(data_frame_mod)", "e": 1025, "s": 596, "text": null }, { "code": null, "e": 1033, "s": 1025, "text": "Output:" }, { "code": null, "e": 1295, "s": 1033, "text": "[1] \"Original DataFrame\"\ncol1 col2 col3 \n1 Grp1 1 1 \n2 Grp1 2 2 \n3 Grp2 3 1 \n4 Grp2 1 2 \n5 Grp3 2 1 \n6 Grp3 3 2 \n[1] \"Modified DataFrame\" \ncol1 col2 col3 \n1 Grp1 1 1 \n2 Grp1 2 2 \n3 Grp2 3 1 \n4 Grp2 1 2" }, { "code": null, "e": 1331, "s": 1295, "text": "Example: Splitting dataframe by row" }, { "code": null, "e": 1333, "s": 1331, "text": "R" }, { "code": "# create first dataframedata_frame1<-data.frame(col1=c(rep('Grp1',2), rep('Grp2',2), rep('Grp3',2)), col2=rep(1:3,2), col3=rep(1:2,3) ) print(\"Original DataFrame\")print(data_frame1) # extracting first four rowsdata_frame_mod <- data_frame1[6,]print(\"Modified DataFrame\")print(data_frame_mod)", "e": 1758, "s": 1333, "text": null }, { "code": null, "e": 1766, "s": 1758, "text": "Output:" }, { "code": null, "e": 1974, "s": 1766, "text": "[1] \"Original DataFrame\"\ncol1 col2 col3 \n1 Grp1 1 1 \n2 Grp1 2 2 \n3 Grp2 3 1 \n4 Grp2 1 2 \n5 Grp3 2 1 \n6 Grp3 3 2 \n[1] \"Modified DataFrame\" \ncol1 col2 col3 \n6 Grp3 3 2" }, { "code": null, "e": 2221, "s": 1974, "text": "The dataframe rows can also be generated randomly by using the set.seed() method. It generates a random sample, which is then fed into any arbitrary random dummy generator function. The rows can then be extracted by comparing them to a function. " }, { "code": null, "e": 2267, "s": 2221, "text": "Example: Splitting dataframe by rows randomly" }, { "code": null, "e": 2269, "s": 2267, "text": "R" }, { "code": "# create first dataframedata_frame1<-data.frame(col1=c(rep('Grp1',2), rep('Grp2',2), rep('Grp3',2)), col2=rep(1:3,2), col3=rep(1:2,3), col4 = letters[1:6] ) print(\"Original DataFrame\")print(data_frame1) # extracting last two columnsset.seed(99999) rows <- nrow(data_frame1)rand <- rbinom(rows, 2, 0.5) data_frame_mod <- data_frame1[rand == 0, ] print(\"Modified DataFrame\")print(data_frame_mod)", "e": 2849, "s": 2269, "text": null }, { "code": null, "e": 2857, "s": 2849, "text": "Output:" }, { "code": null, "e": 3132, "s": 2857, "text": "[1] \"Original DataFrame\" \ncol1 col2 col3 col4\n 1 Grp1 1 1 a \n2 Grp1 2 2 b \n3 Grp2 3 1 c \n4 Grp2 1 2 d \n5 Grp3 2 1 e \n6 Grp3 3 2 f \n[1] \"Modified DataFrame\" \ncol1 col2 col3 col4\n5 Grp3 2 1 e\n6 Grp3 3 2 f" }, { "code": null, "e": 3346, "s": 3132, "text": "The dataframe can also be referenced using the column names. Multiple column names can be specified using the c() method containing column names as strings. The column names may be contiguous or random in nature. " }, { "code": null, "e": 3354, "s": 3346, "text": "Syntax:" }, { "code": null, "e": 3385, "s": 3354, "text": "data-frame[,c(col1, col2,...)]" }, { "code": null, "e": 3430, "s": 3385, "text": "Example: splitting dataframe by column names" }, { "code": null, "e": 3432, "s": 3430, "text": "R" }, { "code": "# create first dataframedata_frame1<-data.frame(col1=c(rep('Grp1',2), rep('Grp2',2), rep('Grp3',2)), col2=rep(1:3,2), col3=rep(1:2,3), col4 = letters[1:6] ) print(\"Original DataFrame\")print(data_frame1) # extracting sixth rowdata_frame_mod <- data_frame1[,c(\"col2\",\"col4\")]print(\"Modified DataFrame\")print(data_frame_mod)", "e": 3909, "s": 3432, "text": null }, { "code": null, "e": 3917, "s": 3909, "text": "Output:" }, { "code": null, "e": 4216, "s": 3917, "text": "[1] \"Original DataFrame\" \ncol1 col2 col3 col4\n 1 Grp1 1 1 a \n2 Grp1 2 2 b \n3 Grp2 3 1 c \n4 Grp2 1 2 d \n5 Grp3 2 1 e \n6 Grp3 3 2 f \n[1] \"Modified DataFrame\" \ncol2 col4 \n1 1 a \n2 2 b \n3 3 c \n4 1 d \n5 2 e \n6 3 f" }, { "code": null, "e": 4392, "s": 4216, "text": "The dataframe can also be referenced using the column indices. Individual, as well as multiple columns, can be extracted from the dataframe by specifying the column position. " }, { "code": null, "e": 4400, "s": 4392, "text": "Syntax:" }, { "code": null, "e": 4439, "s": 4400, "text": "data-frame[,start-col-num:end-col-num]" }, { "code": null, "e": 4482, "s": 4439, "text": "Example: Split dataframe by column indices" }, { "code": null, "e": 4484, "s": 4482, "text": "R" }, { "code": "# create first dataframedata_frame1<-data.frame(col1=c(rep('Grp1',2), rep('Grp2',2), rep('Grp3',2)), col2=rep(1:3,2), col3=rep(1:2,3), col4 = letters[1:6] ) print(\"Original DataFrame\")print(data_frame1) # extracting last two columnsdata_frame_mod <- data_frame1[,c(3:4)]print(\"Modified DataFrame\")print(data_frame_mod)", "e": 4958, "s": 4484, "text": null }, { "code": null, "e": 4966, "s": 4958, "text": "Output:" }, { "code": null, "e": 5265, "s": 4966, "text": "[1] \"Original DataFrame\" \ncol1 col2 col3 col4\n 1 Grp1 1 1 a \n2 Grp1 2 2 b \n3 Grp2 3 1 c \n4 Grp2 1 2 d \n5 Grp3 2 1 e \n6 Grp3 3 2 f \n[1] \"Modified DataFrame\" \ncol3 col4 \n1 1 a \n2 2 b \n3 1 c \n4 2 d \n5 1 e \n6 2 f" }, { "code": null, "e": 5272, "s": 5265, "text": "Picked" }, { "code": null, "e": 5293, "s": 5272, "text": "R DataFrame-Programs" }, { "code": null, "e": 5305, "s": 5293, "text": "R-DataFrame" }, { "code": null, "e": 5316, "s": 5305, "text": "R Language" }, { "code": null, "e": 5327, "s": 5316, "text": "R Programs" } ]
Lock framework vs Thread synchronization in Java
24 Sep, 2021 Thread synchronization mechanism can be achieved using Lock framework, which is present in java.util.concurrent package. Lock framework works like synchronized blocks except locks can be more sophisticated than Java’s synchronized blocks. Locks allow more flexible structuring of synchronized code. This new approach was introduced in Java 5 to tackle the below-mentioned problem of synchronization. Let’s look at an Vector class, which has many synchronized methods. When there are 100 synchronized methods in a class, only one thread can be executed of these 100 methods at any given point in time. Only one thread is allowed to access only one method at any given point of time using a synchronized block. This is a very expensive operation. Locks avoid this by allowing the configuration of various locks for different purpose. One can have couple of methods synchronized under one lock and other methods under a different lock. This allows more concurrency and also increases overall performance. Example: Lock lock = new ReentrantLock(); lock.lock(); // Critical section lock.unlock(); A lock is acquired via the lock() method and released via the unlock() method. Invoking an unlock() without lock() will throw an exception. As already mentioned the Lock interface is present in java.util.concurrent.locks package and the ReentrantLock implements the Lock interface. Note: The number of lock() calls should always be equal to the number of unlock() calls. In the below code, the user has created one resource named “TestResource” which has two methods and two different locks for each respectively. There are two jobs named “DisplayJob” and “ReadJob”. The LockTest class creates 5 threads to accomplish ‘DisplayJob’ and 5 threads to accomplish ‘ReadJob’. All the 10 threads share single resource “TestResource”. Java import java.util.Date;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock; // Test class to test the lock example// 5 threads are created with DisplayJob// and 5 thread are created with ReadJob.// Both these jobs use single TestResource named "test".public class LockTest{ public static void main(String[] args) { TestResource test = new TestResource(); Thread thread[] = new Thread[10]; for (int i = 0; i < 5; i++) { thread[i] = new Thread(new DisplayJob(test), "Thread " + i); } for (int i = 5; i < 10; i++) { thread[i] = new Thread(new ReadJob(test), "Thread " + i); } for (int i = 0; i < 10; i++) { thread[i].start(); } } }// DisplayJob class implementing Runnable interface.// This uses TestResource object passed in the constructor.// run method invokes displayRecord method on TestResource.class DisplayJob implements Runnable{ private TestResource test; DisplayJob(TestResource tr) { test = tr; } @Override public void run() { System.out.println("display job"); test.displayRecord(new Object()); }}// ReadJob class implementing Runnable interface.// which uses TestResource object passed in the constructor.// run method invokes readRecord method on TestResource.class ReadJob implements Runnable{ private TestResource test; ReadJob(TestResource tr) { test = tr; } @Override public void run() { System.out.println("read job"); test.readRecord(new Object()); }}// Class which has two locks and two methods. class TestResource{ // displayQueueLock is created to make // displayQueueLock thread safe. // When T1 acquires lock on testresource(o1) // object displayRecord method // T2 has to wait for lock to be released // by T1 on testresource(o1) object // displayRecord method. But T3, can execute // readRecord method with out waiting for lock // to be released by t1 as // readRecord method uses readQueueLock not // displayQueueLock. private final Lock displayQueueLock = new ReentrantLock(); private final Lock readQueueLock = new ReentrantLock(); // displayRecord uses displayQueueLock to // achieve thread safety. public void displayRecord(Object document) { final Lock displayLock = this.displayQueueLock; displayLock.lock(); try { Long duration = (long) (Math.random() * 10000); System.out.println(Thread.currentThread(). getName() + ": TestResource: display a Job"+ " during " + (duration / 1000) + " seconds ::"+ " Time - " + new Date()); Thread.sleep(duration); } catch (InterruptedException e) { e.printStackTrace(); } finally { System.out.printf("%s: The document has been"+ " dispalyed\n", Thread.currentThread().getName()); displayLock.unlock(); } } // readRecord uses readQueueLock to achieve thread safety. public void readRecord(Object document) { final Lock readQueueLock = this.readQueueLock; readQueueLock.lock(); try { Long duration = (long) (Math.random() * 10000); System.out.println (Thread.currentThread().getName() + ": TestResource: reading a Job during " + (duration / 1000) + " seconds :: Time - " + new Date()); Thread.sleep(duration); } catch (InterruptedException e) { e.printStackTrace(); } finally { System.out.printf("%s: The document has"+ " been read\n", Thread.currentThread().getName()); readQueueLock.unlock(); } }} Output: display job display job display job display job display job read job read job read job read job read job Thread 5: TestResource: reading a Job during 4 seconds :: Time – Wed Feb 27 15:49:53 UTC 2019 Thread 0: TestResource: display a Job during 6 seconds :: Time – Wed Feb 27 15:49:53 UTC 2019 Thread 5: The document has been read Thread 6: TestResource: reading a Job during 4 seconds :: Time – Wed Feb 27 15:49:58 UTC 2019 In the above example, DisplayJob not required to wait for ReadJob threads to complete the task as ReadJob and Display job uses two different locks. This can not be possible with “synchronized”. Differences are as follows: Lock.lock(); myMethod();Lock.unlock(); unlock() cant be executed in this code if any exception being thrown from myMethod(). khushboogoyal499 Java-Multithreading Difference Between Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between Synchronous and Asynchronous Transmission Difference Between Method Overloading and Method Overriding in Java Difference Between Go-Back-N and Selective Repeat Protocol Time complexities of different data structures Difference between Compile-time and Run-time Polymorphism in Java Arrays in Java Object Oriented Programming (OOPs) Concept in Java Arrays.sort() in Java with examples Reverse a string in Java Split() String method in Java with examples
[ { "code": null, "e": 54, "s": 26, "text": "\n24 Sep, 2021" }, { "code": null, "e": 454, "s": 54, "text": "Thread synchronization mechanism can be achieved using Lock framework, which is present in java.util.concurrent package. Lock framework works like synchronized blocks except locks can be more sophisticated than Java’s synchronized blocks. Locks allow more flexible structuring of synchronized code. This new approach was introduced in Java 5 to tackle the below-mentioned problem of synchronization." }, { "code": null, "e": 1056, "s": 454, "text": "Let’s look at an Vector class, which has many synchronized methods. When there are 100 synchronized methods in a class, only one thread can be executed of these 100 methods at any given point in time. Only one thread is allowed to access only one method at any given point of time using a synchronized block. This is a very expensive operation. Locks avoid this by allowing the configuration of various locks for different purpose. One can have couple of methods synchronized under one lock and other methods under a different lock. This allows more concurrency and also increases overall performance." }, { "code": null, "e": 1066, "s": 1056, "text": "Example: " }, { "code": null, "e": 1148, "s": 1066, "text": "Lock lock = new ReentrantLock();\nlock.lock();\n\n// Critical section\nlock.unlock();" }, { "code": null, "e": 1431, "s": 1148, "text": "A lock is acquired via the lock() method and released via the unlock() method. Invoking an unlock() without lock() will throw an exception. As already mentioned the Lock interface is present in java.util.concurrent.locks package and the ReentrantLock implements the Lock interface. " }, { "code": null, "e": 1520, "s": 1431, "text": "Note: The number of lock() calls should always be equal to the number of unlock() calls." }, { "code": null, "e": 1876, "s": 1520, "text": "In the below code, the user has created one resource named “TestResource” which has two methods and two different locks for each respectively. There are two jobs named “DisplayJob” and “ReadJob”. The LockTest class creates 5 threads to accomplish ‘DisplayJob’ and 5 threads to accomplish ‘ReadJob’. All the 10 threads share single resource “TestResource”." }, { "code": null, "e": 1881, "s": 1876, "text": "Java" }, { "code": "import java.util.Date;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock; // Test class to test the lock example// 5 threads are created with DisplayJob// and 5 thread are created with ReadJob.// Both these jobs use single TestResource named \"test\".public class LockTest{ public static void main(String[] args) { TestResource test = new TestResource(); Thread thread[] = new Thread[10]; for (int i = 0; i < 5; i++) { thread[i] = new Thread(new DisplayJob(test), \"Thread \" + i); } for (int i = 5; i < 10; i++) { thread[i] = new Thread(new ReadJob(test), \"Thread \" + i); } for (int i = 0; i < 10; i++) { thread[i].start(); } } }// DisplayJob class implementing Runnable interface.// This uses TestResource object passed in the constructor.// run method invokes displayRecord method on TestResource.class DisplayJob implements Runnable{ private TestResource test; DisplayJob(TestResource tr) { test = tr; } @Override public void run() { System.out.println(\"display job\"); test.displayRecord(new Object()); }}// ReadJob class implementing Runnable interface.// which uses TestResource object passed in the constructor.// run method invokes readRecord method on TestResource.class ReadJob implements Runnable{ private TestResource test; ReadJob(TestResource tr) { test = tr; } @Override public void run() { System.out.println(\"read job\"); test.readRecord(new Object()); }}// Class which has two locks and two methods. class TestResource{ // displayQueueLock is created to make // displayQueueLock thread safe. // When T1 acquires lock on testresource(o1) // object displayRecord method // T2 has to wait for lock to be released // by T1 on testresource(o1) object // displayRecord method. But T3, can execute // readRecord method with out waiting for lock // to be released by t1 as // readRecord method uses readQueueLock not // displayQueueLock. private final Lock displayQueueLock = new ReentrantLock(); private final Lock readQueueLock = new ReentrantLock(); // displayRecord uses displayQueueLock to // achieve thread safety. public void displayRecord(Object document) { final Lock displayLock = this.displayQueueLock; displayLock.lock(); try { Long duration = (long) (Math.random() * 10000); System.out.println(Thread.currentThread(). getName() + \": TestResource: display a Job\"+ \" during \" + (duration / 1000) + \" seconds ::\"+ \" Time - \" + new Date()); Thread.sleep(duration); } catch (InterruptedException e) { e.printStackTrace(); } finally { System.out.printf(\"%s: The document has been\"+ \" dispalyed\\n\", Thread.currentThread().getName()); displayLock.unlock(); } } // readRecord uses readQueueLock to achieve thread safety. public void readRecord(Object document) { final Lock readQueueLock = this.readQueueLock; readQueueLock.lock(); try { Long duration = (long) (Math.random() * 10000); System.out.println (Thread.currentThread().getName() + \": TestResource: reading a Job during \" + (duration / 1000) + \" seconds :: Time - \" + new Date()); Thread.sleep(duration); } catch (InterruptedException e) { e.printStackTrace(); } finally { System.out.printf(\"%s: The document has\"+ \" been read\\n\", Thread.currentThread().getName()); readQueueLock.unlock(); } }}", "e": 5917, "s": 1881, "text": null }, { "code": null, "e": 5926, "s": 5917, "text": "Output: " }, { "code": null, "e": 6352, "s": 5926, "text": "display job display job display job display job display job read job read job read job read job read job Thread 5: TestResource: reading a Job during 4 seconds :: Time – Wed Feb 27 15:49:53 UTC 2019 Thread 0: TestResource: display a Job during 6 seconds :: Time – Wed Feb 27 15:49:53 UTC 2019 Thread 5: The document has been read Thread 6: TestResource: reading a Job during 4 seconds :: Time – Wed Feb 27 15:49:58 UTC 2019 " }, { "code": null, "e": 6546, "s": 6352, "text": "In the above example, DisplayJob not required to wait for ReadJob threads to complete the task as ReadJob and Display job uses two different locks. This can not be possible with “synchronized”." }, { "code": null, "e": 6576, "s": 6546, "text": "Differences are as follows: " }, { "code": null, "e": 6615, "s": 6576, "text": "Lock.lock(); myMethod();Lock.unlock();" }, { "code": null, "e": 6701, "s": 6615, "text": "unlock() cant be executed in this code if any exception being thrown from myMethod()." }, { "code": null, "e": 6720, "s": 6703, "text": "khushboogoyal499" }, { "code": null, "e": 6740, "s": 6720, "text": "Java-Multithreading" }, { "code": null, "e": 6759, "s": 6740, "text": "Difference Between" }, { "code": null, "e": 6764, "s": 6759, "text": "Java" }, { "code": null, "e": 6769, "s": 6764, "text": "Java" }, { "code": null, "e": 6867, "s": 6769, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6928, "s": 6867, "text": "Difference between Synchronous and Asynchronous Transmission" }, { "code": null, "e": 6996, "s": 6928, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 7055, "s": 6996, "text": "Difference Between Go-Back-N and Selective Repeat Protocol" }, { "code": null, "e": 7102, "s": 7055, "text": "Time complexities of different data structures" }, { "code": null, "e": 7168, "s": 7102, "text": "Difference between Compile-time and Run-time Polymorphism in Java" }, { "code": null, "e": 7183, "s": 7168, "text": "Arrays in Java" }, { "code": null, "e": 7234, "s": 7183, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 7270, "s": 7234, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 7295, "s": 7270, "text": "Reverse a string in Java" } ]
MongoDB - Drop Collection
In this chapter, we will see how to drop a collection using MongoDB. MongoDB's db.collection.drop() is used to drop a collection from the database. Basic syntax of drop() command is as follows − db.COLLECTION_NAME.drop() First, check the available collections into your database mydb. >use mydb switched to db mydb >show collections mycol mycollection system.indexes tutorialspoint > Now drop the collection with the name mycollection. >db.mycollection.drop() true > Again check the list of collections into database. >show collections mycol system.indexes tutorialspoint > drop() method will return true, if the selected collection is dropped successfully, otherwise it will return false.
[ { "code": null, "e": 2756, "s": 2687, "text": "In this chapter, we will see how to drop a collection using MongoDB." }, { "code": null, "e": 2835, "s": 2756, "text": "MongoDB's db.collection.drop() is used to drop a collection from the database." }, { "code": null, "e": 2882, "s": 2835, "text": "Basic syntax of drop() command is as follows −" }, { "code": null, "e": 2909, "s": 2882, "text": "db.COLLECTION_NAME.drop()\n" }, { "code": null, "e": 2973, "s": 2909, "text": "First, check the available collections into your database mydb." }, { "code": null, "e": 3072, "s": 2973, "text": ">use mydb\nswitched to db mydb\n>show collections\nmycol\nmycollection\nsystem.indexes\ntutorialspoint\n>" }, { "code": null, "e": 3124, "s": 3072, "text": "Now drop the collection with the name mycollection." }, { "code": null, "e": 3155, "s": 3124, "text": ">db.mycollection.drop()\ntrue\n>" }, { "code": null, "e": 3206, "s": 3155, "text": "Again check the list of collections into database." }, { "code": null, "e": 3262, "s": 3206, "text": ">show collections\nmycol\nsystem.indexes\ntutorialspoint\n>" } ]
Creating a User With an Expiry Date in Linux
22 Jun, 2020 Linux is a multi-user system and thus, it allows more than one person to interact with the system at the same time. There are numerous ways in which we can create new users in Linux. The system administrator has the responsibility to manage different users of the system. For types of users in Linux refer Users in Linux System Administration. User accounts with an expiration date provide a facility to create a user account for temporary use. Let’s discuss how to create a user with an expiry date in Linux. Syntax: $ sudo useradd -e YYYY-MM-DD username In the above command: useradd is a command used to add a new user account. -e YYYY-MM-DD specifies the expiry date for a new user account. Let us create a new user with Username: Test and Expiry Date: June 10 2020.In order to create a new user execute the following command in terminal. sudo useradd -e 2020-06-10 Test In order to login as a newly created user, a password needs to set up. Thus, we use paswd command. To set a new password execute the following command in the terminal. sudo passwd Test Once the command executes a prompt will ask to set a new password. To verify the user account expiration details we can use chage command.To get the details, execute the following command in the terminal. sudo chage -l Test Thus, in this way, we can create a new user account with an expiration date. linux Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Docker - COPY Instruction scp command in Linux with Examples chown command in Linux with Examples SED command in Linux | Set 2 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": "\n22 Jun, 2020" }, { "code": null, "e": 374, "s": 28, "text": "Linux is a multi-user system and thus, it allows more than one person to interact with the system at the same time. There are numerous ways in which we can create new users in Linux. The system administrator has the responsibility to manage different users of the system. For types of users in Linux refer Users in Linux System Administration. " }, { "code": null, "e": 541, "s": 374, "text": "User accounts with an expiration date provide a facility to create a user account for temporary use. Let’s discuss how to create a user with an expiry date in Linux. " }, { "code": null, "e": 550, "s": 541, "text": "Syntax: " }, { "code": null, "e": 589, "s": 550, "text": "$ sudo useradd -e YYYY-MM-DD username\n" }, { "code": null, "e": 611, "s": 589, "text": "In the above command:" }, { "code": null, "e": 665, "s": 611, "text": "useradd is a command used to add a new user account. " }, { "code": null, "e": 730, "s": 665, "text": "-e YYYY-MM-DD specifies the expiry date for a new user account. " }, { "code": null, "e": 879, "s": 730, "text": "Let us create a new user with Username: Test and Expiry Date: June 10 2020.In order to create a new user execute the following command in terminal. " }, { "code": null, "e": 912, "s": 879, "text": "sudo useradd -e 2020-06-10 Test\n" }, { "code": null, "e": 1081, "s": 912, "text": "In order to login as a newly created user, a password needs to set up. Thus, we use paswd command. To set a new password execute the following command in the terminal. " }, { "code": null, "e": 1099, "s": 1081, "text": "sudo passwd Test\n" }, { "code": null, "e": 1168, "s": 1099, "text": "Once the command executes a prompt will ask to set a new password. " }, { "code": null, "e": 1308, "s": 1168, "text": "To verify the user account expiration details we can use chage command.To get the details, execute the following command in the terminal. " }, { "code": null, "e": 1328, "s": 1308, "text": "sudo chage -l Test\n" }, { "code": null, "e": 1406, "s": 1328, "text": "Thus, in this way, we can create a new user account with an expiration date. " }, { "code": null, "e": 1412, "s": 1406, "text": "linux" }, { "code": null, "e": 1423, "s": 1412, "text": "Linux-Unix" }, { "code": null, "e": 1521, "s": 1423, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1547, "s": 1521, "text": "Docker - COPY Instruction" }, { "code": null, "e": 1582, "s": 1547, "text": "scp command in Linux with Examples" }, { "code": null, "e": 1619, "s": 1582, "text": "chown command in Linux with Examples" }, { "code": null, "e": 1648, "s": 1619, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 1687, "s": 1648, "text": "Introduction to Linux Operating System" }, { "code": null, "e": 1727, "s": 1687, "text": "Array Basics in Shell Scripting | Set 1" }, { "code": null, "e": 1764, "s": 1727, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 1801, "s": 1764, "text": "chmod command in Linux with examples" }, { "code": null, "e": 1835, "s": 1801, "text": "mv command in Linux with examples" } ]
GATE | GATE-IT-2004 | Question 74 - GeeksforGeeks
15 Oct, 2019 Insert into department values (1, 'Mathematics') Insert into department values (2, 'Physics') Insert into student values (l, 'Navin', 1) Insert into student values (2, 'Mukesh', 2) Insert into student values (3, 'Gita', 1) How many rows and columns will be retrieved by the following SQL statement? Select * from student, department (A) 0 row and 4 columns(B) 3 rows and 4 columns(C) 3 rows and 5 columns(D) 6 rows and 5 columnsAnswer: (D)Explanation: Simple,Cartesian product of two tables will result Rows = 3*2 = 6 Columns = 3+2 = 5 Option (D) is correct. Quiz of this Question GATE IT 2004 GATE-GATE IT 2004 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | Gate IT 2007 | Question 25 GATE | GATE-CS-2000 | Question 41 GATE | GATE-CS-2001 | Question 39 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE-CS-2006 | Question 47 GATE | GATE MOCK 2017 | Question 24 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25695, "s": 25667, "text": "\n15 Oct, 2019" }, { "code": null, "e": 25919, "s": 25695, "text": "Insert into department values (1, 'Mathematics')\nInsert into department values (2, 'Physics')\nInsert into student values (l, 'Navin', 1)\nInsert into student values (2, 'Mukesh', 2)\nInsert into student values (3, 'Gita', 1) " }, { "code": null, "e": 25995, "s": 25919, "text": "How many rows and columns will be retrieved by the following SQL statement?" }, { "code": null, "e": 26029, "s": 25995, "text": "Select * from student, department" }, { "code": null, "e": 26199, "s": 26029, "text": "(A) 0 row and 4 columns(B) 3 rows and 4 columns(C) 3 rows and 5 columns(D) 6 rows and 5 columnsAnswer: (D)Explanation: Simple,Cartesian product of two tables will result" }, { "code": null, "e": 26234, "s": 26199, "text": "Rows = 3*2 = 6 \nColumns = 3+2 = 5 " }, { "code": null, "e": 26257, "s": 26234, "text": "Option (D) is correct." }, { "code": null, "e": 26280, "s": 26257, "text": " Quiz of this Question" }, { "code": null, "e": 26293, "s": 26280, "text": "GATE IT 2004" }, { "code": null, "e": 26311, "s": 26293, "text": "GATE-GATE IT 2004" }, { "code": null, "e": 26316, "s": 26311, "text": "GATE" }, { "code": null, "e": 26414, "s": 26316, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26448, "s": 26414, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 26482, "s": 26448, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 26516, "s": 26482, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 26549, "s": 26516, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 26585, "s": 26549, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 26619, "s": 26585, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 26655, "s": 26619, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 26689, "s": 26655, "text": "GATE | Gate IT 2008 | Question 43" }, { "code": null, "e": 26723, "s": 26689, "text": "GATE | GATE-CS-2009 | Question 38" } ]
PySpark - Order by multiple columns - GeeksforGeeks
19 Dec, 2021 In this article, we are going to see how to orderby multiple columns in PySpark DataFrames through Python. Python3 # importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [["1", "sravan", "company 1"], ["2", "ojaswi", "company 1"], ["3", "rohith", "company 2"], ["4", "sridevi", "company 1"], ["5", "bobby", "company 1"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) dataframe.show() Output: orderby means we are going to sort the dataframe by multiple columns in ascending or descending order. we can do this by using the following methods. This function will return the dataframe after ordering the multiple columns. It will sort first based on the column name given. Syntax: Ascending order: dataframe.orderBy([‘column1′,’column2′,......,’column n’], ascending=True).show() Descending Order: dataframe.orderBy([‘column1′,’column2′,......,’column n’], ascending=False).show() where: dataframe is the Pyspark Input dataframe ascending=True specifies to sort the dataframe in ascending order ascending=False specifies to sort the dataframe in descending order Example 1: Sort the PySpark dataframe in ascending order with orderBy(). Python3 # importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [["1", "sravan", "company 1"], ["2", "ojaswi", "company 1"], ["3", "rohith", "company 2"], ["4", "sridevi", "company 1"], ["5", "bobby", "company 1"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # orderBy dataframe in asc orderdataframe.orderBy(['Name', 'ID', 'Company'], ascending=True).show() Output: Example 2: Sort the PySpark dataframe in descending order with orderBy(). Python3 # importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [["1", "sravan", "company 1"], ["2", "ojaswi", "company 1"], ["3", "rohith", "company 2"], ["4", "sridevi", "company 1"], ["5", "bobby", "company 1"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # orderBy dataframe in desc orderdataframe.orderBy(['Name', 'ID', 'Company'], ascending=False).show() Output: This function will return the dataframe after ordering the multiple columns. It will sort first based on the column name given. Syntax: Ascending order: dataframe.sort([‘column1′,’column2′,......,’column n’], ascending=True).show() Descending Order: dataframe.sort([‘column1′,’column2′,......,’column n’], ascending=False).show() where, dataframe is the Pyspark Input dataframeascending=True specifies to sort the dataframe in ascending orderascending=False specifies to sort the dataframe in descending order dataframe is the Pyspark Input dataframe ascending=True specifies to sort the dataframe in ascending order ascending=False specifies to sort the dataframe in descending order Example 1: Sort PySpark dataframe in ascending order Python3 # importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [["1", "sravan", "company 1"], ["2", "ojaswi", "company 1"], ["3", "rohith", "company 2"], ["4", "sridevi", "company 1"], ["5", "bobby", "company 1"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # orderBy dataframe in asc orderdataframe.sort(['Name', 'ID', 'Company'], ascending=True).show() Output: Example 2: Sort the PySpark dataframe in descending order Python3 # importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [["1", "sravan", "company 1"], ["2", "ojaswi", "company 1"], ["3", "rohith", "company 2"], ["4", "sridevi", "company 1"], ["5", "bobby", "company 1"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # orderBy dataframe in desc orderdataframe.sort(['Name', 'ID', 'Company'], ascending=False).show() Output: Picked Python-Pyspark Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n19 Dec, 2021" }, { "code": null, "e": 25645, "s": 25537, "text": "In this article, we are going to see how to orderby multiple columns in PySpark DataFrames through Python." }, { "code": null, "e": 25653, "s": 25645, "text": "Python3" }, { "code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [[\"1\", \"sravan\", \"company 1\"], [\"2\", \"ojaswi\", \"company 1\"], [\"3\", \"rohith\", \"company 2\"], [\"4\", \"sridevi\", \"company 1\"], [\"5\", \"bobby\", \"company 1\"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) dataframe.show()", "e": 26264, "s": 25653, "text": null }, { "code": null, "e": 26272, "s": 26264, "text": "Output:" }, { "code": null, "e": 26422, "s": 26272, "text": "orderby means we are going to sort the dataframe by multiple columns in ascending or descending order. we can do this by using the following methods." }, { "code": null, "e": 26550, "s": 26422, "text": "This function will return the dataframe after ordering the multiple columns. It will sort first based on the column name given." }, { "code": null, "e": 26558, "s": 26550, "text": "Syntax:" }, { "code": null, "e": 26657, "s": 26558, "text": "Ascending order: dataframe.orderBy([‘column1′,’column2′,......,’column n’], ascending=True).show()" }, { "code": null, "e": 26758, "s": 26657, "text": "Descending Order: dataframe.orderBy([‘column1′,’column2′,......,’column n’], ascending=False).show()" }, { "code": null, "e": 26765, "s": 26758, "text": "where:" }, { "code": null, "e": 26806, "s": 26765, "text": "dataframe is the Pyspark Input dataframe" }, { "code": null, "e": 26872, "s": 26806, "text": "ascending=True specifies to sort the dataframe in ascending order" }, { "code": null, "e": 26940, "s": 26872, "text": "ascending=False specifies to sort the dataframe in descending order" }, { "code": null, "e": 27013, "s": 26940, "text": "Example 1: Sort the PySpark dataframe in ascending order with orderBy()." }, { "code": null, "e": 27021, "s": 27013, "text": "Python3" }, { "code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [[\"1\", \"sravan\", \"company 1\"], [\"2\", \"ojaswi\", \"company 1\"], [\"3\", \"rohith\", \"company 2\"], [\"4\", \"sridevi\", \"company 1\"], [\"5\", \"bobby\", \"company 1\"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # orderBy dataframe in asc orderdataframe.orderBy(['Name', 'ID', 'Company'], ascending=True).show()", "e": 27732, "s": 27021, "text": null }, { "code": null, "e": 27740, "s": 27732, "text": "Output:" }, { "code": null, "e": 27814, "s": 27740, "text": "Example 2: Sort the PySpark dataframe in descending order with orderBy()." }, { "code": null, "e": 27822, "s": 27814, "text": "Python3" }, { "code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [[\"1\", \"sravan\", \"company 1\"], [\"2\", \"ojaswi\", \"company 1\"], [\"3\", \"rohith\", \"company 2\"], [\"4\", \"sridevi\", \"company 1\"], [\"5\", \"bobby\", \"company 1\"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # orderBy dataframe in desc orderdataframe.orderBy(['Name', 'ID', 'Company'], ascending=False).show()", "e": 28536, "s": 27822, "text": null }, { "code": null, "e": 28544, "s": 28536, "text": "Output:" }, { "code": null, "e": 28672, "s": 28544, "text": "This function will return the dataframe after ordering the multiple columns. It will sort first based on the column name given." }, { "code": null, "e": 28680, "s": 28672, "text": "Syntax:" }, { "code": null, "e": 28776, "s": 28680, "text": "Ascending order: dataframe.sort([‘column1′,’column2′,......,’column n’], ascending=True).show()" }, { "code": null, "e": 28874, "s": 28776, "text": "Descending Order: dataframe.sort([‘column1′,’column2′,......,’column n’], ascending=False).show()" }, { "code": null, "e": 28881, "s": 28874, "text": "where," }, { "code": null, "e": 29054, "s": 28881, "text": "dataframe is the Pyspark Input dataframeascending=True specifies to sort the dataframe in ascending orderascending=False specifies to sort the dataframe in descending order" }, { "code": null, "e": 29095, "s": 29054, "text": "dataframe is the Pyspark Input dataframe" }, { "code": null, "e": 29161, "s": 29095, "text": "ascending=True specifies to sort the dataframe in ascending order" }, { "code": null, "e": 29229, "s": 29161, "text": "ascending=False specifies to sort the dataframe in descending order" }, { "code": null, "e": 29282, "s": 29229, "text": "Example 1: Sort PySpark dataframe in ascending order" }, { "code": null, "e": 29290, "s": 29282, "text": "Python3" }, { "code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [[\"1\", \"sravan\", \"company 1\"], [\"2\", \"ojaswi\", \"company 1\"], [\"3\", \"rohith\", \"company 2\"], [\"4\", \"sridevi\", \"company 1\"], [\"5\", \"bobby\", \"company 1\"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # orderBy dataframe in asc orderdataframe.sort(['Name', 'ID', 'Company'], ascending=True).show()", "e": 29995, "s": 29290, "text": null }, { "code": null, "e": 30003, "s": 29995, "text": "Output:" }, { "code": null, "e": 30061, "s": 30003, "text": "Example 2: Sort the PySpark dataframe in descending order" }, { "code": null, "e": 30069, "s": 30061, "text": "Python3" }, { "code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [[\"1\", \"sravan\", \"company 1\"], [\"2\", \"ojaswi\", \"company 1\"], [\"3\", \"rohith\", \"company 2\"], [\"4\", \"sridevi\", \"company 1\"], [\"5\", \"bobby\", \"company 1\"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # orderBy dataframe in desc orderdataframe.sort(['Name', 'ID', 'Company'], ascending=False).show()", "e": 30776, "s": 30069, "text": null }, { "code": null, "e": 30784, "s": 30776, "text": "Output:" }, { "code": null, "e": 30791, "s": 30784, "text": "Picked" }, { "code": null, "e": 30806, "s": 30791, "text": "Python-Pyspark" }, { "code": null, "e": 30813, "s": 30806, "text": "Python" }, { "code": null, "e": 30911, "s": 30813, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30943, "s": 30911, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30985, "s": 30943, "text": "Check if element exists in list in Python" }, { "code": null, "e": 31027, "s": 30985, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 31054, "s": 31027, "text": "Python Classes and Objects" }, { "code": null, "e": 31110, "s": 31054, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 31132, "s": 31110, "text": "Defaultdict in Python" }, { "code": null, "e": 31171, "s": 31132, "text": "Python | Get unique values from a list" }, { "code": null, "e": 31202, "s": 31171, "text": "Python | os.path.join() method" }, { "code": null, "e": 31231, "s": 31202, "text": "Create a directory in Python" } ]
Interview Oracle India | Set 24 (For 5 Years Experienced) - GeeksforGeeks
24 Mar, 2018 Round 1: First round was multiple choice question based on Core Java on inheritance, exception handling, type erasure, threading etc. Round 2: Second round was coding round and the questions asked to me to code was as follows – Priyanka works for an international toy company that ships by container. Her task is to the determine the lowest cost way to combine her orders for shipping. She has a list of item weights. The shipping company has a requirement that all items loaded in a container must weigh less than or equal to 4 units plus the weight of the minimum weight item. All items meeting that requirement will be shipped in one container. What is the smallest number of containers that can be contracted to ship the items based on the given list of weights? Input Format The first line contains an integer , the number of orders to ship.Next line will contain integers, , representing the orders in a weight array. Output Format Return the integer value of the number of containers Priyanka must contract ot ship all of the toys. Constraints Sample Input 8 1 2 3 21 7 12 14 21 Sample Output 4 Round 3: This round was face to face . He asked me questions on 1.hibernate(versioning, many to one mapping etc..) 2.code matrix problem . A 2n+1 (odd) size square matrix is given . We have to check if the centre element is equal to the individual sum of all the half diagonals in only ONE for loop . For example – 5*5 matrix – M = 2 9 1 4 -2 6 7 2 11 4 4 2 9 2 4 1 9 2 4 4 0 2 4 2 5 Sum of Half Diagonal 1 = 2+7=9 Sum of Half Diagonal 2 = 9+0=9 Sum of Half Diagonal 3 = 11 + -2 = 9 Sum of Half Diagonal 4 = 5+4 = 9 All the sums equal to the centre element that is M [2][2]=9, Hence return true or if any on of the sums of half diagonals doesnt match to the centre element, return false. 3. a puzzle to find a defective ball amongst a collection of balls 4. A way to synchronise booking of same seat on bookmyshow without using synchronisation like locks . Round 4: Design Round – Asked me to design a online retail System like Amazon taking into account the Customer, the Seller, the logistics and asked me to come up with database tables . Round 5 : Managerial Round – He asked me few questions on my previous projects, nature of work that i have done, few behavioural questions and one coding question. Oracle Experienced Interview Experiences Oracle Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Amazon Interview Experience for SDE1 (8 Months Experienced) 2022 Goldman Sachs Interview Experience for Technology Analyst (1.8 Years Experienced) Amazon Interview Experience for System Development Engineer (Exp - 6 months) FactSet Interview Experience (Off-Campus) 8 Months Experienced JP Morgan Chase Interview Questions Amazon Interview Questions Commonly Asked Java Programming Interview Questions | Set 2 Amazon Interview Experience for SDE-1 (Off-Campus) Amazon AWS Interview Experience for SDE-1 Difference between ANN, CNN and RNN
[ { "code": null, "e": 26739, "s": 26711, "text": "\n24 Mar, 2018" }, { "code": null, "e": 26748, "s": 26739, "text": "Round 1:" }, { "code": null, "e": 26873, "s": 26748, "text": "First round was multiple choice question based on Core Java on inheritance, exception handling, type erasure, threading etc." }, { "code": null, "e": 26882, "s": 26873, "text": "Round 2:" }, { "code": null, "e": 26967, "s": 26882, "text": "Second round was coding round and the questions asked to me to code was as follows –" }, { "code": null, "e": 27125, "s": 26967, "text": "Priyanka works for an international toy company that ships by container. Her task is to the determine the lowest cost way to combine her orders for shipping." }, { "code": null, "e": 27387, "s": 27125, "text": "She has a list of item weights. The shipping company has a requirement that all items loaded in a container must weigh less than or equal to 4 units plus the weight of the minimum weight item. All items meeting that requirement will be shipped in one container." }, { "code": null, "e": 27506, "s": 27387, "text": "What is the smallest number of containers that can be contracted to ship the items based on the given list of weights?" }, { "code": null, "e": 27519, "s": 27506, "text": "Input Format" }, { "code": null, "e": 27665, "s": 27519, "text": "The first line contains an integer , the number of orders to ship.Next line will contain integers, , representing the orders in a weight array." }, { "code": null, "e": 27679, "s": 27665, "text": "Output Format" }, { "code": null, "e": 27780, "s": 27679, "text": "Return the integer value of the number of containers Priyanka must contract ot ship all of the toys." }, { "code": null, "e": 27792, "s": 27780, "text": "Constraints" }, { "code": null, "e": 27805, "s": 27792, "text": "Sample Input" }, { "code": null, "e": 27828, "s": 27805, "text": "8\n1 2 3 21 7 12 14 21\n" }, { "code": null, "e": 27842, "s": 27828, "text": "Sample Output" }, { "code": null, "e": 27844, "s": 27842, "text": "4" }, { "code": null, "e": 27853, "s": 27844, "text": "Round 3:" }, { "code": null, "e": 27908, "s": 27853, "text": "This round was face to face . He asked me questions on" }, { "code": null, "e": 27959, "s": 27908, "text": "1.hibernate(versioning, many to one mapping etc..)" }, { "code": null, "e": 28159, "s": 27959, "text": "2.code matrix problem . A 2n+1 (odd) size square matrix is given . We have to check if the centre element is equal to the individual sum of all the half diagonals in only ONE for loop . For example –" }, { "code": null, "e": 28172, "s": 28159, "text": "5*5 matrix –" }, { "code": null, "e": 28197, "s": 28172, "text": "M = 2 9 1 4 -2" }, { "code": null, "e": 28216, "s": 28197, "text": "6 7 2 11 4" }, { "code": null, "e": 28233, "s": 28216, "text": "4 2 9 2 4" }, { "code": null, "e": 28252, "s": 28233, "text": "1 9 2 4 4" }, { "code": null, "e": 28270, "s": 28252, "text": "0 2 4 2 5" }, { "code": null, "e": 28303, "s": 28272, "text": "Sum of Half Diagonal 1 = 2+7=9" }, { "code": null, "e": 28334, "s": 28303, "text": "Sum of Half Diagonal 2 = 9+0=9" }, { "code": null, "e": 28371, "s": 28334, "text": "Sum of Half Diagonal 3 = 11 + -2 = 9" }, { "code": null, "e": 28404, "s": 28371, "text": "Sum of Half Diagonal 4 = 5+4 = 9" }, { "code": null, "e": 28576, "s": 28404, "text": "All the sums equal to the centre element that is M [2][2]=9, Hence return true or if any on of the sums of half diagonals doesnt match to the centre element, return false." }, { "code": null, "e": 28645, "s": 28578, "text": "3. a puzzle to find a defective ball amongst a collection of balls" }, { "code": null, "e": 28747, "s": 28645, "text": "4. A way to synchronise booking of same seat on bookmyshow without using synchronisation like locks ." }, { "code": null, "e": 28756, "s": 28747, "text": "Round 4:" }, { "code": null, "e": 28932, "s": 28756, "text": "Design Round – Asked me to design a online retail System like Amazon taking into account the Customer, the Seller, the logistics and asked me to come up with database tables ." }, { "code": null, "e": 28942, "s": 28932, "text": "Round 5 :" }, { "code": null, "e": 28961, "s": 28942, "text": "Managerial Round –" }, { "code": null, "e": 29096, "s": 28961, "text": "He asked me few questions on my previous projects, nature of work that i have done, few behavioural questions and one coding question." }, { "code": null, "e": 29105, "s": 29098, "text": "Oracle" }, { "code": null, "e": 29117, "s": 29105, "text": "Experienced" }, { "code": null, "e": 29139, "s": 29117, "text": "Interview Experiences" }, { "code": null, "e": 29146, "s": 29139, "text": "Oracle" }, { "code": null, "e": 29244, "s": 29146, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29309, "s": 29244, "text": "Amazon Interview Experience for SDE1 (8 Months Experienced) 2022" }, { "code": null, "e": 29391, "s": 29309, "text": "Goldman Sachs Interview Experience for Technology Analyst (1.8 Years Experienced)" }, { "code": null, "e": 29468, "s": 29391, "text": "Amazon Interview Experience for System Development Engineer (Exp - 6 months)" }, { "code": null, "e": 29531, "s": 29468, "text": "FactSet Interview Experience (Off-Campus) 8 Months Experienced" }, { "code": null, "e": 29567, "s": 29531, "text": "JP Morgan Chase Interview Questions" }, { "code": null, "e": 29594, "s": 29567, "text": "Amazon Interview Questions" }, { "code": null, "e": 29654, "s": 29594, "text": "Commonly Asked Java Programming Interview Questions | Set 2" }, { "code": null, "e": 29705, "s": 29654, "text": "Amazon Interview Experience for SDE-1 (Off-Campus)" }, { "code": null, "e": 29747, "s": 29705, "text": "Amazon AWS Interview Experience for SDE-1" } ]
Python Program for array rotation - GeeksforGeeks
19 Feb, 2022 Write a function rotate(ar[], d, n) that rotates arr[] of size n by d elements. Rotation of the above array by 2 will make array METHOD 1 (Using temp array): Input arr[] = [1, 2, 3, 4, 5, 6, 7], d = 2, n =7 1) Store d elements in a temp array temp[] = [1, 2] 2) Shift rest of the arr[] arr[] = [3, 4, 5, 6, 7, 6, 7] 3) Store back the d elements arr[] = [3, 4, 5, 6, 7, 1, 2] Python3 # function to rotate array by d elements using temp arraydef rotateArray(arr, n, d): temp = [] i = 0 while (i < d): temp.append(arr[i]) i = i + 1 i = 0 while (d < n): arr[i] = arr[d] i = i + 1 d = d + 1 arr[:] = arr[: i] + temp return arr # Driver function to test above functionarr = [1, 2, 3, 4, 5, 6, 7]print("Array after left rotation is: ", end=' ')print(rotateArray(arr, len(arr), 2)) # this code is contributed by Anabhra Tyagi Array after left rotation is: [3, 4, 5, 6, 7, 1, 2] Time complexity: O(n) Auxiliary Space: O(d) METHOD 2 (Rotate one by one) : leftRotate(arr[], d, n) start For i = 0 to i < d Left rotate all elements of arr[] by one end To rotate by one, store arr[0] in a temporary variable temp, move arr[1] to arr[0], arr[2] to arr[1] ...and finally temp to arr[n-1]Let us take the same example arr[] = [1, 2, 3, 4, 5, 6, 7], d = 2 Rotate arr[] by one 2 times We get [2, 3, 4, 5, 6, 7, 1] after first rotation and [ 3, 4, 5, 6, 7, 1, 2] after second rotation. Python3 #Function to left rotate arr[] of size n by d*/def leftRotate(arr, d, n): for i in range(d): leftRotatebyOne(arr, n) #Function to left Rotate arr[] of size n by 1*/def leftRotatebyOne(arr, n): temp = arr[0] for i in range(n-1): arr[i] = arr[i+1] arr[n-1] = temp # utility function to print an array */def printArray(arr,size): for i in range(size): print ("%d"% arr[i],end=" ") # Driver program to test above functions */arr = [1, 2, 3, 4, 5, 6, 7]leftRotate(arr, 2, 7)printArray(arr, 7) # This code is contributed by Shreyanshi Arun 3 4 5 6 7 1 2 Time complexity : O(n * d) Auxiliary Space : O(1) METHOD 3 (A Juggling Algorithm) This is an extension of method 2. Instead of moving one by one, divide the array in different sets where number of sets is equal to GCD of n and d and move the elements within sets. If GCD is 1 as is for the above example array (n = 7 and d =2), then elements will be moved within one set only, we just start with temp = arr[0] and keep moving arr[I+d] to arr[I] and finally store temp at the right place.Here is an example for n =12 and d = 3. GCD is 3 and Let arr[] be {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12} a) Elements are first moved in first set – (See below diagram for this movement arr[] after this step --> {4 2 3 7 5 6 10 8 9 1 11 12} b) Then in second set. arr[] after this step --> {4 5 3 7 8 6 10 11 9 1 2 12} c) Finally in third set. arr[] after this step --> {4 5 6 7 8 9 10 11 12 1 2 3} Python3 #Function to left rotate arr[] of size n by ddef leftRotate(arr, d, n): for i in range(gcd(d,n)): # move i-th values of blocks temp = arr[i] j = i while 1: k = j + d if k >= n: k = k - n if k == i: break arr[j] = arr[k] j = k arr[j] = temp #UTILITY FUNCTIONS#function to print an arraydef printArray(arr, size): for i in range(size): print ("%d" % arr[i], end=" ") #Function to get gcd of a and bdef gcd(a, b): if b == 0: return a; else: return gcd(b, a%b) # Driver program to test above functionsarr = [1, 2, 3, 4, 5, 6, 7]leftRotate(arr, 2, 7)printArray(arr, 7) # This code is contributed by Shreyanshi Arun 3 4 5 6 7 1 2 Time complexity : O(n) Auxiliary Space : O(1) Another Approach : Using List slicing Python3 # Python program using the List# slicing approach to rotate the arraydef rotateList(arr,d,n): arr[:]=arr[d:n]+arr[0:d] return arr# Driver function to test above functionarr = [1, 2, 3, 4, 5, 6]print(arr)print("Rotated list is")print(rotateList(arr,2,len(arr))) # this code is contributed by virusbuddah [1, 2, 3, 4, 5, 6] Rotated list is [3, 4, 5, 6, 1, 2] If array needs to be rotated by more than its length then mod should be done. For example: rotate arr[] of size n by d where d is greater than n. In this case d%n should be calculated and rotate by the result after mod. Please refer complete article on Program for array rotation for more details! Akanksha_Rai virusbuddha anabhratyagi sudhirbhandari sagar0719kumar sailahari2002 Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python | Convert string dictionary to dictionary Iterate over characters of a string in Python Python Program for factorial of a number Python | Convert set into a list Python | Check if a variable is string Python | Convert a list into a tuple Add a key:value pair to dictionary in Python Appending to list in Python dictionary Python program to find sum of elements in list Python program to find largest number in a list
[ { "code": null, "e": 26273, "s": 26245, "text": "\n19 Feb, 2022" }, { "code": null, "e": 26354, "s": 26273, "text": "Write a function rotate(ar[], d, n) that rotates arr[] of size n by d elements. " }, { "code": null, "e": 26403, "s": 26354, "text": "Rotation of the above array by 2 will make array" }, { "code": null, "e": 26432, "s": 26403, "text": "METHOD 1 (Using temp array):" }, { "code": null, "e": 26658, "s": 26432, "text": "Input arr[] = [1, 2, 3, 4, 5, 6, 7], d = 2, n =7\n1) Store d elements in a temp array\n temp[] = [1, 2]\n2) Shift rest of the arr[]\n arr[] = [3, 4, 5, 6, 7, 6, 7]\n3) Store back the d elements\n arr[] = [3, 4, 5, 6, 7, 1, 2]" }, { "code": null, "e": 26666, "s": 26658, "text": "Python3" }, { "code": "# function to rotate array by d elements using temp arraydef rotateArray(arr, n, d): temp = [] i = 0 while (i < d): temp.append(arr[i]) i = i + 1 i = 0 while (d < n): arr[i] = arr[d] i = i + 1 d = d + 1 arr[:] = arr[: i] + temp return arr # Driver function to test above functionarr = [1, 2, 3, 4, 5, 6, 7]print(\"Array after left rotation is: \", end=' ')print(rotateArray(arr, len(arr), 2)) # this code is contributed by Anabhra Tyagi", "e": 27158, "s": 26666, "text": null }, { "code": null, "e": 27211, "s": 27158, "text": "Array after left rotation is: [3, 4, 5, 6, 7, 1, 2]" }, { "code": null, "e": 27255, "s": 27211, "text": "Time complexity: O(n) Auxiliary Space: O(d)" }, { "code": null, "e": 27287, "s": 27255, "text": "METHOD 2 (Rotate one by one) : " }, { "code": null, "e": 27387, "s": 27287, "text": "leftRotate(arr[], d, n)\nstart\n For i = 0 to i < d\n Left rotate all elements of arr[] by one\nend" }, { "code": null, "e": 27714, "s": 27387, "text": "To rotate by one, store arr[0] in a temporary variable temp, move arr[1] to arr[0], arr[2] to arr[1] ...and finally temp to arr[n-1]Let us take the same example arr[] = [1, 2, 3, 4, 5, 6, 7], d = 2 Rotate arr[] by one 2 times We get [2, 3, 4, 5, 6, 7, 1] after first rotation and [ 3, 4, 5, 6, 7, 1, 2] after second rotation. " }, { "code": null, "e": 27722, "s": 27714, "text": "Python3" }, { "code": "#Function to left rotate arr[] of size n by d*/def leftRotate(arr, d, n): for i in range(d): leftRotatebyOne(arr, n) #Function to left Rotate arr[] of size n by 1*/def leftRotatebyOne(arr, n): temp = arr[0] for i in range(n-1): arr[i] = arr[i+1] arr[n-1] = temp # utility function to print an array */def printArray(arr,size): for i in range(size): print (\"%d\"% arr[i],end=\" \") # Driver program to test above functions */arr = [1, 2, 3, 4, 5, 6, 7]leftRotate(arr, 2, 7)printArray(arr, 7) # This code is contributed by Shreyanshi Arun", "e": 28303, "s": 27722, "text": null }, { "code": null, "e": 28318, "s": 28303, "text": "3 4 5 6 7 1 2 " }, { "code": null, "e": 28369, "s": 28318, "text": "Time complexity : O(n * d) Auxiliary Space : O(1) " }, { "code": null, "e": 28860, "s": 28369, "text": "METHOD 3 (A Juggling Algorithm) This is an extension of method 2. Instead of moving one by one, divide the array in different sets where number of sets is equal to GCD of n and d and move the elements within sets. If GCD is 1 as is for the above example array (n = 7 and d =2), then elements will be moved within one set only, we just start with temp = arr[0] and keep moving arr[I+d] to arr[I] and finally store temp at the right place.Here is an example for n =12 and d = 3. GCD is 3 and " }, { "code": null, "e": 28997, "s": 28860, "text": "Let arr[] be {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}\n\na) Elements are first moved in first set – (See below diagram for this movement" }, { "code": null, "e": 29248, "s": 28997, "text": " arr[] after this step --> {4 2 3 7 5 6 10 8 9 1 11 12}\n\nb) Then in second set.\n arr[] after this step --> {4 5 3 7 8 6 10 11 9 1 2 12}\n\nc) Finally in third set.\n arr[] after this step --> {4 5 6 7 8 9 10 11 12 1 2 3}" }, { "code": null, "e": 29256, "s": 29248, "text": "Python3" }, { "code": "#Function to left rotate arr[] of size n by ddef leftRotate(arr, d, n): for i in range(gcd(d,n)): # move i-th values of blocks temp = arr[i] j = i while 1: k = j + d if k >= n: k = k - n if k == i: break arr[j] = arr[k] j = k arr[j] = temp #UTILITY FUNCTIONS#function to print an arraydef printArray(arr, size): for i in range(size): print (\"%d\" % arr[i], end=\" \") #Function to get gcd of a and bdef gcd(a, b): if b == 0: return a; else: return gcd(b, a%b) # Driver program to test above functionsarr = [1, 2, 3, 4, 5, 6, 7]leftRotate(arr, 2, 7)printArray(arr, 7) # This code is contributed by Shreyanshi Arun", "e": 30030, "s": 29256, "text": null }, { "code": null, "e": 30045, "s": 30030, "text": "3 4 5 6 7 1 2 " }, { "code": null, "e": 30091, "s": 30045, "text": "Time complexity : O(n) Auxiliary Space : O(1)" }, { "code": null, "e": 30129, "s": 30091, "text": "Another Approach : Using List slicing" }, { "code": null, "e": 30137, "s": 30129, "text": "Python3" }, { "code": "# Python program using the List# slicing approach to rotate the arraydef rotateList(arr,d,n): arr[:]=arr[d:n]+arr[0:d] return arr# Driver function to test above functionarr = [1, 2, 3, 4, 5, 6]print(arr)print(\"Rotated list is\")print(rotateList(arr,2,len(arr))) # this code is contributed by virusbuddah", "e": 30443, "s": 30137, "text": null }, { "code": null, "e": 30497, "s": 30443, "text": "[1, 2, 3, 4, 5, 6]\nRotated list is\n[3, 4, 5, 6, 1, 2]" }, { "code": null, "e": 30576, "s": 30497, "text": "If array needs to be rotated by more than its length then mod should be done. " }, { "code": null, "e": 30796, "s": 30576, "text": "For example: rotate arr[] of size n by d where d is greater than n. In this case d%n should be calculated and rotate by the result after mod. Please refer complete article on Program for array rotation for more details!" }, { "code": null, "e": 30809, "s": 30796, "text": "Akanksha_Rai" }, { "code": null, "e": 30821, "s": 30809, "text": "virusbuddha" }, { "code": null, "e": 30834, "s": 30821, "text": "anabhratyagi" }, { "code": null, "e": 30849, "s": 30834, "text": "sudhirbhandari" }, { "code": null, "e": 30864, "s": 30849, "text": "sagar0719kumar" }, { "code": null, "e": 30878, "s": 30864, "text": "sailahari2002" }, { "code": null, "e": 30894, "s": 30878, "text": "Python Programs" }, { "code": null, "e": 30992, "s": 30894, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31041, "s": 30992, "text": "Python | Convert string dictionary to dictionary" }, { "code": null, "e": 31087, "s": 31041, "text": "Iterate over characters of a string in Python" }, { "code": null, "e": 31128, "s": 31087, "text": "Python Program for factorial of a number" }, { "code": null, "e": 31161, "s": 31128, "text": "Python | Convert set into a list" }, { "code": null, "e": 31200, "s": 31161, "text": "Python | Check if a variable is string" }, { "code": null, "e": 31237, "s": 31200, "text": "Python | Convert a list into a tuple" }, { "code": null, "e": 31282, "s": 31237, "text": "Add a key:value pair to dictionary in Python" }, { "code": null, "e": 31321, "s": 31282, "text": "Appending to list in Python dictionary" }, { "code": null, "e": 31368, "s": 31321, "text": "Python program to find sum of elements in list" } ]
Python | ASCII art using pyfiglet module - GeeksforGeeks
29 Jun, 2018 pyfiglet takes ASCII text and renders it in ASCII art fonts. figlet_format method convert ASCII text into ASCII art fonts. It takes following arguments : text font ( DEFAULT_FONT = 'standard' ) Command to install pyfiglet module : pip install pyfiglet Code #1: Text in default font # import pyfiglet moduleimport pyfiglet result = pyfiglet.figlet_format("Geeks For Geeks")print(result) Output: ____ _ _____ ____ _ / ___| ___ ___| | _____ | ___|__ _ __ / ___| ___ ___| | _____ | | _ / _ \/ _ \ |/ / __| | |_ / _ \| '__| | | _ / _ \/ _ \ |/ / __| | |_| | __/ __/ \__ \ | _| (_) | | | |_| | __/ __/ \__ \ \____|\___|\___|_|\_\___/ |_| \___/|_| \____|\___|\___|_|\_\___/ Code #2: Text in slant font # import pyfiglet moduleimport pyfiglet result = pyfiglet.figlet_format("Geeks For Geeks", font = "slant" )print(result) Output: ______ __ ______ ______ __ / ____/__ ___ / /_______ / ____/___ _____ / ____/__ ___ / /_______ / / __/ _ \/ _ \/ //_/ ___/ / /_ / __ \/ ___/ / / __/ _ \/ _ \/ //_/ ___/ / /_/ / __/ __/ (__ ) / __/ / /_/ / / / /_/ / __/ __/ (__ ) \____/\___/\___/_/|_/____/ /_/ \____/_/ \____/\___/\___/_/|_/____/ Code #3: Text in 3-d font # import pyfiglet moduleimport pyfiglet result = pyfiglet.figlet_format("G e e k", font = "3-d" )print(result) Output: ******** ** **//////** /** ** // ***** ***** /** ** /** **///** **///** /** ** /** ***** /******* /******* /**** //** ////** /**//// /**//// /**/** //******** //****** //****** /**//** //////// ////// ////// // // Code #4: Text in 3×5 font # importing pyfiglet moduleimport pyfiglet result = pyfiglet.figlet_format("G e e k", font = "3x5" )print(result) Output: ## # # ### ### # # # # ## ## ## # # ### ### # # ## Code #5: Text in 5lineoblique font # import pyfiglet moduleimport pyfiglet result = pyfiglet.figlet_format("G e e k", font = "5lineoblique" )print(result) Output: // ) ) // ___ ___ / ___ // ____ //___) ) //___) ) //\ \ // / / // // // \ \ ((____/ / ((____ ((____ // \ \ Code #6: Text in alphabet font # import pyfiglet moduleimport pyfiglet result = pyfiglet.figlet_format("G e e k", font = "alphabet" )print(result) Output: GGG k G k k G GG eee eee kk G G e e e e k k GGG ee ee k k Code #7: Text in banner3-D font # import pyfiglet moduleimport pyfiglet result = pyfiglet.figlet_format("Geeks", font = "banner3-D" )print(result) Output: :'######:::'########:'########:'##:::'##::'######:: '##... ##:: ##.....:: ##.....:: ##::'##::'##... ##: ##:::..::: ##::::::: ##::::::: ##:'##::: ##:::..:: ##::'####: ######::: ######::: #####::::. ######:: ##::: ##:: ##...:::: ##...:::: ##. ##::::..... ##: ##::: ##:: ##::::::: ##::::::: ##:. ##::'##::: ##: . ######::: ########: ########: ##::. ##:. ######:: :......::::........::........::..::::..:::......::: Code #8: Text in doh font # import pyfiglet moduleimport pyfiglet result = pyfiglet.figlet_format("Geeks", font = "doh" )print(result) Output: GGGGGGGGGGGGG kkkkkkkk GGG::::::::::::G k::::::k GG:::::::::::::::G k::::::k G:::::GGGGGGGG::::G k::::::k G:::::G GGGGGG eeeeeeeeeeee eeeeeeeeeeee k:::::k kkkkkkk G:::::G ee::::::::::::ee ee::::::::::::ee k:::::k k:::::k G:::::G e::::::eeeee:::::ee e::::::eeeee:::::eek:::::k k:::::k G:::::G GGGGGGGGGGe::::::e e:::::ee::::::e e:::::ek:::::k k:::::k G:::::G G::::::::Ge:::::::eeeee::::::ee:::::::eeeee::::::ek::::::k:::::k G:::::G GGGGG::::Ge:::::::::::::::::e e:::::::::::::::::e k:::::::::::k G:::::G G::::Ge::::::eeeeeeeeeee e::::::eeeeeeeeeee k:::::::::::k G:::::G G::::Ge:::::::e e:::::::e k::::::k:::::k G:::::GGGGGGGG::::Ge::::::::e e::::::::e k::::::k k:::::k GG:::::::::::::::G e::::::::eeeeeeee e::::::::eeeeeeee k::::::k k:::::k GGG::::::GGG:::G ee:::::::::::::e ee:::::::::::::e k::::::k k:::::k GGGGGG GGGG eeeeeeeeeeeeee eeeeeeeeeeeeee kkkkkkkk kkkkkkk Code #9: Text in isometric1 font # import pyfiglet moduleimport pyfiglet result = pyfiglet.figlet_format("Geeks", font = "isometric1" )print(result) Output: ___ ___ ___ ___ ___ /\ \ /\ \ /\ \ /\__\ /\ \ /::\ \ /::\ \ /::\ \ /:/ / /::\ \ /:/\:\ \ /:/\:\ \ /:/\:\ \ /:/__/ /:/\ \ \ /:/ \:\ \ /::\~\:\ \ /::\~\:\ \ /::\__\____ _\:\~\ \ \ /:/__/_\:\__\ /:/\:\ \:\__\ /:/\:\ \:\__\ /:/\:::::\__\ /\ \:\ \ \__\ \:\ /\ \/__/ \:\~\:\ \/__/ \:\~\:\ \/__/ \/_|:|~~|~ \:\ \:\ \/__/ \:\ \:\__\ \:\ \:\__\ \:\ \:\__\ |:| | \:\ \:\__\ \:\/:/ / \:\ \/__/ \:\ \/__/ |:| | \:\/:/ / \::/ / \:\__\ \:\__\ |:| | \::/ / \/__/ \/__/ \/__/ \|__| \/__/ Code #10: Text in letters font # import pyfiglet moduleimport pyfiglet result = pyfiglet.figlet_format("Geeks", font = "letters" )print(result) Output: GGGG kk GG GG eee eee kk kk sss GG ee e ee e kkkkk s GG GG eeeee eeeee kk kk sss GGGGGG eeeee eeeee kk kk s sss Code #11: Text in alligator font # import pyfiglet moduleimport pyfiglet result = pyfiglet.figlet_format("G e e k", font = "alligator" )print(result) Output: :::::::: :::::::::: :::::::::: ::: ::: :+: :+: :+: :+: :+: :+: +:+ +:+ +:+ +:+ +:+ :#: +#++:++# +#++:++# +#++:++ +#+ +#+# +#+ +#+ +#+ +#+ #+# #+# #+# #+# #+# #+# ######## ########## ########## ### ### Code #12: Text in dot matrix font # import pyfiglet moduleimport pyfiglet result = pyfiglet.figlet_format("Geeks", font = "dotmatrix" )print(result) Output: _ _ _ _ _ (_)(_)(_) _ (_) (_) (_) _ _ _ _ _ _ _ _ (_) _ _ _ _ _ (_) _ _ _ (_)(_)(_)(_)_ (_)(_)(_)(_)_ (_) _(_)_(_)(_)(_)(_) (_) (_)(_)(_)(_) _ _ _ (_)(_) _ _ _ (_)(_) _(_) (_)_ _ _ _ (_) (_)(_)(_)(_)(_)(_)(_)(_)(_)(_)(_)(_)(_)_ (_)(_)(_)(_)_ (_) _ _ _ (_)(_)_ _ _ _ (_)_ _ _ _ (_) (_)_ _ _ _ _(_) (_)(_)(_)(_) (_)(_)(_)(_) (_)(_)(_)(_) (_) (_) (_)(_)(_)(_) Code #13: Text in bubble font # import pyfiglet moduleimport pyfiglet result = pyfiglet.figlet_format("Geeks For Geeks", font = "bubble" )print(result) Output: _ _ _ _ _ _ _ _ _ _ _ _ _ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ ( G | e | e | k | s ) ( F | o | r ) ( G | e | e | k | s ) \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ Code #14: Text in bubblehead font # import pyfiglet moduleimport pyfiglet result = pyfiglet.figlet_format("Geeks For Geeks", font = "bulbhead" )print(result) Output: ___ ____ ____ _ _ ___ ____ _____ ____ / __)( ___)( ___)( )/ )/ __) ( ___)( _ )( _ \ ( (_-. )__) )__) ) ( \__ \ )__) )(_)( ) / \___/(____)(____)(_)\_)(___/ (__) (_____)(_)\_) ___ ____ ____ _ _ ___ / __)( ___)( ___)( )/ )/ __) ( (_-. )__) )__) ) ( \__ \ \___/(____)(____)(_)\_)(___/ Code #15: Text in digital font # import pyfiglet moduleimport pyfiglet result = pyfiglet.figlet_format("Geeks For Geeks", font = "digital" )print(result) Output: +-+-+-+-+-+ +-+-+-+ +-+-+-+-+-+ |G|e|e|k|s| |F|o|r| |G|e|e|k|s| +-+-+-+-+-+ +-+-+-+ +-+-+-+-+-+ python-modules 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": 25703, "s": 25675, "text": "\n29 Jun, 2018" }, { "code": null, "e": 25826, "s": 25703, "text": "pyfiglet takes ASCII text and renders it in ASCII art fonts. figlet_format method convert ASCII text into ASCII art fonts." }, { "code": null, "e": 25857, "s": 25826, "text": "It takes following arguments :" }, { "code": null, "e": 25897, "s": 25857, "text": "text\nfont ( DEFAULT_FONT = 'standard' )" }, { "code": null, "e": 25934, "s": 25897, "text": "Command to install pyfiglet module :" }, { "code": null, "e": 25955, "s": 25934, "text": "pip install pyfiglet" }, { "code": null, "e": 25986, "s": 25955, "text": " Code #1: Text in default font" }, { "code": "# import pyfiglet moduleimport pyfiglet result = pyfiglet.figlet_format(\"Geeks For Geeks\")print(result)", "e": 26091, "s": 25986, "text": null }, { "code": null, "e": 26099, "s": 26091, "text": "Output:" }, { "code": null, "e": 26530, "s": 26099, "text": " ____ _ _____ ____ _ \n / ___| ___ ___| | _____ | ___|__ _ __ / ___| ___ ___| | _____ \n| | _ / _ \\/ _ \\ |/ / __| | |_ / _ \\| '__| | | _ / _ \\/ _ \\ |/ / __|\n| |_| | __/ __/ \\__ \\ | _| (_) | | | |_| | __/ __/ \\__ \\\n \\____|\\___|\\___|_|\\_\\___/ |_| \\___/|_| \\____|\\___|\\___|_|\\_\\___/\n \n" }, { "code": null, "e": 26559, "s": 26530, "text": " Code #2: Text in slant font" }, { "code": "# import pyfiglet moduleimport pyfiglet result = pyfiglet.figlet_format(\"Geeks For Geeks\", font = \"slant\" )print(result)", "e": 26682, "s": 26559, "text": null }, { "code": null, "e": 26690, "s": 26682, "text": "Output:" }, { "code": null, "e": 27161, "s": 26690, "text": " ______ __ ______ ______ __ \n / ____/__ ___ / /_______ / ____/___ _____ / ____/__ ___ / /_______\n / / __/ _ \\/ _ \\/ //_/ ___/ / /_ / __ \\/ ___/ / / __/ _ \\/ _ \\/ //_/ ___/\n/ /_/ / __/ __/ (__ ) / __/ / /_/ / / / /_/ / __/ __/ (__ ) \n\\____/\\___/\\___/_/|_/____/ /_/ \\____/_/ \\____/\\___/\\___/_/|_/____/ \n \n" }, { "code": null, "e": 27188, "s": 27161, "text": " Code #3: Text in 3-d font" }, { "code": "# import pyfiglet moduleimport pyfiglet result = pyfiglet.figlet_format(\"G e e k\", font = \"3-d\" )print(result)", "e": 27300, "s": 27188, "text": null }, { "code": null, "e": 27308, "s": 27300, "text": "Output:" }, { "code": null, "e": 27648, "s": 27308, "text": " ******** ** \n **//////** /** \n ** // ***** ***** /** **\n/** **///** **///** /** ** \n/** ***** /******* /******* /**** \n//** ////** /**//// /**//// /**/** \n //******** //****** //****** /**//**\n //////// ////// ////// // // \n" }, { "code": null, "e": 27675, "s": 27648, "text": " Code #4: Text in 3×5 font" }, { "code": "# importing pyfiglet moduleimport pyfiglet result = pyfiglet.figlet_format(\"G e e k\", font = \"3x5\" )print(result)", "e": 27790, "s": 27675, "text": null }, { "code": null, "e": 27798, "s": 27790, "text": "Output:" }, { "code": null, "e": 27974, "s": 27798, "text": " \n ## # \n# ### ### # # \n# # ## ## ## \n# # ### ### # # \n ## \n" }, { "code": null, "e": 28010, "s": 27974, "text": " Code #5: Text in 5lineoblique font" }, { "code": "# import pyfiglet moduleimport pyfiglet result = pyfiglet.figlet_format(\"G e e k\", font = \"5lineoblique\" )print(result)", "e": 28131, "s": 28010, "text": null }, { "code": null, "e": 28139, "s": 28131, "text": "Output:" }, { "code": null, "e": 28452, "s": 28139, "text": " \n // ) ) \n // ___ ___ / ___ \n // ____ //___) ) //___) ) //\\ \\ \n // / / // // // \\ \\ \n((____/ / ((____ ((____ // \\ \\ \n\n" }, { "code": null, "e": 28484, "s": 28452, "text": " Code #6: Text in alphabet font" }, { "code": "# import pyfiglet moduleimport pyfiglet result = pyfiglet.figlet_format(\"G e e k\", font = \"alphabet\" )print(result)", "e": 28601, "s": 28484, "text": null }, { "code": null, "e": 28609, "s": 28601, "text": "Output:" }, { "code": null, "e": 28726, "s": 28609, "text": " GGG k \nG k k \nG GG eee eee kk \nG G e e e e k k \n GGG ee ee k k \n\n" }, { "code": null, "e": 28759, "s": 28726, "text": " Code #7: Text in banner3-D font" }, { "code": "# import pyfiglet moduleimport pyfiglet result = pyfiglet.figlet_format(\"Geeks\", font = \"banner3-D\" )print(result)", "e": 28875, "s": 28759, "text": null }, { "code": null, "e": 28883, "s": 28875, "text": "Output:" }, { "code": null, "e": 29300, "s": 28883, "text": ":'######:::'########:'########:'##:::'##::'######::\n'##... ##:: ##.....:: ##.....:: ##::'##::'##... ##:\n ##:::..::: ##::::::: ##::::::: ##:'##::: ##:::..::\n ##::'####: ######::: ######::: #####::::. ######::\n ##::: ##:: ##...:::: ##...:::: ##. ##::::..... ##:\n ##::: ##:: ##::::::: ##::::::: ##:. ##::'##::: ##:\n. ######::: ########: ########: ##::. ##:. ######::\n:......::::........::........::..::::..:::......::: " }, { "code": null, "e": 29327, "s": 29300, "text": " Code #8: Text in doh font" }, { "code": "# import pyfiglet moduleimport pyfiglet result = pyfiglet.figlet_format(\"Geeks\", font = \"doh\" )print(result)", "e": 29437, "s": 29327, "text": null }, { "code": null, "e": 29445, "s": 29437, "text": "Output:" }, { "code": null, "e": 30817, "s": 29445, "text": " \n GGGGGGGGGGGGG kkkkkkkk \n GGG::::::::::::G k::::::k \n GG:::::::::::::::G k::::::k \n G:::::GGGGGGGG::::G k::::::k \n G:::::G GGGGGG eeeeeeeeeeee eeeeeeeeeeee k:::::k kkkkkkk\nG:::::G ee::::::::::::ee ee::::::::::::ee k:::::k k:::::k \nG:::::G e::::::eeeee:::::ee e::::::eeeee:::::eek:::::k k:::::k \nG:::::G GGGGGGGGGGe::::::e e:::::ee::::::e e:::::ek:::::k k:::::k \nG:::::G G::::::::Ge:::::::eeeee::::::ee:::::::eeeee::::::ek::::::k:::::k \nG:::::G GGGGG::::Ge:::::::::::::::::e e:::::::::::::::::e k:::::::::::k \nG:::::G G::::Ge::::::eeeeeeeeeee e::::::eeeeeeeeeee k:::::::::::k \n G:::::G G::::Ge:::::::e e:::::::e k::::::k:::::k \n G:::::GGGGGGGG::::Ge::::::::e e::::::::e k::::::k k:::::k \n GG:::::::::::::::G e::::::::eeeeeeee e::::::::eeeeeeee k::::::k k:::::k \n GGG::::::GGG:::G ee:::::::::::::e ee:::::::::::::e k::::::k k:::::k \n GGGGGG GGGG eeeeeeeeeeeeee eeeeeeeeeeeeee kkkkkkkk kkkkkkk \n" }, { "code": null, "e": 30851, "s": 30817, "text": " Code #9: Text in isometric1 font" }, { "code": "# import pyfiglet moduleimport pyfiglet result = pyfiglet.figlet_format(\"Geeks\", font = \"isometric1\" )print(result)", "e": 30968, "s": 30851, "text": null }, { "code": null, "e": 30976, "s": 30968, "text": "Output:" }, { "code": null, "e": 31759, "s": 30976, "text": "\n ___ ___ ___ ___ ___ \n /\\ \\ /\\ \\ /\\ \\ /\\__\\ /\\ \\ \n /::\\ \\ /::\\ \\ /::\\ \\ /:/ / /::\\ \\ \n /:/\\:\\ \\ /:/\\:\\ \\ /:/\\:\\ \\ /:/__/ /:/\\ \\ \\ \n /:/ \\:\\ \\ /::\\~\\:\\ \\ /::\\~\\:\\ \\ /::\\__\\____ _\\:\\~\\ \\ \\ \n /:/__/_\\:\\__\\ /:/\\:\\ \\:\\__\\ /:/\\:\\ \\:\\__\\ /:/\\:::::\\__\\ /\\ \\:\\ \\ \\__\\\n \\:\\ /\\ \\/__/ \\:\\~\\:\\ \\/__/ \\:\\~\\:\\ \\/__/ \\/_|:|~~|~ \\:\\ \\:\\ \\/__/\n \\:\\ \\:\\__\\ \\:\\ \\:\\__\\ \\:\\ \\:\\__\\ |:| | \\:\\ \\:\\__\\ \n \\:\\/:/ / \\:\\ \\/__/ \\:\\ \\/__/ |:| | \\:\\/:/ / \n \\::/ / \\:\\__\\ \\:\\__\\ |:| | \\::/ / \n \\/__/ \\/__/ \\/__/ \\|__| \\/__/ \n" }, { "code": null, "e": 31791, "s": 31759, "text": " Code #10: Text in letters font" }, { "code": "# import pyfiglet moduleimport pyfiglet result = pyfiglet.figlet_format(\"Geeks\", font = \"letters\" )print(result)", "e": 31905, "s": 31791, "text": null }, { "code": null, "e": 31913, "s": 31905, "text": "Output:" }, { "code": null, "e": 32131, "s": 31913, "text": " GGGG kk \n GG GG eee eee kk kk sss \nGG ee e ee e kkkkk s \nGG GG eeeee eeeee kk kk sss \n GGGGGG eeeee eeeee kk kk s \n sss \n\n" }, { "code": null, "e": 32165, "s": 32131, "text": " Code #11: Text in alligator font" }, { "code": "# import pyfiglet moduleimport pyfiglet result = pyfiglet.figlet_format(\"G e e k\", font = \"alligator\" )print(result)", "e": 32283, "s": 32165, "text": null }, { "code": null, "e": 32291, "s": 32283, "text": "Output:" }, { "code": null, "e": 32782, "s": 32291, "text": " :::::::: :::::::::: :::::::::: ::: ::: \n :+: :+: :+: :+: :+: :+: \n +:+ +:+ +:+ +:+ +:+ \n :#: +#++:++# +#++:++# +#++:++ \n +#+ +#+# +#+ +#+ +#+ +#+ \n#+# #+# #+# #+# #+# #+# \n######## ########## ########## ### ### \n" }, { "code": null, "e": 32817, "s": 32782, "text": " Code #12: Text in dot matrix font" }, { "code": "# import pyfiglet moduleimport pyfiglet result = pyfiglet.figlet_format(\"Geeks\", font = \"dotmatrix\" )print(result)", "e": 32933, "s": 32817, "text": null }, { "code": null, "e": 32941, "s": 32933, "text": "Output:" }, { "code": null, "e": 33599, "s": 32941, "text": " _ _ _ _ \n _ (_)(_)(_) _ (_) \n(_) (_) _ _ _ _ _ _ _ _ (_) _ _ _ _ _ \n(_) _ _ _ (_)(_)(_)(_)_ (_)(_)(_)(_)_ (_) _(_)_(_)(_)(_)(_) \n(_) (_)(_)(_)(_) _ _ _ (_)(_) _ _ _ (_)(_) _(_) (_)_ _ _ _ \n(_) (_)(_)(_)(_)(_)(_)(_)(_)(_)(_)(_)(_)(_)_ (_)(_)(_)(_)_ \n(_) _ _ _ (_)(_)_ _ _ _ (_)_ _ _ _ (_) (_)_ _ _ _ _(_) \n (_)(_)(_)(_) (_)(_)(_)(_) (_)(_)(_)(_) (_) (_) (_)(_)(_)(_) \n \n" }, { "code": null, "e": 33630, "s": 33599, "text": " Code #13: Text in bubble font" }, { "code": "# import pyfiglet moduleimport pyfiglet result = pyfiglet.figlet_format(\"Geeks For Geeks\", font = \"bubble\" )print(result)", "e": 33753, "s": 33630, "text": null }, { "code": null, "e": 33761, "s": 33753, "text": "Output:" }, { "code": null, "e": 33995, "s": 33761, "text": " _ _ _ _ _ _ _ _ _ _ _ _ _ \n / \\ / \\ / \\ / \\ / \\ / \\ / \\ / \\ / \\ / \\ / \\ / \\ / \\ \n( G | e | e | k | s ) ( F | o | r ) ( G | e | e | k | s )\n \\_/ \\_/ \\_/ \\_/ \\_/ \\_/ \\_/ \\_/ \\_/ \\_/ \\_/ \\_/ \\_/ \n\n" }, { "code": null, "e": 34030, "s": 33995, "text": " Code #14: Text in bubblehead font" }, { "code": "# import pyfiglet moduleimport pyfiglet result = pyfiglet.figlet_format(\"Geeks For Geeks\", font = \"bulbhead\" )print(result)", "e": 34155, "s": 34030, "text": null }, { "code": null, "e": 34163, "s": 34155, "text": "Output:" }, { "code": null, "e": 34488, "s": 34163, "text": " ___ ____ ____ _ _ ___ ____ _____ ____ \n / __)( ___)( ___)( )/ )/ __) ( ___)( _ )( _ \\\n( (_-. )__) )__) ) ( \\__ \\ )__) )(_)( ) /\n \\___/(____)(____)(_)\\_)(___/ (__) (_____)(_)\\_)\n ___ ____ ____ _ _ ___ \n / __)( ___)( ___)( )/ )/ __)\n( (_-. )__) )__) ) ( \\__ \\\n \\___/(____)(____)(_)\\_)(___/\n" }, { "code": null, "e": 34520, "s": 34488, "text": " Code #15: Text in digital font" }, { "code": "# import pyfiglet moduleimport pyfiglet result = pyfiglet.figlet_format(\"Geeks For Geeks\", font = \"digital\" )print(result)", "e": 34644, "s": 34520, "text": null }, { "code": null, "e": 34652, "s": 34644, "text": "Output:" }, { "code": null, "e": 34750, "s": 34652, "text": "+-+-+-+-+-+ +-+-+-+ +-+-+-+-+-+\n|G|e|e|k|s| |F|o|r| |G|e|e|k|s|\n+-+-+-+-+-+ +-+-+-+ +-+-+-+-+-+\n\n" }, { "code": null, "e": 34765, "s": 34750, "text": "python-modules" }, { "code": null, "e": 34772, "s": 34765, "text": "Python" }, { "code": null, "e": 34870, "s": 34772, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34888, "s": 34870, "text": "Python Dictionary" }, { "code": null, "e": 34923, "s": 34888, "text": "Read a file line by line in Python" }, { "code": null, "e": 34955, "s": 34923, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 34977, "s": 34955, "text": "Enumerate() in Python" }, { "code": null, "e": 35019, "s": 34977, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 35049, "s": 35019, "text": "Iterate over a list in Python" }, { "code": null, "e": 35075, "s": 35049, "text": "Python String | replace()" }, { "code": null, "e": 35104, "s": 35075, "text": "*args and **kwargs in Python" }, { "code": null, "e": 35148, "s": 35104, "text": "Reading and Writing to text files in Python" } ]
Python math library | isclose() method - GeeksforGeeks
22 May, 2019 In Python math module, math.isclose() method is used to determine whether two floating point numbers are close in value. For using this function you must import math module. Syntax: isclose(a, b, rel_tol = 1e-09, abs_tol 0.0) Parameters:rel_tol: maximum difference for being considered “close”, relative to the magnitude of the input valuesabs_tol: maximum difference for being considered “close”, regardless of the magnitude of the input values -> rel_tol and abs_tol can be changed by using keyword argument, or by simply providing directly as according to their positions in the parameter list. Return Value : Return True if a is close in value to b, and False otherwise. Note: For the values to be considered close, the difference between them must be smaller than at least one of the tolerances. Code #1: # Importing Math moduleimport math # printing whether two values are close or notprint(math.isclose(2.005, 2.005))print(math.isclose(2.005, 2.004))print(math.isclose(2.006, 2.005)) Output: True False False Code #2: # Importing Math moduleimport math # printing whether two values are close or notprint(math.isclose(2.005, 2.125, abs_tol = 0.25))print(math.isclose(2.547, 2.0048, abs_tol = 0.5))print(math.isclose(2.0214, 2.00214, abs_tol = 0.02)) Output: True False True You can change absolute tolerance, as in above case absolute tolerance is different in all three cases. Reference: Python math library Python math-library-functions 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": 25899, "s": 25871, "text": "\n22 May, 2019" }, { "code": null, "e": 26073, "s": 25899, "text": "In Python math module, math.isclose() method is used to determine whether two floating point numbers are close in value. For using this function you must import math module." }, { "code": null, "e": 26125, "s": 26073, "text": "Syntax: isclose(a, b, rel_tol = 1e-09, abs_tol 0.0)" }, { "code": null, "e": 26345, "s": 26125, "text": "Parameters:rel_tol: maximum difference for being considered “close”, relative to the magnitude of the input valuesabs_tol: maximum difference for being considered “close”, regardless of the magnitude of the input values" }, { "code": null, "e": 26497, "s": 26345, "text": "-> rel_tol and abs_tol can be changed by using keyword argument, or by simply providing directly as according to their positions in the parameter list." }, { "code": null, "e": 26574, "s": 26497, "text": "Return Value : Return True if a is close in value to b, and False otherwise." }, { "code": null, "e": 26700, "s": 26574, "text": "Note: For the values to be considered close, the difference between them must be smaller than at least one of the tolerances." }, { "code": null, "e": 26709, "s": 26700, "text": "Code #1:" }, { "code": "# Importing Math moduleimport math # printing whether two values are close or notprint(math.isclose(2.005, 2.005))print(math.isclose(2.005, 2.004))print(math.isclose(2.006, 2.005))", "e": 26891, "s": 26709, "text": null }, { "code": null, "e": 26899, "s": 26891, "text": "Output:" }, { "code": null, "e": 26917, "s": 26899, "text": "True\nFalse\nFalse\n" }, { "code": null, "e": 26927, "s": 26917, "text": " Code #2:" }, { "code": "# Importing Math moduleimport math # printing whether two values are close or notprint(math.isclose(2.005, 2.125, abs_tol = 0.25))print(math.isclose(2.547, 2.0048, abs_tol = 0.5))print(math.isclose(2.0214, 2.00214, abs_tol = 0.02))", "e": 27160, "s": 26927, "text": null }, { "code": null, "e": 27168, "s": 27160, "text": "Output:" }, { "code": null, "e": 27185, "s": 27168, "text": "True\nFalse\nTrue\n" }, { "code": null, "e": 27289, "s": 27185, "text": "You can change absolute tolerance, as in above case absolute tolerance is different in all three cases." }, { "code": null, "e": 27320, "s": 27289, "text": "Reference: Python math library" }, { "code": null, "e": 27350, "s": 27320, "text": "Python math-library-functions" }, { "code": null, "e": 27357, "s": 27350, "text": "Python" }, { "code": null, "e": 27455, "s": 27357, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27473, "s": 27455, "text": "Python Dictionary" }, { "code": null, "e": 27508, "s": 27473, "text": "Read a file line by line in Python" }, { "code": null, "e": 27540, "s": 27508, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27562, "s": 27540, "text": "Enumerate() in Python" }, { "code": null, "e": 27604, "s": 27562, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27634, "s": 27604, "text": "Iterate over a list in Python" }, { "code": null, "e": 27660, "s": 27634, "text": "Python String | replace()" }, { "code": null, "e": 27689, "s": 27660, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27733, "s": 27689, "text": "Reading and Writing to text files in Python" } ]
Prediction of Wine type using Deep Learning - GeeksforGeeks
24 Jan, 2022 We use deep learning for the large data sets but to understand the concept of deep learning, we use the small data set of wine quality. You can find the wine quality data set from the UCI Machine Learning Repository which is available for free. The aim of this article is to get started with the libraries of deep learning such as Keras, etc and to be familiar with the basis of neural network. About the Data Set : Before we start loading in the data, it is really important to know about your data. The data set consist of 12 variables that are included in the data. Few of them are as follows – Fixed acidity : The total acidity is divided into two groups: the volatile acids and the nonvolatile or fixed acids.The value of this variable is represented by in gm/dm3 in the data sets.Volatile acidity: The volatile acidity is a process of wine turning into vinegar. In this data sets, the volatile acidity is expressed in gm/dm3.Citric acid : Citric acid is one of the fixed acids in wines. It’s expressed in g/dm3 in the data sets.Residual Sugar : Residual Sugar is the sugar remaining after fermentation stops, or is stopped. It’s expressed in g/dm3 in the data set.Chlorides : It can be a important contributor to saltiness in wine. The value of this variable is represented by in gm/dm3 in the data sets.Free sulfur dioxide : It is the part of the sulfur dioxide that is added to a wine. The value of this variable is represented by in gm/dm3 in the data sets.Total Sulfur Dioxide : It is the sum of the bound and the free sulfur dioxide.The value of this variable is represented by in gm/dm3 in the data sets. Fixed acidity : The total acidity is divided into two groups: the volatile acids and the nonvolatile or fixed acids.The value of this variable is represented by in gm/dm3 in the data sets. Volatile acidity: The volatile acidity is a process of wine turning into vinegar. In this data sets, the volatile acidity is expressed in gm/dm3. Citric acid : Citric acid is one of the fixed acids in wines. It’s expressed in g/dm3 in the data sets. Residual Sugar : Residual Sugar is the sugar remaining after fermentation stops, or is stopped. It’s expressed in g/dm3 in the data set. Chlorides : It can be a important contributor to saltiness in wine. The value of this variable is represented by in gm/dm3 in the data sets. Free sulfur dioxide : It is the part of the sulfur dioxide that is added to a wine. The value of this variable is represented by in gm/dm3 in the data sets. Total Sulfur Dioxide : It is the sum of the bound and the free sulfur dioxide.The value of this variable is represented by in gm/dm3 in the data sets. Loading the data. Python3 # Import Required Librariesimport matplotlib.pyplot as pltimport pandas as pdimport numpy as np # Read in white wine datawhite = pd.read_csv("http://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv", sep =';') # Read in red wine datared = pd.read_csv("http://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv", sep =';') First rows of `red`. Python3 # First rows of `red`red.head() Output: Last rows of `white`. Python3 # Last rows of `white`white.tail() Output: Take a sample of five rows of `red`. Python3 # Take a sample of five rows of `red`red.sample(5) Output: Data description – Python3 # Describe `white`white.describe() Output: Check for null values in `red`. Python3 # Double check for null values in `red`pd.isnull(red) Output: Creating Histogram. Python3 # Create Histogramfig, ax = plt.subplots(1, 2) ax[0].hist(red.alcohol, 10, facecolor ='red', alpha = 0.5, label ="Red wine") ax[1].hist(white.alcohol, 10, facecolor ='white', ec ="black", lw = 0.5, alpha = 0.5, label ="White wine") fig.subplots_adjust(left = 0, right = 1, bottom = 0, top = 0.5, hspace = 0.05, wspace = 1) ax[0].set_ylim([0, 1000])ax[0].set_xlabel("Alcohol in % Vol")ax[0].set_ylabel("Frequency")ax[1].set_ylim([0, 1000])ax[1].set_xlabel("Alcohol in % Vol")ax[1].set_ylabel("Frequency") fig.suptitle("Distribution of Alcohol in % Vol")plt.show() Output: Splitting the data set for training and validation. Python3 # Add `type` column to `red` with price onered['type'] = 1 # Add `type` column to `white` with price zerowhite['type'] = 0 # Append `white` to `red`wines = red.append(white, ignore_index = True) # Import `train_test_split` from `sklearn.model_selection`from sklearn.model_selection import train_test_splitX = wines.ix[:, 0:11]y = np.ravel(wines.type) # Splitting the data set for training and validatingX_train, X_test, y_train, y_test = train_test_split( X, y, test_size = 0.34, random_state = 45) Python3 # Import `Sequential` from `keras.models`from keras.models import Sequential # Import `Dense` from `keras.layers`from keras.layers import Dense # Initialize the constructormodel = Sequential() # Add an input layermodel.add(Dense(12, activation ='relu', input_shape =(11, ))) # Add one hidden layermodel.add(Dense(9, activation ='relu')) # Add an output layermodel.add(Dense(1, activation ='sigmoid')) # Model output shapemodel.output_shape # Model summarymodel.summary() # Model configmodel.get_config() # List all weight tensorsmodel.get_weights()model.compile(loss ='binary_crossentropy', optimizer ='adam', metrics =['accuracy']) Output: Python3 # Training Modelmodel.fit(X_train, y_train, epochs = 3, batch_size = 1, verbose = 1) # Predicting the Valuey_pred = model.predict(X_test)print(y_pred) Output: shubham_singh clintra Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n24 Jan, 2022" }, { "code": null, "e": 26137, "s": 25537, "text": "We use deep learning for the large data sets but to understand the concept of deep learning, we use the small data set of wine quality. You can find the wine quality data set from the UCI Machine Learning Repository which is available for free. The aim of this article is to get started with the libraries of deep learning such as Keras, etc and to be familiar with the basis of neural network. About the Data Set : Before we start loading in the data, it is really important to know about your data. The data set consist of 12 variables that are included in the data. Few of them are as follows – " }, { "code": null, "e": 27156, "s": 26137, "text": "Fixed acidity : The total acidity is divided into two groups: the volatile acids and the nonvolatile or fixed acids.The value of this variable is represented by in gm/dm3 in the data sets.Volatile acidity: The volatile acidity is a process of wine turning into vinegar. In this data sets, the volatile acidity is expressed in gm/dm3.Citric acid : Citric acid is one of the fixed acids in wines. It’s expressed in g/dm3 in the data sets.Residual Sugar : Residual Sugar is the sugar remaining after fermentation stops, or is stopped. It’s expressed in g/dm3 in the data set.Chlorides : It can be a important contributor to saltiness in wine. The value of this variable is represented by in gm/dm3 in the data sets.Free sulfur dioxide : It is the part of the sulfur dioxide that is added to a wine. The value of this variable is represented by in gm/dm3 in the data sets.Total Sulfur Dioxide : It is the sum of the bound and the free sulfur dioxide.The value of this variable is represented by in gm/dm3 in the data sets." }, { "code": null, "e": 27345, "s": 27156, "text": "Fixed acidity : The total acidity is divided into two groups: the volatile acids and the nonvolatile or fixed acids.The value of this variable is represented by in gm/dm3 in the data sets." }, { "code": null, "e": 27491, "s": 27345, "text": "Volatile acidity: The volatile acidity is a process of wine turning into vinegar. In this data sets, the volatile acidity is expressed in gm/dm3." }, { "code": null, "e": 27595, "s": 27491, "text": "Citric acid : Citric acid is one of the fixed acids in wines. It’s expressed in g/dm3 in the data sets." }, { "code": null, "e": 27732, "s": 27595, "text": "Residual Sugar : Residual Sugar is the sugar remaining after fermentation stops, or is stopped. It’s expressed in g/dm3 in the data set." }, { "code": null, "e": 27873, "s": 27732, "text": "Chlorides : It can be a important contributor to saltiness in wine. The value of this variable is represented by in gm/dm3 in the data sets." }, { "code": null, "e": 28030, "s": 27873, "text": "Free sulfur dioxide : It is the part of the sulfur dioxide that is added to a wine. The value of this variable is represented by in gm/dm3 in the data sets." }, { "code": null, "e": 28181, "s": 28030, "text": "Total Sulfur Dioxide : It is the sum of the bound and the free sulfur dioxide.The value of this variable is represented by in gm/dm3 in the data sets." }, { "code": null, "e": 28203, "s": 28183, "text": "Loading the data. " }, { "code": null, "e": 28211, "s": 28203, "text": "Python3" }, { "code": "# Import Required Librariesimport matplotlib.pyplot as pltimport pandas as pdimport numpy as np # Read in white wine datawhite = pd.read_csv(\"http://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv\", sep =';') # Read in red wine datared = pd.read_csv(\"http://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv\", sep =';')", "e": 28601, "s": 28211, "text": null }, { "code": null, "e": 28626, "s": 28601, "text": " First rows of `red`. " }, { "code": null, "e": 28634, "s": 28626, "text": "Python3" }, { "code": "# First rows of `red`red.head()", "e": 28666, "s": 28634, "text": null }, { "code": null, "e": 28676, "s": 28666, "text": "Output: " }, { "code": null, "e": 28702, "s": 28676, "text": " Last rows of `white`. " }, { "code": null, "e": 28710, "s": 28702, "text": "Python3" }, { "code": "# Last rows of `white`white.tail()", "e": 28745, "s": 28710, "text": null }, { "code": null, "e": 28755, "s": 28745, "text": "Output: " }, { "code": null, "e": 28796, "s": 28755, "text": " Take a sample of five rows of `red`. " }, { "code": null, "e": 28804, "s": 28796, "text": "Python3" }, { "code": "# Take a sample of five rows of `red`red.sample(5)", "e": 28855, "s": 28804, "text": null }, { "code": null, "e": 28865, "s": 28855, "text": "Output: " }, { "code": null, "e": 28886, "s": 28865, "text": "Data description – " }, { "code": null, "e": 28894, "s": 28886, "text": "Python3" }, { "code": "# Describe `white`white.describe()", "e": 28929, "s": 28894, "text": null }, { "code": null, "e": 28939, "s": 28929, "text": "Output: " }, { "code": null, "e": 28973, "s": 28939, "text": "Check for null values in `red`. " }, { "code": null, "e": 28981, "s": 28973, "text": "Python3" }, { "code": "# Double check for null values in `red`pd.isnull(red)", "e": 29035, "s": 28981, "text": null }, { "code": null, "e": 29045, "s": 29035, "text": "Output: " }, { "code": null, "e": 29069, "s": 29047, "text": "Creating Histogram. " }, { "code": null, "e": 29077, "s": 29069, "text": "Python3" }, { "code": "# Create Histogramfig, ax = plt.subplots(1, 2) ax[0].hist(red.alcohol, 10, facecolor ='red', alpha = 0.5, label =\"Red wine\") ax[1].hist(white.alcohol, 10, facecolor ='white', ec =\"black\", lw = 0.5, alpha = 0.5, label =\"White wine\") fig.subplots_adjust(left = 0, right = 1, bottom = 0, top = 0.5, hspace = 0.05, wspace = 1) ax[0].set_ylim([0, 1000])ax[0].set_xlabel(\"Alcohol in % Vol\")ax[0].set_ylabel(\"Frequency\")ax[1].set_ylim([0, 1000])ax[1].set_xlabel(\"Alcohol in % Vol\")ax[1].set_ylabel(\"Frequency\") fig.suptitle(\"Distribution of Alcohol in % Vol\")plt.show()", "e": 29687, "s": 29077, "text": null }, { "code": null, "e": 29697, "s": 29687, "text": "Output: " }, { "code": null, "e": 29753, "s": 29697, "text": " Splitting the data set for training and validation. " }, { "code": null, "e": 29761, "s": 29753, "text": "Python3" }, { "code": "# Add `type` column to `red` with price onered['type'] = 1 # Add `type` column to `white` with price zerowhite['type'] = 0 # Append `white` to `red`wines = red.append(white, ignore_index = True) # Import `train_test_split` from `sklearn.model_selection`from sklearn.model_selection import train_test_splitX = wines.ix[:, 0:11]y = np.ravel(wines.type) # Splitting the data set for training and validatingX_train, X_test, y_train, y_test = train_test_split( X, y, test_size = 0.34, random_state = 45)", "e": 30270, "s": 29761, "text": null }, { "code": null, "e": 30278, "s": 30270, "text": "Python3" }, { "code": "# Import `Sequential` from `keras.models`from keras.models import Sequential # Import `Dense` from `keras.layers`from keras.layers import Dense # Initialize the constructormodel = Sequential() # Add an input layermodel.add(Dense(12, activation ='relu', input_shape =(11, ))) # Add one hidden layermodel.add(Dense(9, activation ='relu')) # Add an output layermodel.add(Dense(1, activation ='sigmoid')) # Model output shapemodel.output_shape # Model summarymodel.summary() # Model configmodel.get_config() # List all weight tensorsmodel.get_weights()model.compile(loss ='binary_crossentropy', optimizer ='adam', metrics =['accuracy'])", "e": 30912, "s": 30278, "text": null }, { "code": null, "e": 30922, "s": 30912, "text": "Output: " }, { "code": null, "e": 30934, "s": 30926, "text": "Python3" }, { "code": "# Training Modelmodel.fit(X_train, y_train, epochs = 3, batch_size = 1, verbose = 1) # Predicting the Valuey_pred = model.predict(X_test)print(y_pred)", "e": 31096, "s": 30934, "text": null }, { "code": null, "e": 31106, "s": 31096, "text": "Output: " }, { "code": null, "e": 31122, "s": 31108, "text": "shubham_singh" }, { "code": null, "e": 31130, "s": 31122, "text": "clintra" }, { "code": null, "e": 31137, "s": 31130, "text": "Python" }, { "code": null, "e": 31235, "s": 31137, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31267, "s": 31235, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 31309, "s": 31267, "text": "Check if element exists in list in Python" }, { "code": null, "e": 31351, "s": 31309, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 31378, "s": 31351, "text": "Python Classes and Objects" }, { "code": null, "e": 31434, "s": 31378, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 31456, "s": 31434, "text": "Defaultdict in Python" }, { "code": null, "e": 31495, "s": 31456, "text": "Python | Get unique values from a list" }, { "code": null, "e": 31526, "s": 31495, "text": "Python | os.path.join() method" }, { "code": null, "e": 31555, "s": 31526, "text": "Create a directory in Python" } ]
How to calculate days left until next Christmas using JavaScript ? - GeeksforGeeks
14 Apr, 2021 In this article, we will learn how to calculate the number of days left until next Christmas using JavaScript. Christmas marks the birth of Christ, mainly celebrated by millions of people around the globe on 25 December every year as a religious and cultural festival. Approach: In order to calculate the number of days between two dates in JavaScript, the Date object must be used. We find out the year value of this year’s Christmas Day using getFullYear() method. We then check if the current date has already passed the Christmas day by checking if the month is December and the day is more than the 25th. The getMonth() method is used to get the month and the getDate() method is used to get the date value of the given time. If this condition is satisfied, we add one more year to the Christmas year that we found earlier, hence advancing the Christmas Day for the next year. We then create the final date value of the next Christmas Day. We can use the getTime() function to obtain both the date values in milliseconds. After the conversion, we subtract the later one from the earlier one to get the difference in milliseconds. The final number of days is obtained by dividing the difference (in milliseconds) between the two dates by the number of milliseconds in one day. Syntax: let today = new Date(); let christmasYear = today.getFullYear(); if (today.getMonth() == 11 && today.getDate() > 25) { christmasYear = christmasYear + 1; } let christmasDate = new Date(christmasYear, 11, 25); let dayMilliseconds = 1000 * 60 * 60 * 24; let remainingDays = Math.ceil( (christmasDate.getTime() - today.getTime()) / (dayMilliseconds) ); Example: HTML <html><body> <h1 style="color: green;"> GeeksforGeeks </h1> <h3> Program to calculate days left until next Christmas using JavaScript? </h3> <script> // Get the current date let today = new Date(); // Get the year of the current date let christmasYear = today.getFullYear(); // Check if the current date is // already past by checking if the month // is December and the current day // is greater than 25 if (today.getMonth() == 11 && today.getDate() > 25) { // Add an year so that the next // Christmas date could be used christmasYear = christmasYear + 1; } // Get the date of the next Christmas let christmasDate = new Date(christmasYear, 11, 25); // Get the number of milliseconds in 1 day let dayMilliseconds = 1000 * 60 * 60 * 24; // Get the remaining amount of days let remainingDays = Math.ceil( (christmasDate.getTime() - today.getTime()) / (dayMilliseconds) ); // Write it to the page document.write("There are " + remainingDays + " days remaining until Christmas."); </script></body></html> Output: javascript-date JavaScript-Methods JavaScript-Questions Picked 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 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": 39239, "s": 39211, "text": "\n14 Apr, 2021" }, { "code": null, "e": 39508, "s": 39239, "text": "In this article, we will learn how to calculate the number of days left until next Christmas using JavaScript. Christmas marks the birth of Christ, mainly celebrated by millions of people around the globe on 25 December every year as a religious and cultural festival." }, { "code": null, "e": 39970, "s": 39508, "text": "Approach: In order to calculate the number of days between two dates in JavaScript, the Date object must be used. We find out the year value of this year’s Christmas Day using getFullYear() method. We then check if the current date has already passed the Christmas day by checking if the month is December and the day is more than the 25th. The getMonth() method is used to get the month and the getDate() method is used to get the date value of the given time." }, { "code": null, "e": 40184, "s": 39970, "text": "If this condition is satisfied, we add one more year to the Christmas year that we found earlier, hence advancing the Christmas Day for the next year. We then create the final date value of the next Christmas Day." }, { "code": null, "e": 40520, "s": 40184, "text": "We can use the getTime() function to obtain both the date values in milliseconds. After the conversion, we subtract the later one from the earlier one to get the difference in milliseconds. The final number of days is obtained by dividing the difference (in milliseconds) between the two dates by the number of milliseconds in one day." }, { "code": null, "e": 40528, "s": 40520, "text": "Syntax:" }, { "code": null, "e": 40888, "s": 40528, "text": "let today = new Date();\nlet christmasYear = today.getFullYear();\n\nif (today.getMonth() == 11 && today.getDate() > 25) {\n christmasYear = christmasYear + 1;\n}\n\nlet christmasDate = new Date(christmasYear, 11, 25);\nlet dayMilliseconds = 1000 * 60 * 60 * 24;\n\nlet remainingDays = Math.ceil(\n (christmasDate.getTime() - today.getTime()) /\n (dayMilliseconds)\n);" }, { "code": null, "e": 40897, "s": 40888, "text": "Example:" }, { "code": null, "e": 40902, "s": 40897, "text": "HTML" }, { "code": "<html><body> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <h3> Program to calculate days left until next Christmas using JavaScript? </h3> <script> // Get the current date let today = new Date(); // Get the year of the current date let christmasYear = today.getFullYear(); // Check if the current date is // already past by checking if the month // is December and the current day // is greater than 25 if (today.getMonth() == 11 && today.getDate() > 25) { // Add an year so that the next // Christmas date could be used christmasYear = christmasYear + 1; } // Get the date of the next Christmas let christmasDate = new Date(christmasYear, 11, 25); // Get the number of milliseconds in 1 day let dayMilliseconds = 1000 * 60 * 60 * 24; // Get the remaining amount of days let remainingDays = Math.ceil( (christmasDate.getTime() - today.getTime()) / (dayMilliseconds) ); // Write it to the page document.write(\"There are \" + remainingDays + \" days remaining until Christmas.\"); </script></body></html>", "e": 42055, "s": 40902, "text": null }, { "code": null, "e": 42063, "s": 42055, "text": "Output:" }, { "code": null, "e": 42079, "s": 42063, "text": "javascript-date" }, { "code": null, "e": 42098, "s": 42079, "text": "JavaScript-Methods" }, { "code": null, "e": 42119, "s": 42098, "text": "JavaScript-Questions" }, { "code": null, "e": 42126, "s": 42119, "text": "Picked" }, { "code": null, "e": 42137, "s": 42126, "text": "JavaScript" }, { "code": null, "e": 42154, "s": 42137, "text": "Web Technologies" }, { "code": null, "e": 42252, "s": 42154, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42292, "s": 42252, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 42337, "s": 42292, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 42398, "s": 42337, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 42470, "s": 42398, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 42539, "s": 42470, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 42579, "s": 42539, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 42612, "s": 42579, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 42657, "s": 42612, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 42700, "s": 42657, "text": "How to fetch data from an API in ReactJS ?" } ]
How to configure node.js console font ? - GeeksforGeeks
27 Feb, 2020 You can format the console font in Node.js using the CHALK module. The chalk module is can be used to customize node console. By using it, one can change console look using features of it like bold the text, making underlines, highlighting the background color of a text, etc. Features of Chalk module: It’s easy to get started and easy to use. It is widely used and popular module for formatting the text. Users can format the console text very easily. Installing Chalk module and using It: You can visit the link Install Chalk module to install this package using command.$ npm install --save chalk $ npm install --save chalk After installing chalk module you can check your chalk version on command prompt by using the following command.npm version chalk npm version chalk After that, you can just create a folder and add a file for example app.js. To run this file you need to execute command.$ node app.js $ node app.js Requiring module: You need to include the chalk module in your file using these lines.var chalk = require('chalk'); var chalk = require('chalk'); Filename: app.js// Include chalk modulevar chalk = require('chalk') // Set background color to yellowconsole.log(chalk.black.bgYellow('Greetings from Geekforgeeks')); // Set background color to blueconsole.log(chalk.black.bgBlue('Greetings from Geekforgeeks')); // Modifiers can also be appliedconsole.log(chalk.bold.green('Greetings from Geekforgeeks')); // Include chalk modulevar chalk = require('chalk') // Set background color to yellowconsole.log(chalk.black.bgYellow('Greetings from Geekforgeeks')); // Set background color to blueconsole.log(chalk.black.bgBlue('Greetings from Geekforgeeks')); // Modifiers can also be appliedconsole.log(chalk.bold.green('Greetings from Geekforgeeks')); Steps to run the program: The project structure will look like this: Run app.js file using following commands:node app.js node app.js Node.js-Misc Picked Node.js Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Node.js Export Module How to connect Node.js with React.js ? Difference between dependencies, devDependencies and peerDependencies Mongoose find() Function Mongoose Populate() Method Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26293, "s": 26265, "text": "\n27 Feb, 2020" }, { "code": null, "e": 26570, "s": 26293, "text": "You can format the console font in Node.js using the CHALK module. The chalk module is can be used to customize node console. By using it, one can change console look using features of it like bold the text, making underlines, highlighting the background color of a text, etc." }, { "code": null, "e": 26596, "s": 26570, "text": "Features of Chalk module:" }, { "code": null, "e": 26638, "s": 26596, "text": "It’s easy to get started and easy to use." }, { "code": null, "e": 26700, "s": 26638, "text": "It is widely used and popular module for formatting the text." }, { "code": null, "e": 26747, "s": 26700, "text": "Users can format the console text very easily." }, { "code": null, "e": 26785, "s": 26747, "text": "Installing Chalk module and using It:" }, { "code": null, "e": 26894, "s": 26785, "text": "You can visit the link Install Chalk module to install this package using command.$ npm install --save chalk" }, { "code": null, "e": 26921, "s": 26894, "text": "$ npm install --save chalk" }, { "code": null, "e": 27051, "s": 26921, "text": "After installing chalk module you can check your chalk version on command prompt by using the following command.npm version chalk" }, { "code": null, "e": 27069, "s": 27051, "text": "npm version chalk" }, { "code": null, "e": 27204, "s": 27069, "text": "After that, you can just create a folder and add a file for example app.js. To run this file you need to execute command.$ node app.js" }, { "code": null, "e": 27218, "s": 27204, "text": "$ node app.js" }, { "code": null, "e": 27334, "s": 27218, "text": "Requiring module: You need to include the chalk module in your file using these lines.var chalk = require('chalk');" }, { "code": null, "e": 27364, "s": 27334, "text": "var chalk = require('chalk');" }, { "code": null, "e": 27723, "s": 27364, "text": "Filename: app.js// Include chalk modulevar chalk = require('chalk') // Set background color to yellowconsole.log(chalk.black.bgYellow('Greetings from Geekforgeeks')); // Set background color to blueconsole.log(chalk.black.bgBlue('Greetings from Geekforgeeks')); // Modifiers can also be appliedconsole.log(chalk.bold.green('Greetings from Geekforgeeks'));" }, { "code": "// Include chalk modulevar chalk = require('chalk') // Set background color to yellowconsole.log(chalk.black.bgYellow('Greetings from Geekforgeeks')); // Set background color to blueconsole.log(chalk.black.bgBlue('Greetings from Geekforgeeks')); // Modifiers can also be appliedconsole.log(chalk.bold.green('Greetings from Geekforgeeks'));", "e": 28066, "s": 27723, "text": null }, { "code": null, "e": 28092, "s": 28066, "text": "Steps to run the program:" }, { "code": null, "e": 28135, "s": 28092, "text": "The project structure will look like this:" }, { "code": null, "e": 28188, "s": 28135, "text": "Run app.js file using following commands:node app.js" }, { "code": null, "e": 28200, "s": 28188, "text": "node app.js" }, { "code": null, "e": 28213, "s": 28200, "text": "Node.js-Misc" }, { "code": null, "e": 28220, "s": 28213, "text": "Picked" }, { "code": null, "e": 28228, "s": 28220, "text": "Node.js" }, { "code": null, "e": 28247, "s": 28228, "text": "Technical Scripter" }, { "code": null, "e": 28264, "s": 28247, "text": "Web Technologies" }, { "code": null, "e": 28362, "s": 28264, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28384, "s": 28362, "text": "Node.js Export Module" }, { "code": null, "e": 28423, "s": 28384, "text": "How to connect Node.js with React.js ?" }, { "code": null, "e": 28493, "s": 28423, "text": "Difference between dependencies, devDependencies and peerDependencies" }, { "code": null, "e": 28518, "s": 28493, "text": "Mongoose find() Function" }, { "code": null, "e": 28545, "s": 28518, "text": "Mongoose Populate() Method" }, { "code": null, "e": 28585, "s": 28545, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28630, "s": 28585, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28673, "s": 28630, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28735, "s": 28673, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Python program to modify the content of a Binary File - GeeksforGeeks
27 Dec, 2021 Given a binary file that contains some sentences (space separated words), let’s write a Python program to modify or alter any particular word of the sentence. Approach:Step 1: Searching for the word in the binary file. Step 2: While searching in the file, the variable “pos” stores the position of file pointer record then traverse(continue) reading of the record. Step 3: If the word to be searched exists then place the write pointer (to ending of the previous record) i.e. at pos. Step 4: Call write() function to take the new record. Step 5: Write the new object at the position “pos” and hence the record is updated and print “record successfully updated”. Step 6: If the word does not exists then print “record not found”. ImplementationLet’s suppose the content of the binary file is: Python3 # Python program to modify the# content of binary file # Function to update the# content of binary filedef update_binary(word, new) # string variable to store # each word after reading # from the file string = b"" # Flag variable to check # if the record is found or # not Flag = 0 # Open the file in r + b mode which means # opening a binary file for reading and # writing with open('file.txt', 'r + b') as file: pos = 0 # Reading the content of the # file character by character data = string = file.read(1) # Looping till the end of # file is reached while data: data = file.read(1) # Checking if the space is reached if data == b" ": # checking the word read with # the word entered by user if string == word: # Moving the file pointer # at the end of the previously # read record file.seek(pos) # Updating the content of the file file.write(new) Flag = 1 break else: # storing the position of # current file pointer i.e. at # the end of previously read record pos = file.tell() data = string = file.read(1) else: # Storing the data of the file # in the string variable string += data continue if Flag: print("Record successfully updated") else: print("Record not found") # Driver code# Input the word to be found# and the new wordword = input("Enter the word to be replaced: ").encode()new = input("\nEnter the new word: ").encode() update_binary(word, new) Output: Text file: Akanksha_Rai rajeev0719singh kk9826225 Python file-handling-programs python-file-handling Python Python Programs 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 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": 25621, "s": 25593, "text": "\n27 Dec, 2021" }, { "code": null, "e": 25780, "s": 25621, "text": "Given a binary file that contains some sentences (space separated words), let’s write a Python program to modify or alter any particular word of the sentence." }, { "code": null, "e": 26350, "s": 25780, "text": "Approach:Step 1: Searching for the word in the binary file. Step 2: While searching in the file, the variable “pos” stores the position of file pointer record then traverse(continue) reading of the record. Step 3: If the word to be searched exists then place the write pointer (to ending of the previous record) i.e. at pos. Step 4: Call write() function to take the new record. Step 5: Write the new object at the position “pos” and hence the record is updated and print “record successfully updated”. Step 6: If the word does not exists then print “record not found”." }, { "code": null, "e": 26413, "s": 26350, "text": "ImplementationLet’s suppose the content of the binary file is:" }, { "code": null, "e": 26421, "s": 26413, "text": "Python3" }, { "code": "# Python program to modify the# content of binary file # Function to update the# content of binary filedef update_binary(word, new) # string variable to store # each word after reading # from the file string = b\"\" # Flag variable to check # if the record is found or # not Flag = 0 # Open the file in r + b mode which means # opening a binary file for reading and # writing with open('file.txt', 'r + b') as file: pos = 0 # Reading the content of the # file character by character data = string = file.read(1) # Looping till the end of # file is reached while data: data = file.read(1) # Checking if the space is reached if data == b\" \": # checking the word read with # the word entered by user if string == word: # Moving the file pointer # at the end of the previously # read record file.seek(pos) # Updating the content of the file file.write(new) Flag = 1 break else: # storing the position of # current file pointer i.e. at # the end of previously read record pos = file.tell() data = string = file.read(1) else: # Storing the data of the file # in the string variable string += data continue if Flag: print(\"Record successfully updated\") else: print(\"Record not found\") # Driver code# Input the word to be found# and the new wordword = input(\"Enter the word to be replaced: \").encode()new = input(\"\\nEnter the new word: \").encode() update_binary(word, new)", "e": 28330, "s": 26421, "text": null }, { "code": null, "e": 28338, "s": 28330, "text": "Output:" }, { "code": null, "e": 28349, "s": 28338, "text": "Text file:" }, { "code": null, "e": 28364, "s": 28351, "text": "Akanksha_Rai" }, { "code": null, "e": 28380, "s": 28364, "text": "rajeev0719singh" }, { "code": null, "e": 28390, "s": 28380, "text": "kk9826225" }, { "code": null, "e": 28420, "s": 28390, "text": "Python file-handling-programs" }, { "code": null, "e": 28441, "s": 28420, "text": "python-file-handling" }, { "code": null, "e": 28448, "s": 28441, "text": "Python" }, { "code": null, "e": 28464, "s": 28448, "text": "Python Programs" }, { "code": null, "e": 28562, "s": 28464, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28580, "s": 28562, "text": "Python Dictionary" }, { "code": null, "e": 28612, "s": 28580, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28634, "s": 28612, "text": "Enumerate() in Python" }, { "code": null, "e": 28676, "s": 28634, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28706, "s": 28676, "text": "Iterate over a list in Python" }, { "code": null, "e": 28749, "s": 28706, "text": "Python program to convert a list to string" }, { "code": null, "e": 28771, "s": 28749, "text": "Defaultdict in Python" }, { "code": null, "e": 28810, "s": 28771, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28856, "s": 28810, "text": "Python | Split string into list of characters" } ]
Introduction to Markdown - GeeksforGeeks
03 Mar, 2022 If you have ever worked with git platforms like GitHub, BitBucket or Submitted any question or answers to an online forum, chances are you pretty much have unknowingly used Markdown. Markdown is a lightweight markup language. Created by John Gruber in 2004, Markdown is now one of the world’s most popular markup languages. And given below is a detailed explanation of its advantages and on using it. The extension for a Markdown file is .md or .markdown. To compile a markdown file you need an application capable of processing markdown files like Microsoft Word, Dillinger, etc. These applications use a Markdown processor or parser which converts a markdown file to printable HTML code. Advantages Of Markdown: It’s not made just for programmers, because you can write E-Books with it using leanpub.Convertible to formats like PDF, HTML, docs etc.You can format your mail using markdown with MarkdownHere.It is heavily used to write formatted pages across various platforms like StackOverflow, Github and many more.Markdown Files can be converted to webpages using tools like Github Pages, blot.im and smallvictori.es. It’s not made just for programmers, because you can write E-Books with it using leanpub. Convertible to formats like PDF, HTML, docs etc. You can format your mail using markdown with MarkdownHere. It is heavily used to write formatted pages across various platforms like StackOverflow, Github and many more. Markdown Files can be converted to webpages using tools like Github Pages, blot.im and smallvictori.es. It would be really helpful if you know the basics of Web Formatting, but no need to worry if you don’t, we will cover everything from Amateur to Professional. Markdown helps in creating all basic elements that you see on a web page like texts, lists, external links, images and many more. To start writing Markdown code there are plenty of tools available online. As you know the best way of learning something is by doing it. You can start executing code as shown below in any online Markdown editor like Dillinger. Given below is a syntax which will be useful to learn and later as a cheat sheet for writing Markdown codes. Headers Syntax: # Header1 ## Header2 ### Header3 #### Header4 .... Output: Output: Formatting Syntax: *This is Italic* _This is also Italic_ **This is bold** __This is also bold__ __This is a **combination**__ Output: Lists Syntax: 1.One 2.Two 3.Three - Elem 1 - Elem 2 * Member * Another Member - Elem Main - Another one - Sub list - It's Member Images & Links Syntax: IMAGE : ![GeeksForGeeks Logo]( https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-6.png) LINK : [GeeksForGeeks](https://www.geeksforgeeks.org/) Output: Output: Code & Quotes Syntax: ``` This is Some Code ``` Here Code is `Inline` . > These are > Some Quotes Output: Output: This Article is a cheat sheet you can use for Markdown, For a detailed tutorial on Markdown syntax see daringfireball.net sumitgumber28 rkbhola5 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 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 Remove elements from a JavaScript Array How to apply style to parent if it has child with CSS? How to execute PHP code using command line ? How to Insert Form Data into Database using PHP ? Types of CSS (Cascading Style Sheet)
[ { "code": null, "e": 26193, "s": 26165, "text": "\n03 Mar, 2022" }, { "code": null, "e": 26377, "s": 26193, "text": "If you have ever worked with git platforms like GitHub, BitBucket or Submitted any question or answers to an online forum, chances are you pretty much have unknowingly used Markdown. " }, { "code": null, "e": 26596, "s": 26377, "text": "Markdown is a lightweight markup language. Created by John Gruber in 2004, Markdown is now one of the world’s most popular markup languages. And given below is a detailed explanation of its advantages and on using it. " }, { "code": null, "e": 26886, "s": 26596, "text": "The extension for a Markdown file is .md or .markdown. To compile a markdown file you need an application capable of processing markdown files like Microsoft Word, Dillinger, etc. These applications use a Markdown processor or parser which converts a markdown file to printable HTML code. " }, { "code": null, "e": 26912, "s": 26886, "text": "Advantages Of Markdown: " }, { "code": null, "e": 27320, "s": 26912, "text": "It’s not made just for programmers, because you can write E-Books with it using leanpub.Convertible to formats like PDF, HTML, docs etc.You can format your mail using markdown with MarkdownHere.It is heavily used to write formatted pages across various platforms like StackOverflow, Github and many more.Markdown Files can be converted to webpages using tools like Github Pages, blot.im and smallvictori.es." }, { "code": null, "e": 27409, "s": 27320, "text": "It’s not made just for programmers, because you can write E-Books with it using leanpub." }, { "code": null, "e": 27458, "s": 27409, "text": "Convertible to formats like PDF, HTML, docs etc." }, { "code": null, "e": 27517, "s": 27458, "text": "You can format your mail using markdown with MarkdownHere." }, { "code": null, "e": 27628, "s": 27517, "text": "It is heavily used to write formatted pages across various platforms like StackOverflow, Github and many more." }, { "code": null, "e": 27732, "s": 27628, "text": "Markdown Files can be converted to webpages using tools like Github Pages, blot.im and smallvictori.es." }, { "code": null, "e": 28022, "s": 27732, "text": "It would be really helpful if you know the basics of Web Formatting, but no need to worry if you don’t, we will cover everything from Amateur to Professional. Markdown helps in creating all basic elements that you see on a web page like texts, lists, external links, images and many more. " }, { "code": null, "e": 28251, "s": 28022, "text": "To start writing Markdown code there are plenty of tools available online. As you know the best way of learning something is by doing it. You can start executing code as shown below in any online Markdown editor like Dillinger. " }, { "code": null, "e": 28362, "s": 28251, "text": "Given below is a syntax which will be useful to learn and later as a cheat sheet for writing Markdown codes. " }, { "code": null, "e": 28380, "s": 28362, "text": "Headers Syntax: " }, { "code": null, "e": 28431, "s": 28380, "text": "# Header1\n## Header2\n### Header3\n#### Header4\n...." }, { "code": null, "e": 28441, "s": 28431, "text": "Output: " }, { "code": null, "e": 28451, "s": 28441, "text": "Output: " }, { "code": null, "e": 28472, "s": 28451, "text": "Formatting Syntax: " }, { "code": null, "e": 28582, "s": 28472, "text": "*This is Italic*\n_This is also Italic_\n\n**This is bold**\n__This is also bold__\n\n__This is a **combination**__" }, { "code": null, "e": 28592, "s": 28582, "text": "Output: " }, { "code": null, "e": 28608, "s": 28592, "text": "Lists Syntax: " }, { "code": null, "e": 28734, "s": 28608, "text": "1.One\n2.Two\n3.Three\n\n- Elem 1\n- Elem 2\n\n* Member\n* Another Member\n\n- Elem Main\n- Another one\n - Sub list\n - It's Member" }, { "code": null, "e": 28767, "s": 28742, "text": "Images & Links Syntax: " }, { "code": null, "e": 28934, "s": 28767, "text": " IMAGE :\n![GeeksForGeeks Logo](\nhttps://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-6.png)\n\n LINK :\n[GeeksForGeeks](https://www.geeksforgeeks.org/)" }, { "code": null, "e": 28944, "s": 28934, "text": "Output: " }, { "code": null, "e": 28954, "s": 28944, "text": "Output: " }, { "code": null, "e": 28978, "s": 28954, "text": "Code & Quotes Syntax: " }, { "code": null, "e": 29054, "s": 28978, "text": "``` This is Some Code ```\nHere Code is `Inline` .\n> These are\n> Some Quotes" }, { "code": null, "e": 29064, "s": 29054, "text": "Output: " }, { "code": null, "e": 29074, "s": 29064, "text": "Output: " }, { "code": null, "e": 29197, "s": 29074, "text": "This Article is a cheat sheet you can use for Markdown, For a detailed tutorial on Markdown syntax see daringfireball.net " }, { "code": null, "e": 29211, "s": 29197, "text": "sumitgumber28" }, { "code": null, "e": 29220, "s": 29211, "text": "rkbhola5" }, { "code": null, "e": 29237, "s": 29220, "text": "Web Technologies" }, { "code": null, "e": 29264, "s": 29237, "text": "Web technologies Questions" }, { "code": null, "e": 29362, "s": 29264, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29402, "s": 29362, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29447, "s": 29402, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29490, "s": 29447, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29551, "s": 29490, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29623, "s": 29551, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 29663, "s": 29623, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29718, "s": 29663, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 29763, "s": 29718, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 29813, "s": 29763, "text": "How to Insert Form Data into Database using PHP ?" } ]
Create XML Documents using Python - GeeksforGeeks
10 May, 2020 Extensible Markup Language(XML), is a markup language that you can use to create your own tags. It was created by the World Wide Web Consortium (W3C) to overcome the limitations of HTML, which is the basis for all Web pages. XML is based on SGML – Standard Generalized Markup Language. It is used for storing and transporting data. XML doesn’t depend on the platform and the programming language. You can write a program in any language on any platform to send, receive, or store data using XML. It defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. Data is stored in XML documents. XSL(eXtensible Stylesheet Language) documents describe how to change XML documents into other kinds of documents (such as HTML, TXT or even XML.) The process of transformation is called XSLT, or sometimes XSL transformations. Example: <?xml version=“1.0” standalone=“yes” ?><message> <from> Robert </from> <to> Mario </to></message> Note: For more information, refer to XML | Basics 1) Creating XML document using minidomFirst, we import minidom for using xml.dom. Then we create the root element and append it to the XML. After that creating a child product of parent namely Geeks for Geeks. After creating a child product the filename is saved as ‘any name as per your choice.xml’. Do not forget to append .xml at the end of the filename you have given to the file. Minidom is a minimal implementation of the Document Object Model interface, with an API similar to that in other languages. It is intended to be simpler than the full DOM and also significantly smaller. Example: from xml.dom import minidomimport os root = minidom.Document() xml = root.createElement('root') root.appendChild(xml) productChild = root.createElement('product')productChild.setAttribute('name', 'Geeks for Geeks') xml.appendChild(productChild) xml_str = root.toprettyxml(indent ="\t") save_path_file = "gfg.xml" with open(save_path_file, "w") as f: f.write(xml_str) Output: 2) Creating XML document using ElementTreeFirstly we have to import 'xml.etree.ElementTree' for creating a subtree. After that, we make root element, and that root element should be in an intended block otherwise the error will arise. After creating the root element, we can create a tree structure easily. Then the file will be stored as ‘name you want to give to that file.xml’. ElementTree is an important Python library that allows you to parse and navigate an XML document. Using ElementTree, we can break a document in a tree structure that is easy to work with. Example: import xml.etree.ElementTree as gfg def GenerateXML(fileName) : root = gfg.Element("Catalog") m1 = gfg.Element("mobile") root.append (m1) b1 = gfg.SubElement(m1, "brand") b1.text = "Redmi" b2 = gfg.SubElement(m1, "price") b2.text = "6999" m2 = gfg.Element("mobile") root.append (m2) c1 = gfg.SubElement(m2, "brand") c1.text = "Samsung" c2 = gfg.SubElement(m2, "price") c2.text = "9999" m3 = gfg.Element("mobile") root.append (m3) d1 = gfg.SubElement(m3, "brand") d1.text = "RealMe" d2 = gfg.SubElement(m3, "price") d2.text = "11999" tree = gfg.ElementTree(root) with open (fileName, "wb") as files : tree.write(files) # Driver Codeif __name__ == "__main__": GenerateXML("Catalog.xml") Output: There are three helper functions that are useful for creating a hierarchy of Elementnodes. Element() function creates a standard node, SubElement() function attaches a new node to a parent node, and Comment() function creates a node that serializes using XML’s comment syntax. The attribute values can be configured one at a time withset() (as with the root node), or all at once by passing a dictionary to the node factory(as with each group and podcast node). python-utility 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 Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Convert integer to string in Python
[ { "code": null, "e": 25747, "s": 25719, "text": "\n10 May, 2020" }, { "code": null, "e": 26354, "s": 25747, "text": "Extensible Markup Language(XML), is a markup language that you can use to create your own tags. It was created by the World Wide Web Consortium (W3C) to overcome the limitations of HTML, which is the basis for all Web pages. XML is based on SGML – Standard Generalized Markup Language. It is used for storing and transporting data. XML doesn’t depend on the platform and the programming language. You can write a program in any language on any platform to send, receive, or store data using XML. It defines a set of rules for encoding documents in a format that is both human-readable and machine-readable." }, { "code": null, "e": 26613, "s": 26354, "text": "Data is stored in XML documents. XSL(eXtensible Stylesheet Language) documents describe how to change XML documents into other kinds of documents (such as HTML, TXT or even XML.) The process of transformation is called XSLT, or sometimes XSL transformations." }, { "code": null, "e": 26622, "s": 26613, "text": "Example:" }, { "code": "<?xml version=“1.0” standalone=“yes” ?><message> <from> Robert </from> <to> Mario </to></message>", "e": 26725, "s": 26622, "text": null }, { "code": null, "e": 26775, "s": 26725, "text": "Note: For more information, refer to XML | Basics" }, { "code": null, "e": 27363, "s": 26775, "text": "1) Creating XML document using minidomFirst, we import minidom for using xml.dom. Then we create the root element and append it to the XML. After that creating a child product of parent namely Geeks for Geeks. After creating a child product the filename is saved as ‘any name as per your choice.xml’. Do not forget to append .xml at the end of the filename you have given to the file. Minidom is a minimal implementation of the Document Object Model interface, with an API similar to that in other languages. It is intended to be simpler than the full DOM and also significantly smaller." }, { "code": null, "e": 27372, "s": 27363, "text": "Example:" }, { "code": "from xml.dom import minidomimport os root = minidom.Document() xml = root.createElement('root') root.appendChild(xml) productChild = root.createElement('product')productChild.setAttribute('name', 'Geeks for Geeks') xml.appendChild(productChild) xml_str = root.toprettyxml(indent =\"\\t\") save_path_file = \"gfg.xml\" with open(save_path_file, \"w\") as f: f.write(xml_str) ", "e": 27754, "s": 27372, "text": null }, { "code": null, "e": 27762, "s": 27754, "text": "Output:" }, { "code": null, "e": 28331, "s": 27762, "text": "2) Creating XML document using ElementTreeFirstly we have to import 'xml.etree.ElementTree' for creating a subtree. After that, we make root element, and that root element should be in an intended block otherwise the error will arise. After creating the root element, we can create a tree structure easily. Then the file will be stored as ‘name you want to give to that file.xml’. ElementTree is an important Python library that allows you to parse and navigate an XML document. Using ElementTree, we can break a document in a tree structure that is easy to work with." }, { "code": null, "e": 28340, "s": 28331, "text": "Example:" }, { "code": "import xml.etree.ElementTree as gfg def GenerateXML(fileName) : root = gfg.Element(\"Catalog\") m1 = gfg.Element(\"mobile\") root.append (m1) b1 = gfg.SubElement(m1, \"brand\") b1.text = \"Redmi\" b2 = gfg.SubElement(m1, \"price\") b2.text = \"6999\" m2 = gfg.Element(\"mobile\") root.append (m2) c1 = gfg.SubElement(m2, \"brand\") c1.text = \"Samsung\" c2 = gfg.SubElement(m2, \"price\") c2.text = \"9999\" m3 = gfg.Element(\"mobile\") root.append (m3) d1 = gfg.SubElement(m3, \"brand\") d1.text = \"RealMe\" d2 = gfg.SubElement(m3, \"price\") d2.text = \"11999\" tree = gfg.ElementTree(root) with open (fileName, \"wb\") as files : tree.write(files) # Driver Codeif __name__ == \"__main__\": GenerateXML(\"Catalog.xml\")", "e": 29158, "s": 28340, "text": null }, { "code": null, "e": 29166, "s": 29158, "text": "Output:" }, { "code": null, "e": 29443, "s": 29166, "text": "There are three helper functions that are useful for creating a hierarchy of Elementnodes. Element() function creates a standard node, SubElement() function attaches a new node to a parent node, and Comment() function creates a node that serializes using XML’s comment syntax." }, { "code": null, "e": 29628, "s": 29443, "text": "The attribute values can be configured one at a time withset() (as with the root node), or all at once by passing a dictionary to the node factory(as with each group and podcast node)." }, { "code": null, "e": 29643, "s": 29628, "text": "python-utility" }, { "code": null, "e": 29650, "s": 29643, "text": "Python" }, { "code": null, "e": 29748, "s": 29650, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29766, "s": 29748, "text": "Python Dictionary" }, { "code": null, "e": 29798, "s": 29766, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29820, "s": 29798, "text": "Enumerate() in Python" }, { "code": null, "e": 29862, "s": 29820, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29892, "s": 29862, "text": "Iterate over a list in Python" }, { "code": null, "e": 29918, "s": 29892, "text": "Python String | replace()" }, { "code": null, "e": 29947, "s": 29918, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29991, "s": 29947, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 30028, "s": 29991, "text": "Create a Pandas DataFrame from Lists" } ]
How to Effortlessly Handle Class Imbalance with Python and SMOTE | by Dario Radečić | Towards Data Science
How many times did you get a 99% accurate model that’s unusable? Building classification models is no-joke, especially when there’s a class imbalance in your data. You know, when there’s only one fraud in 1000 transactions. You see, identifying 950 of 999 genuine transactions is easy. The trick is to correctly identify a single fraud case — every time. Reading feels like a nightmare? There’s an easy solution: That’s where SMOTE (Synthetic Minority Over-sampling Technique) comes in handy. You can use it to oversample the minority class. SMOTE is a type of data augmentation that synthesizes new samples from the existing ones. Yes — SMOTE actually creates new samples. It is light years ahead from simple duplication of the minority class. That approach stupidly creates “new” data points by duplicating existing ones. As a result, no new information is brought to the dataset. But how does SMOTE do it? It selects samples in the minority class that are close and then draws lines between them. New sample points are located on these lines. To be more precise, a random sample is chosen, and then a KNN algorithm is used to select neighbors to which lines are drawn. With this procedure, you can create as many synthetic samples as needed. This makes SMOTE perfect for datasets of all sizes. The only real downside is that synthetic examples are created without “consulting” the majority class. This could result in overlapping samples in both classes. That’s the only theory you’ll need to understand this article. Here are the topics covered next: Dataset loading and preparation Machine learning without SMOTE Machine learning with SMOTE Conclusion So you need a classification dataset that suffers from a class imbalance problem. Something like credit card fraud detection should do. Here’s one from Kaggle you can download for free. Here’s how to load it with Python: There are twenty-something columns which you’ll prepare in a bit. First, let’s explore the target class distribution: Yikes. Only around 1.68% of transactions are classified as fraud. A great recipe to make high-accuracy low-recall models. More on that in a bit. You can’t pass a dataset to a machine learning algorithm in this form. Some preparation is a must. You won’t spend much time here. The goal is to get a minimum viable dataset for machine learning. Here’s the list of initial changes: Remap gender, car, and reality to integers (0, 1) – these columns have only two possible values Create dummy variables for income_type, education_type, family_name, house_type – to go from strings to binary (0, 1) Drop unnecessary columns — Unnamed: 0, ID, and every column for which you created dummy variables Merge all into a single data frame Here’s the code for that: The dataset now looks like this: Better, but still needs a bit of work. Notice how larger the values are in income than in no_of_child. That’s expected, but machine learning algorithms will give more importance to variables on a larger scale. Introducing data scaling. You’ll use MinMaxScaler from scikit-learn to scale columns that have values greater than 1 to [0, 1] range. Here’ how: Here’s how the dataset looks now: Much better — everything is in the [0, 1] range, all columns are numerical, and there are no missing values. This means one thing — the dataset is machine learning ready. Let’s start with a naive approach. You’ll create a Random Forest model on the dataset and completely ignore the class imbalance. To start, you’ll have to split the dataset into training and testing portions. There’s only 1.68% of fraud transactions in the entire dataset. Ideally, you want the percentage roughly the same in the train and test sets. Here’s how to do the split and check the percentage of the positive class: Onto the modeling now. Let’s make it as simple as possible. You’ll train a Random Forest classifier on the train set and evaluate it on the test set. Confusion matrix, accuracy score, and recall score will tell you just how bad is it: The model is 98% accurate, so where’s the problem? Yes, it can correctly classify almost all genuine transactions. But it also classified 91% of fraud transactions as genuine. In a nutshell — the model is unusable. Class imbalance killed its performance. SMOTE can help. You already know what SMOTE is, and now you’ll see how to install it and use it. Execute the following command from Terminal: pip install imbalanced-learn You can now apply SMOTE to features (X) and the target (y) and store the results in dedicated variables. The new feature and target set is larger, due to oversampling. Here’s the code for applying SMOTE: There are 37K data points instead of 25K, and the class balance is perfect — 50:50. You’ll train the model on a new dataset next: The resulting model is usable, to say at least. SMOTE did its job, and it resulted in a model that significantly outperformed its previous version. Let’s wrap things up next. And there you have it — SMOTE in a nutshell. You can use it whenever a dataset suffers from a class imbalance problem. The go-to approach nowadays is to use both undersampling and oversampling, but that’s a topic for another time. Just for fun, you can compare the misclassifications of both models. By doing so, you could see if the model built after oversampling still misclassifies the same data points. How do you handle class imbalance? Let me know in the comments below. 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": 395, "s": 171, "text": "How many times did you get a 99% accurate model that’s unusable? Building classification models is no-joke, especially when there’s a class imbalance in your data. You know, when there’s only one fraud in 1000 transactions." }, { "code": null, "e": 526, "s": 395, "text": "You see, identifying 950 of 999 genuine transactions is easy. The trick is to correctly identify a single fraud case — every time." }, { "code": null, "e": 584, "s": 526, "text": "Reading feels like a nightmare? There’s an easy solution:" }, { "code": null, "e": 803, "s": 584, "text": "That’s where SMOTE (Synthetic Minority Over-sampling Technique) comes in handy. You can use it to oversample the minority class. SMOTE is a type of data augmentation that synthesizes new samples from the existing ones." }, { "code": null, "e": 1054, "s": 803, "text": "Yes — SMOTE actually creates new samples. It is light years ahead from simple duplication of the minority class. That approach stupidly creates “new” data points by duplicating existing ones. As a result, no new information is brought to the dataset." }, { "code": null, "e": 1080, "s": 1054, "text": "But how does SMOTE do it?" }, { "code": null, "e": 1217, "s": 1080, "text": "It selects samples in the minority class that are close and then draws lines between them. New sample points are located on these lines." }, { "code": null, "e": 1468, "s": 1217, "text": "To be more precise, a random sample is chosen, and then a KNN algorithm is used to select neighbors to which lines are drawn. With this procedure, you can create as many synthetic samples as needed. This makes SMOTE perfect for datasets of all sizes." }, { "code": null, "e": 1629, "s": 1468, "text": "The only real downside is that synthetic examples are created without “consulting” the majority class. This could result in overlapping samples in both classes." }, { "code": null, "e": 1692, "s": 1629, "text": "That’s the only theory you’ll need to understand this article." }, { "code": null, "e": 1726, "s": 1692, "text": "Here are the topics covered next:" }, { "code": null, "e": 1758, "s": 1726, "text": "Dataset loading and preparation" }, { "code": null, "e": 1789, "s": 1758, "text": "Machine learning without SMOTE" }, { "code": null, "e": 1817, "s": 1789, "text": "Machine learning with SMOTE" }, { "code": null, "e": 1828, "s": 1817, "text": "Conclusion" }, { "code": null, "e": 2014, "s": 1828, "text": "So you need a classification dataset that suffers from a class imbalance problem. Something like credit card fraud detection should do. Here’s one from Kaggle you can download for free." }, { "code": null, "e": 2049, "s": 2014, "text": "Here’s how to load it with Python:" }, { "code": null, "e": 2167, "s": 2049, "text": "There are twenty-something columns which you’ll prepare in a bit. First, let’s explore the target class distribution:" }, { "code": null, "e": 2312, "s": 2167, "text": "Yikes. Only around 1.68% of transactions are classified as fraud. A great recipe to make high-accuracy low-recall models. More on that in a bit." }, { "code": null, "e": 2411, "s": 2312, "text": "You can’t pass a dataset to a machine learning algorithm in this form. Some preparation is a must." }, { "code": null, "e": 2509, "s": 2411, "text": "You won’t spend much time here. The goal is to get a minimum viable dataset for machine learning." }, { "code": null, "e": 2545, "s": 2509, "text": "Here’s the list of initial changes:" }, { "code": null, "e": 2641, "s": 2545, "text": "Remap gender, car, and reality to integers (0, 1) – these columns have only two possible values" }, { "code": null, "e": 2759, "s": 2641, "text": "Create dummy variables for income_type, education_type, family_name, house_type – to go from strings to binary (0, 1)" }, { "code": null, "e": 2857, "s": 2759, "text": "Drop unnecessary columns — Unnamed: 0, ID, and every column for which you created dummy variables" }, { "code": null, "e": 2892, "s": 2857, "text": "Merge all into a single data frame" }, { "code": null, "e": 2918, "s": 2892, "text": "Here’s the code for that:" }, { "code": null, "e": 2951, "s": 2918, "text": "The dataset now looks like this:" }, { "code": null, "e": 3187, "s": 2951, "text": "Better, but still needs a bit of work. Notice how larger the values are in income than in no_of_child. That’s expected, but machine learning algorithms will give more importance to variables on a larger scale. Introducing data scaling." }, { "code": null, "e": 3306, "s": 3187, "text": "You’ll use MinMaxScaler from scikit-learn to scale columns that have values greater than 1 to [0, 1] range. Here’ how:" }, { "code": null, "e": 3340, "s": 3306, "text": "Here’s how the dataset looks now:" }, { "code": null, "e": 3449, "s": 3340, "text": "Much better — everything is in the [0, 1] range, all columns are numerical, and there are no missing values." }, { "code": null, "e": 3511, "s": 3449, "text": "This means one thing — the dataset is machine learning ready." }, { "code": null, "e": 3640, "s": 3511, "text": "Let’s start with a naive approach. You’ll create a Random Forest model on the dataset and completely ignore the class imbalance." }, { "code": null, "e": 3861, "s": 3640, "text": "To start, you’ll have to split the dataset into training and testing portions. There’s only 1.68% of fraud transactions in the entire dataset. Ideally, you want the percentage roughly the same in the train and test sets." }, { "code": null, "e": 3936, "s": 3861, "text": "Here’s how to do the split and check the percentage of the positive class:" }, { "code": null, "e": 4171, "s": 3936, "text": "Onto the modeling now. Let’s make it as simple as possible. You’ll train a Random Forest classifier on the train set and evaluate it on the test set. Confusion matrix, accuracy score, and recall score will tell you just how bad is it:" }, { "code": null, "e": 4222, "s": 4171, "text": "The model is 98% accurate, so where’s the problem?" }, { "code": null, "e": 4386, "s": 4222, "text": "Yes, it can correctly classify almost all genuine transactions. But it also classified 91% of fraud transactions as genuine. In a nutshell — the model is unusable." }, { "code": null, "e": 4442, "s": 4386, "text": "Class imbalance killed its performance. SMOTE can help." }, { "code": null, "e": 4568, "s": 4442, "text": "You already know what SMOTE is, and now you’ll see how to install it and use it. Execute the following command from Terminal:" }, { "code": null, "e": 4597, "s": 4568, "text": "pip install imbalanced-learn" }, { "code": null, "e": 4801, "s": 4597, "text": "You can now apply SMOTE to features (X) and the target (y) and store the results in dedicated variables. The new feature and target set is larger, due to oversampling. Here’s the code for applying SMOTE:" }, { "code": null, "e": 4931, "s": 4801, "text": "There are 37K data points instead of 25K, and the class balance is perfect — 50:50. You’ll train the model on a new dataset next:" }, { "code": null, "e": 5079, "s": 4931, "text": "The resulting model is usable, to say at least. SMOTE did its job, and it resulted in a model that significantly outperformed its previous version." }, { "code": null, "e": 5106, "s": 5079, "text": "Let’s wrap things up next." }, { "code": null, "e": 5337, "s": 5106, "text": "And there you have it — SMOTE in a nutshell. You can use it whenever a dataset suffers from a class imbalance problem. The go-to approach nowadays is to use both undersampling and oversampling, but that’s a topic for another time." }, { "code": null, "e": 5513, "s": 5337, "text": "Just for fun, you can compare the misclassifications of both models. By doing so, you could see if the model built after oversampling still misclassifies the same data points." }, { "code": null, "e": 5583, "s": 5513, "text": "How do you handle class imbalance? Let me know in the comments below." } ]
Fail Fast and Fail Safe Iterators in Java - GeeksforGeeks
29 Jan, 2021 In this article, I am going to explain how those collections behave which doesn’t iterate as fail-fast. First of all, there is no term as fail-safe given in many places as Java SE specifications does not use this term. I am using fail safe to segregate between Fail fast and Non fail-fast iterators.Concurrent Modification: Concurrent Modification in programming means to modify an object concurrently when another task is already running over it. For example, in Java to modify a collection when another thread is iterating over it. Some Iterator implementations (including those of all the general purpose collection implementations provided by the JRE) may choose to throw ConcurrentModificationException if this behavior is detected. Fail Fast And Fail Safe Iterators in Java Iterators in java are used to iterate over the Collection objects.Fail-Fast iterators immediately throw ConcurrentModificationException if there is structural modification of the collection. Structural modification means adding, removing any element from collection while a thread is iterating over that collection. Iterator on ArrayList, HashMap classes are some examples of fail-fast Iterator.Fail-Safe iterators don’t throw any exceptions if a collection is structurally modified while iterating over it. This is because, they operate on the clone of the collection, not on the original collection and that’s why they are called fail-safe iterators. Iterator on CopyOnWriteArrayList, ConcurrentHashMap classes are examples of fail-safe Iterator. How Fail Fast Iterator works ? To know whether the collection is structurally modified or not, fail-fast iterators use an internal flag called modCount which is updated each time a collection is modified.Fail-fast iterators checks the modCount flag whenever it gets the next value (i.e. using next() method), and if it finds that the modCount has been modified after this iterator has been created, it throws ConcurrentModificationException. Java // Java code to illustrate// Fail Fast Iterator in Javaimport java.util.HashMap;import java.util.Iterator;import java.util.Map; public class FailFastExample { public static void main(String[] args) { Map<String, String> cityCode = new HashMap<String, String>(); cityCode.put("Delhi", "India"); cityCode.put("Moscow", "Russia"); cityCode.put("New York", "USA"); Iterator iterator = cityCode.keySet().iterator(); while (iterator.hasNext()) { System.out.println(cityCode.get(iterator.next())); // adding an element to Map // exception will be thrown on next call // of next() method. cityCode.put("Istanbul", "Turkey"); } }} Output : India Exception in thread "main" java.util.ConcurrentModificationException at java.util.HashMap$HashIterator.nextNode(HashMap.java:1442) at java.util.HashMap$KeyIterator.next(HashMap.java:1466) at FailFastExample.main(FailFastExample.java:18) Important points of fail-fast iterators : These iterators throw ConcurrentModificationException if a collection is modified while iterating over it. They use original collection to traverse over the elements of the collection. These iterators don’t require extra memory. Ex : Iterators returned by ArrayList, Vector, HashMap. Note 1(from java-docs): The fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.Note 2 : If you remove an element via Iterator remove() method, exception will not be thrown. However, in case of removing via a particular collection remove() method, ConcurrentModificationException will be thrown. Below code snippet will demonstrate this: Java // Java code to demonstrate remove// case in Fail-fast iterators import java.util.ArrayList;import java.util.Iterator; public class FailFastExample { public static void main(String[] args) { ArrayList<Integer> al = new ArrayList<>(); al.add(1); al.add(2); al.add(3); al.add(4); al.add(5); Iterator<Integer> itr = al.iterator(); while (itr.hasNext()) { if (itr.next() == 2) { // will not throw Exception itr.remove(); } } System.out.println(al); itr = al.iterator(); while (itr.hasNext()) { if (itr.next() == 3) { // will throw Exception on // next call of next() method al.remove(3); } } }} Output : [1, 3, 4, 5] Exception in thread "main" java.util.ConcurrentModificationException at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901) at java.util.ArrayList$Itr.next(ArrayList.java:851) at FailFastExample.main(FailFastExample.java:28) Fail Safe Iterator First of all, there is no term as fail-safe given in many places as Java SE specifications does not use this term. I am using this term to demonstrate the difference between Fail Fast and Non-Fail Fast Iterator. These iterators make a copy of the internal collection (object array) and iterates over the copied collection. Any structural modification done to the iterator affects the copied collection, not original collection. So, original collection remains structurally unchanged. Fail-safe iterators allow modifications of a collection while iterating over it. These iterators don’t throw any Exception if a collection is modified while iterating over it. They use copy of original collection to traverse over the elements of the collection. These iterators require extra memory for cloning of collection. Ex : ConcurrentHashMap, CopyOnWriteArrayList Example of Fail Safe Iterator in Java: Java // Java code to illustrate// Fail Safe Iterator in Javaimport java.util.concurrent.CopyOnWriteArrayList;import java.util.Iterator; class FailSafe { public static void main(String args[]) { CopyOnWriteArrayList<Integer> list = new CopyOnWriteArrayList<Integer>(new Integer[] { 1, 3, 5, 8 }); Iterator itr = list.iterator(); while (itr.hasNext()) { Integer no = (Integer)itr.next(); System.out.println(no); if (no == 8) // This will not print, // hence it has created separate copy list.add(14); } }} Output: 1 3 5 8 Also, those collections which don’t use fail-fast concept may not necessarily create clone/snapshot of it in memory to avoid ConcurrentModificationException. For example, in case of ConcurrentHashMap, it does not operate on a separate copy although it is not fail-fast. Instead, it has semantics that is described by the official specification as weakly consistent(memory consistency properties in Java). Below code snippet will demonstrate this:Example of Fail-Safe Iterator which does not create separate copy Java // Java program to illustrate// Fail-Safe Iterator which// does not create separate copyimport java.util.concurrent.ConcurrentHashMap;import java.util.Iterator; public class FailSafeItr { public static void main(String[] args) { // Creating a ConcurrentHashMap ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<String, Integer>(); map.put("ONE", 1); map.put("TWO", 2); map.put("THREE", 3); map.put("FOUR", 4); // Getting an Iterator from map Iterator it = map.keySet().iterator(); while (it.hasNext()) { String key = (String)it.next(); System.out.println(key + " : " + map.get(key)); // This will reflect in iterator. // Hence, it has not created separate copy map.put("SEVEN", 7); } }} Output ONE : 1 FOUR : 4 TWO : 2 THREE : 3 SEVEN : 7 Note(from java-docs) : The iterators returned by ConcurrentHashMap is weakly consistent. This means that this iterator can tolerate concurrent modification, traverses elements as they existed when iterator was constructed and may (but not guaranteed to) reflect modifications to the collection after the construction of the iterator. Difference between Fail Fast Iterator and Fail Safe Iterator The major difference is fail-safe iterator doesn’t throw any Exception, contrary to fail-fast Iterator.This is because they work on a clone of Collection instead of the original collection and that’s why they are called as the fail-safe iterator. vikas06sharma93 Java-HashMap Java-Iterator Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Interfaces in Java Object Oriented Programming (OOPs) Concept in Java ArrayList in Java How to iterate any Map in Java Initialize an ArrayList in Java Singleton Class in Java Overriding in Java Collections in Java Multithreading in Java Set in Java
[ { "code": null, "e": 24550, "s": 24522, "text": "\n29 Jan, 2021" }, { "code": null, "e": 25289, "s": 24550, "text": "In this article, I am going to explain how those collections behave which doesn’t iterate as fail-fast. First of all, there is no term as fail-safe given in many places as Java SE specifications does not use this term. I am using fail safe to segregate between Fail fast and Non fail-fast iterators.Concurrent Modification: Concurrent Modification in programming means to modify an object concurrently when another task is already running over it. For example, in Java to modify a collection when another thread is iterating over it. Some Iterator implementations (including those of all the general purpose collection implementations provided by the JRE) may choose to throw ConcurrentModificationException if this behavior is detected. " }, { "code": null, "e": 25331, "s": 25289, "text": "Fail Fast And Fail Safe Iterators in Java" }, { "code": null, "e": 26081, "s": 25331, "text": "Iterators in java are used to iterate over the Collection objects.Fail-Fast iterators immediately throw ConcurrentModificationException if there is structural modification of the collection. Structural modification means adding, removing any element from collection while a thread is iterating over that collection. Iterator on ArrayList, HashMap classes are some examples of fail-fast Iterator.Fail-Safe iterators don’t throw any exceptions if a collection is structurally modified while iterating over it. This is because, they operate on the clone of the collection, not on the original collection and that’s why they are called fail-safe iterators. Iterator on CopyOnWriteArrayList, ConcurrentHashMap classes are examples of fail-safe Iterator. " }, { "code": null, "e": 26112, "s": 26081, "text": "How Fail Fast Iterator works ?" }, { "code": null, "e": 26524, "s": 26112, "text": "To know whether the collection is structurally modified or not, fail-fast iterators use an internal flag called modCount which is updated each time a collection is modified.Fail-fast iterators checks the modCount flag whenever it gets the next value (i.e. using next() method), and if it finds that the modCount has been modified after this iterator has been created, it throws ConcurrentModificationException. " }, { "code": null, "e": 26529, "s": 26524, "text": "Java" }, { "code": "// Java code to illustrate// Fail Fast Iterator in Javaimport java.util.HashMap;import java.util.Iterator;import java.util.Map; public class FailFastExample { public static void main(String[] args) { Map<String, String> cityCode = new HashMap<String, String>(); cityCode.put(\"Delhi\", \"India\"); cityCode.put(\"Moscow\", \"Russia\"); cityCode.put(\"New York\", \"USA\"); Iterator iterator = cityCode.keySet().iterator(); while (iterator.hasNext()) { System.out.println(cityCode.get(iterator.next())); // adding an element to Map // exception will be thrown on next call // of next() method. cityCode.put(\"Istanbul\", \"Turkey\"); } }}", "e": 27271, "s": 26529, "text": null }, { "code": null, "e": 27282, "s": 27271, "text": "Output : " }, { "code": null, "e": 27537, "s": 27282, "text": "India\nException in thread \"main\" java.util.ConcurrentModificationException\n at java.util.HashMap$HashIterator.nextNode(HashMap.java:1442)\n at java.util.HashMap$KeyIterator.next(HashMap.java:1466)\n at FailFastExample.main(FailFastExample.java:18)" }, { "code": null, "e": 27581, "s": 27537, "text": "Important points of fail-fast iterators : " }, { "code": null, "e": 27688, "s": 27581, "text": "These iterators throw ConcurrentModificationException if a collection is modified while iterating over it." }, { "code": null, "e": 27766, "s": 27688, "text": "They use original collection to traverse over the elements of the collection." }, { "code": null, "e": 27810, "s": 27766, "text": "These iterators don’t require extra memory." }, { "code": null, "e": 27865, "s": 27810, "text": "Ex : Iterators returned by ArrayList, Vector, HashMap." }, { "code": null, "e": 28589, "s": 27865, "text": "Note 1(from java-docs): The fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.Note 2 : If you remove an element via Iterator remove() method, exception will not be thrown. However, in case of removing via a particular collection remove() method, ConcurrentModificationException will be thrown. Below code snippet will demonstrate this: " }, { "code": null, "e": 28594, "s": 28589, "text": "Java" }, { "code": "// Java code to demonstrate remove// case in Fail-fast iterators import java.util.ArrayList;import java.util.Iterator; public class FailFastExample { public static void main(String[] args) { ArrayList<Integer> al = new ArrayList<>(); al.add(1); al.add(2); al.add(3); al.add(4); al.add(5); Iterator<Integer> itr = al.iterator(); while (itr.hasNext()) { if (itr.next() == 2) { // will not throw Exception itr.remove(); } } System.out.println(al); itr = al.iterator(); while (itr.hasNext()) { if (itr.next() == 3) { // will throw Exception on // next call of next() method al.remove(3); } } }}", "e": 29412, "s": 28594, "text": null }, { "code": null, "e": 29423, "s": 29412, "text": "Output : " }, { "code": null, "e": 29688, "s": 29423, "text": "[1, 3, 4, 5]\nException in thread \"main\" java.util.ConcurrentModificationException\n at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)\n at java.util.ArrayList$Itr.next(ArrayList.java:851)\n at FailFastExample.main(FailFastExample.java:28)" }, { "code": null, "e": 29709, "s": 29690, "text": "Fail Safe Iterator" }, { "code": null, "e": 30195, "s": 29709, "text": "First of all, there is no term as fail-safe given in many places as Java SE specifications does not use this term. I am using this term to demonstrate the difference between Fail Fast and Non-Fail Fast Iterator. These iterators make a copy of the internal collection (object array) and iterates over the copied collection. Any structural modification done to the iterator affects the copied collection, not original collection. So, original collection remains structurally unchanged. " }, { "code": null, "e": 30276, "s": 30195, "text": "Fail-safe iterators allow modifications of a collection while iterating over it." }, { "code": null, "e": 30371, "s": 30276, "text": "These iterators don’t throw any Exception if a collection is modified while iterating over it." }, { "code": null, "e": 30457, "s": 30371, "text": "They use copy of original collection to traverse over the elements of the collection." }, { "code": null, "e": 30566, "s": 30457, "text": "These iterators require extra memory for cloning of collection. Ex : ConcurrentHashMap, CopyOnWriteArrayList" }, { "code": null, "e": 30606, "s": 30566, "text": "Example of Fail Safe Iterator in Java: " }, { "code": null, "e": 30611, "s": 30606, "text": "Java" }, { "code": "// Java code to illustrate// Fail Safe Iterator in Javaimport java.util.concurrent.CopyOnWriteArrayList;import java.util.Iterator; class FailSafe { public static void main(String args[]) { CopyOnWriteArrayList<Integer> list = new CopyOnWriteArrayList<Integer>(new Integer[] { 1, 3, 5, 8 }); Iterator itr = list.iterator(); while (itr.hasNext()) { Integer no = (Integer)itr.next(); System.out.println(no); if (no == 8) // This will not print, // hence it has created separate copy list.add(14); } }}", "e": 31239, "s": 30611, "text": null }, { "code": null, "e": 31249, "s": 31239, "text": "Output: " }, { "code": null, "e": 31257, "s": 31249, "text": "1\n3\n5\n8" }, { "code": null, "e": 31771, "s": 31257, "text": "Also, those collections which don’t use fail-fast concept may not necessarily create clone/snapshot of it in memory to avoid ConcurrentModificationException. For example, in case of ConcurrentHashMap, it does not operate on a separate copy although it is not fail-fast. Instead, it has semantics that is described by the official specification as weakly consistent(memory consistency properties in Java). Below code snippet will demonstrate this:Example of Fail-Safe Iterator which does not create separate copy " }, { "code": null, "e": 31776, "s": 31771, "text": "Java" }, { "code": "// Java program to illustrate// Fail-Safe Iterator which// does not create separate copyimport java.util.concurrent.ConcurrentHashMap;import java.util.Iterator; public class FailSafeItr { public static void main(String[] args) { // Creating a ConcurrentHashMap ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<String, Integer>(); map.put(\"ONE\", 1); map.put(\"TWO\", 2); map.put(\"THREE\", 3); map.put(\"FOUR\", 4); // Getting an Iterator from map Iterator it = map.keySet().iterator(); while (it.hasNext()) { String key = (String)it.next(); System.out.println(key + \" : \" + map.get(key)); // This will reflect in iterator. // Hence, it has not created separate copy map.put(\"SEVEN\", 7); } }}", "e": 32632, "s": 31776, "text": null }, { "code": null, "e": 32641, "s": 32632, "text": "Output " }, { "code": null, "e": 32686, "s": 32641, "text": "ONE : 1\nFOUR : 4\nTWO : 2\nTHREE : 3\nSEVEN : 7" }, { "code": null, "e": 33021, "s": 32686, "text": "Note(from java-docs) : The iterators returned by ConcurrentHashMap is weakly consistent. This means that this iterator can tolerate concurrent modification, traverses elements as they existed when iterator was constructed and may (but not guaranteed to) reflect modifications to the collection after the construction of the iterator. " }, { "code": null, "e": 33082, "s": 33021, "text": "Difference between Fail Fast Iterator and Fail Safe Iterator" }, { "code": null, "e": 33330, "s": 33082, "text": "The major difference is fail-safe iterator doesn’t throw any Exception, contrary to fail-fast Iterator.This is because they work on a clone of Collection instead of the original collection and that’s why they are called as the fail-safe iterator. " }, { "code": null, "e": 33346, "s": 33330, "text": "vikas06sharma93" }, { "code": null, "e": 33359, "s": 33346, "text": "Java-HashMap" }, { "code": null, "e": 33373, "s": 33359, "text": "Java-Iterator" }, { "code": null, "e": 33378, "s": 33373, "text": "Java" }, { "code": null, "e": 33383, "s": 33378, "text": "Java" }, { "code": null, "e": 33481, "s": 33383, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33490, "s": 33481, "text": "Comments" }, { "code": null, "e": 33503, "s": 33490, "text": "Old Comments" }, { "code": null, "e": 33522, "s": 33503, "text": "Interfaces in Java" }, { "code": null, "e": 33573, "s": 33522, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 33591, "s": 33573, "text": "ArrayList in Java" }, { "code": null, "e": 33622, "s": 33591, "text": "How to iterate any Map in Java" }, { "code": null, "e": 33654, "s": 33622, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 33678, "s": 33654, "text": "Singleton Class in Java" }, { "code": null, "e": 33697, "s": 33678, "text": "Overriding in Java" }, { "code": null, "e": 33717, "s": 33697, "text": "Collections in Java" }, { "code": null, "e": 33740, "s": 33717, "text": "Multithreading in Java" } ]
Android - TextView Control
A TextView displays text to the user and optionally allows them to edit it. A TextView is a complete text editor, however the basic class is configured to not allow editing. Following are the important attributes related to TextView control. You can check Android official documentation for complete list of attributes and related methods which you can use to change these attributes are run time. android:id This is the ID which uniquely identifies the control. android:capitalize If set, specifies that this TextView has a textual input method and should automatically capitalize what the user types. Don't automatically capitalize anything - 0 Capitalize the first word of each sentence - 1 Capitalize the first letter of every word - 2 Capitalize every character - 3 android:cursorVisible Makes the cursor visible (the default) or invisible. Default is false. android:editable If set to true, specifies that this TextView has an input method. android:fontFamily Font family (named by string) for the text. android:gravity Specifies how to align the text by the view's x- and/or y-axis when the text is smaller than the view. android:hint Hint text to display when the text is empty. android:inputType The type of data being placed in a text field. Phone, Date, Time, Number, Password etc. android:maxHeight Makes the TextView be at most this many pixels tall. android:maxWidth Makes the TextView be at most this many pixels wide. android:minHeight Makes the TextView be at least this many pixels tall. android:minWidth Makes the TextView be at least this many pixels wide. android:password Whether the characters of the field are displayed as password dots instead of themselves. Possible value either "true" or "false". android:phoneNumber If set, specifies that this TextView has a phone number input method. Possible value either "true" or "false". android:text Text to display. android:textAllCaps Present the text in ALL CAPS. Possible value either "true" or "false". android:textColor Text color. May be a color value, in the form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb". android:textColorHighlight Color of the text selection highlight. android:textColorHint Color of the hint text. May be a color value, in the form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb". android:textIsSelectable Indicates that the content of a non-editable text can be selected. Possible value either "true" or "false". android:textSize Size of the text. Recommended dimension type for text is "sp" for scaled-pixels (example: 15sp). android:textStyle Style (bold, italic, bolditalic) for the text. You can use or more of the following values separated by '|'. normal - 0 bold - 1 italic - 2 android:typeface Typeface (normal, sans, serif, monospace) for the text. You can use or more of the following values separated by '|'. normal - 0 sans - 1 serif - 2 monospace - 3 This example will take you through simple steps to show how to create your own Android application using Linear Layout and TextView. Following is the content of the modified main activity file src/com.example.demo/MainActivity.java. This file can include each of the fundamental lifecycle methods. package com.example.demo; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.View; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //--- text view--- TextView txtView = (TextView) findViewById(R.id.text_id); } } Following will be the content of res/layout/activity_main.xml file − <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <TextView android:id="@+id/text_id" android:layout_width="300dp" android:layout_height="200dp" android:capitalize="characters" android:text="hello_world" android:textColor="@android:color/holo_blue_dark" android:textColorHighlight="@android:color/primary_text_dark" android:layout_centerVertical="true" android:layout_alignParentEnd="true" android:textSize="50dp"/> </RelativeLayout> Following will be the content of res/values/strings.xml to define two new constants − <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">demo</string> </resources> Following is the default content of AndroidManifest.xml − <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.demo" > <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme" > <activity android:name="com.example.demo.MainActivity" android:label="@string/app_name" > <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 demo application. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project's activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window − I will recommend to try above example with different attributes of TextView in Layout XML file as well at programming time to have different look and feel of the TextView. Try to make it editable, change to font color, font family, width, textSize etc and see the result. You can also try above example with multiple TextView controls in one activity. 46 Lectures 7.5 hours Aditya Dua 32 Lectures 3.5 hours Sharad Kumar 9 Lectures 1 hours Abhilash Nelson 14 Lectures 1.5 hours Abhilash Nelson 15 Lectures 1.5 hours Abhilash Nelson 10 Lectures 1 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 3781, "s": 3607, "text": "A TextView displays text to the user and optionally allows them to edit it. A TextView is a complete text editor, however the basic class is configured to not allow editing." }, { "code": null, "e": 4005, "s": 3781, "text": "Following are the important attributes related to TextView control. You can check Android official documentation for complete list of attributes and related methods which you can use to change these attributes are run time." }, { "code": null, "e": 4016, "s": 4005, "text": "android:id" }, { "code": null, "e": 4070, "s": 4016, "text": "This is the ID which uniquely identifies the control." }, { "code": null, "e": 4089, "s": 4070, "text": "android:capitalize" }, { "code": null, "e": 4210, "s": 4089, "text": "If set, specifies that this TextView has a textual input method and should automatically capitalize what the user types." }, { "code": null, "e": 4254, "s": 4210, "text": "Don't automatically capitalize anything - 0" }, { "code": null, "e": 4301, "s": 4254, "text": "Capitalize the first word of each sentence - 1" }, { "code": null, "e": 4347, "s": 4301, "text": "Capitalize the first letter of every word - 2" }, { "code": null, "e": 4378, "s": 4347, "text": "Capitalize every character - 3" }, { "code": null, "e": 4400, "s": 4378, "text": "android:cursorVisible" }, { "code": null, "e": 4471, "s": 4400, "text": "Makes the cursor visible (the default) or invisible. Default is false." }, { "code": null, "e": 4488, "s": 4471, "text": "android:editable" }, { "code": null, "e": 4554, "s": 4488, "text": "If set to true, specifies that this TextView has an input method." }, { "code": null, "e": 4573, "s": 4554, "text": "android:fontFamily" }, { "code": null, "e": 4617, "s": 4573, "text": "Font family (named by string) for the text." }, { "code": null, "e": 4633, "s": 4617, "text": "android:gravity" }, { "code": null, "e": 4736, "s": 4633, "text": "Specifies how to align the text by the view's x- and/or y-axis when the text is smaller than the view." }, { "code": null, "e": 4749, "s": 4736, "text": "android:hint" }, { "code": null, "e": 4794, "s": 4749, "text": "Hint text to display when the text is empty." }, { "code": null, "e": 4812, "s": 4794, "text": "android:inputType" }, { "code": null, "e": 4900, "s": 4812, "text": "The type of data being placed in a text field. Phone, Date, Time, Number, Password etc." }, { "code": null, "e": 4918, "s": 4900, "text": "android:maxHeight" }, { "code": null, "e": 4971, "s": 4918, "text": "Makes the TextView be at most this many pixels tall." }, { "code": null, "e": 4988, "s": 4971, "text": "android:maxWidth" }, { "code": null, "e": 5041, "s": 4988, "text": "Makes the TextView be at most this many pixels wide." }, { "code": null, "e": 5059, "s": 5041, "text": "android:minHeight" }, { "code": null, "e": 5113, "s": 5059, "text": "Makes the TextView be at least this many pixels tall." }, { "code": null, "e": 5130, "s": 5113, "text": "android:minWidth" }, { "code": null, "e": 5184, "s": 5130, "text": "Makes the TextView be at least this many pixels wide." }, { "code": null, "e": 5201, "s": 5184, "text": "android:password" }, { "code": null, "e": 5332, "s": 5201, "text": "Whether the characters of the field are displayed as password dots instead of themselves. Possible value either \"true\" or \"false\"." }, { "code": null, "e": 5352, "s": 5332, "text": "android:phoneNumber" }, { "code": null, "e": 5463, "s": 5352, "text": "If set, specifies that this TextView has a phone number input method. Possible value either \"true\" or \"false\"." }, { "code": null, "e": 5476, "s": 5463, "text": "android:text" }, { "code": null, "e": 5493, "s": 5476, "text": "Text to display." }, { "code": null, "e": 5513, "s": 5493, "text": "android:textAllCaps" }, { "code": null, "e": 5584, "s": 5513, "text": "Present the text in ALL CAPS. Possible value either \"true\" or \"false\"." }, { "code": null, "e": 5602, "s": 5584, "text": "android:textColor" }, { "code": null, "e": 5695, "s": 5602, "text": "Text color. May be a color value, in the form of \"#rgb\", \"#argb\", \"#rrggbb\", or \"#aarrggbb\"." }, { "code": null, "e": 5722, "s": 5695, "text": "android:textColorHighlight" }, { "code": null, "e": 5761, "s": 5722, "text": "Color of the text selection highlight." }, { "code": null, "e": 5783, "s": 5761, "text": "android:textColorHint" }, { "code": null, "e": 5888, "s": 5783, "text": "Color of the hint text. May be a color value, in the form of \"#rgb\", \"#argb\", \"#rrggbb\", or \"#aarrggbb\"." }, { "code": null, "e": 5913, "s": 5888, "text": "android:textIsSelectable" }, { "code": null, "e": 6021, "s": 5913, "text": "Indicates that the content of a non-editable text can be selected. Possible value either \"true\" or \"false\"." }, { "code": null, "e": 6038, "s": 6021, "text": "android:textSize" }, { "code": null, "e": 6135, "s": 6038, "text": "Size of the text. Recommended dimension type for text is \"sp\" for scaled-pixels (example: 15sp)." }, { "code": null, "e": 6153, "s": 6135, "text": "android:textStyle" }, { "code": null, "e": 6262, "s": 6153, "text": "Style (bold, italic, bolditalic) for the text. You can use or more of the following values separated by '|'." }, { "code": null, "e": 6273, "s": 6262, "text": "normal - 0" }, { "code": null, "e": 6282, "s": 6273, "text": "bold - 1" }, { "code": null, "e": 6293, "s": 6282, "text": "italic - 2" }, { "code": null, "e": 6310, "s": 6293, "text": "android:typeface" }, { "code": null, "e": 6428, "s": 6310, "text": "Typeface (normal, sans, serif, monospace) for the text. You can use or more of the following values separated by '|'." }, { "code": null, "e": 6439, "s": 6428, "text": "normal - 0" }, { "code": null, "e": 6448, "s": 6439, "text": "sans - 1" }, { "code": null, "e": 6458, "s": 6448, "text": "serif - 2" }, { "code": null, "e": 6472, "s": 6458, "text": "monospace - 3" }, { "code": null, "e": 6605, "s": 6472, "text": "This example will take you through simple steps to show how to create your own Android application using Linear Layout and TextView." }, { "code": null, "e": 6770, "s": 6605, "text": "Following is the content of the modified main activity file src/com.example.demo/MainActivity.java. This file can include each of the fundamental lifecycle methods." }, { "code": null, "e": 7271, "s": 6770, "text": "package com.example.demo;\n\nimport android.os.Bundle;\nimport android.app.Activity;\nimport android.view.Menu;\nimport android.view.View;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\npublic class MainActivity extends Activity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n \n //--- text view---\n TextView txtView = (TextView) findViewById(R.id.text_id);\n }\n}" }, { "code": null, "e": 7340, "s": 7271, "text": "Following will be the content of res/layout/activity_main.xml file −" }, { "code": null, "e": 8265, "s": 7340, "text": "<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:paddingBottom=\"@dimen/activity_vertical_margin\"\n android:paddingLeft=\"@dimen/activity_horizontal_margin\"\n android:paddingRight=\"@dimen/activity_horizontal_margin\"\n android:paddingTop=\"@dimen/activity_vertical_margin\"\n tools:context=\".MainActivity\" >\n \n <TextView\n android:id=\"@+id/text_id\"\n android:layout_width=\"300dp\"\n android:layout_height=\"200dp\"\n android:capitalize=\"characters\"\n android:text=\"hello_world\"\n android:textColor=\"@android:color/holo_blue_dark\"\n android:textColorHighlight=\"@android:color/primary_text_dark\"\n android:layout_centerVertical=\"true\"\n android:layout_alignParentEnd=\"true\"\n android:textSize=\"50dp\"/>\n\n</RelativeLayout>" }, { "code": null, "e": 8352, "s": 8265, "text": "Following will be the content of res/values/strings.xml to define two new constants −" }, { "code": null, "e": 8457, "s": 8352, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n <string name=\"app_name\">demo</string>\n</resources>" }, { "code": null, "e": 8516, "s": 8457, "text": "Following is the default content of AndroidManifest.xml −" }, { "code": null, "e": 9253, "s": 8516, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.demo\" >\n \n \n <application\n android:allowBackup=\"true\"\n android:icon=\"@drawable/ic_launcher\"\n android:label=\"@string/app_name\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\" >\n \n <activity\n android:name=\"com.example.demo.MainActivity\"\n android:label=\"@string/app_name\" >\n \n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n \n </activity>\n \n </application>\n</manifest>" }, { "code": null, "e": 9635, "s": 9253, "text": "Let's try to run your demo application. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project's activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −" }, { "code": null, "e": 9987, "s": 9635, "text": "I will recommend to try above example with different attributes of TextView in Layout XML file as well at programming time to have different look and feel of the TextView. Try to make it editable, change to font color, font family, width, textSize etc and see the result. You can also try above example with multiple TextView controls in one activity." }, { "code": null, "e": 10022, "s": 9987, "text": "\n 46 Lectures \n 7.5 hours \n" }, { "code": null, "e": 10034, "s": 10022, "text": " Aditya Dua" }, { "code": null, "e": 10069, "s": 10034, "text": "\n 32 Lectures \n 3.5 hours \n" }, { "code": null, "e": 10083, "s": 10069, "text": " Sharad Kumar" }, { "code": null, "e": 10115, "s": 10083, "text": "\n 9 Lectures \n 1 hours \n" }, { "code": null, "e": 10132, "s": 10115, "text": " Abhilash Nelson" }, { "code": null, "e": 10167, "s": 10132, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 10184, "s": 10167, "text": " Abhilash Nelson" }, { "code": null, "e": 10219, "s": 10184, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 10236, "s": 10219, "text": " Abhilash Nelson" }, { "code": null, "e": 10269, "s": 10236, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 10286, "s": 10269, "text": " Abhilash Nelson" }, { "code": null, "e": 10293, "s": 10286, "text": " Print" }, { "code": null, "e": 10304, "s": 10293, "text": " Add Notes" } ]
Sum of first n even numbers
22 Jun, 2022 Given a number n. The problem is to find the sum of first n even numbers.Examples: Input : n = 4 Output : 20 Sum of first 4 even numbers = (2 + 4 + 6 + 8) = 20 Input : n = 20 Output : 420 Naive Approach: Iterate through the first n even numbers and add them. C++ Java Python3 C# PHP Javascript // C++ implementation to find sum of// first n even numbers#include <bits/stdc++.h> using namespace std; // function to find sum of// first n even numbersint evenSum(int n){ int curr = 2, sum = 0; // sum of first n even numbers for (int i = 1; i <= n; i++) { sum += curr; // next even number curr += 2; } // required sum return sum;} // Driver program to test aboveint main(){ int n = 20; cout << "Sum of first " << n << " Even numbers is: " << evenSum(n); return 0;} // Java implementation to find sum// of first n even numbersimport java.util.*;import java.lang.*; public class GfG{ // function to find sum of // first n even numbers static int evenSum(int n) { int curr = 2, sum = 0; // sum of first n even numbers for (int i = 1; i <= n; i++) { sum += curr; // next even number curr += 2; } // required sum return sum; } // driver function public static void main(String argc[]) { int n = 20; System.out.println("Sum of first " + n + " Even numbers is: " + evenSum(n)); } } // This code is contributed by Prerna Saini # Python3 implementation to find sum of# first n even numbers # function to find sum of# first n even numbersdef evensum(n): curr = 2 sum = 0 i = 1 # sum of first n even numbers while i <= n: sum += curr # next even number curr += 2 i = i + 1 return sum # Driver Coden = 20print("sum of first ", n, "even number is: ", evensum(n)) # This article is contributed by rishabh_jain // C# implementation to find sum// of first n even numbersusing System; public class GfG { // function to find sum of // first n even numbers static int evenSum(int n) { int curr = 2, sum = 0; // sum of first n even numbers for (int i = 1; i <= n; i++) { sum += curr; // next even number curr += 2; } // required sum return sum; } // driver function public static void Main() { int n = 20; Console.WriteLine("Sum of first " + n + " Even numbers is: " + evenSum(n)); }} // This code is contributed by vt-m. <?php// PHP implementation to find sum of// first n even numbers // function to find sum of// first n even numbersfunction evenSum($n){ $curr = 2; $sum = 0; // sum of first n even numbers for ($i = 1; $i <= $n; $i++) { $sum += $curr; // next even number $curr += 2; } // required sum return $sum;} // Driver program to test above $n = 20; echo "Sum of first ".$n." Even numbers is: ".evenSum($n); // this code is contributed by mits?> <script> // JavaScript implementation to find sum of// first n even numbers // function to find sum of // first n even numbers function evenSum(n) { let curr = 2, sum = 0; // sum of first n even numbers for (let i = 1; i <= n; i++) { sum += curr; // next even number curr += 2; } // required sum return sum; } // Driver program to test above let n = 20; document.write("Sum of first " + n + " Even numbers is: " + evenSum(n)); //This code is contributed by Surbhi Tyagi </script> Sum of first 20 Even numbers is: 420 Time Complexity: O(n) Auxiliary Space: O(1) Efficient Approach: By applying the formula given below. Sum of first n even numbers = n * (n + 1). Proof: Sum of first n terms of an A.P.(Arithmetic Progression) = (n/2) * [2*a + (n-1)*d].....(i) where, a is the first term of the series and d is the difference between the adjacent terms of the series. Here, a = 2, d = 2, applying these values to eq.(i), we get Sum = (n/2) * [2*2 + (n-1)*2] = (n/2) * [4 + 2*n - 2] = (n/2) * (2*n + 2) = n * (n + 1) C++ Java Python3 C# PHP Javascript // C++ implementation to find sum of// first n even numbers#include <bits/stdc++.h>using namespace std; // function to find sum of// first n even numbersint evenSum(int n){ // required sum return (n * (n + 1));} // Driver program to test aboveint main(){ int n = 20; cout << "Sum of first " << n << " Even numbers is: " << evenSum(n); return 0;} // Java implementation to find sum// of first n even numbersimport java.util.*;import java.lang.*; public class GfG{ // function to find sum of // first n even numbers static int evenSum(int n) { // required sum return (n * (n + 1)); } // driver function public static void main(String argc[]) { int n = 20; System.out.println("Sum of first " + n + " Even numbers is: " + evenSum(n)); }} // This code is contributed by Prerna Saini # Python3 implementation to find# sum of first n even numbers # function to find sum of# first n even numbersdef evensum(n): return n * (n + 1) # Driver Coden = 20print("sum of first", n, "even number is: ", evensum(n)) # This article is contributed by rishabh_jain // C# implementation to find sum// of first n even numbers'using System; public class GfG { // function to find sum of // first n even numbers static int evenSum(int n) { // required sum return (n * (n + 1)); } // driver function public static void Main() { int n = 20; Console.WriteLine("Sum of first " + n + " Even numbers is: " + evenSum(n)); }} // This code is contributed by vt_m <?php// PHP implementation// to find sum of// first n even numbers // function to find sum of// first n even numbersfunction evenSum($n){ // required sum return ($n * ($n + 1));} // Driver Code$n = 20;echo "Sum of first " , $n, " Even numbers is: " , evenSum($n); // This code is contributed// by akt_mit?> <script>// Javascript implementation// to find sum of// first n even numbers // function to find sum of// first n even numbersfunction evenSum(n){ // required sum return (n * (n + 1));} // Driver Codelet n = 20;document.write("Sum of first " + n + " Even numbers is: " , evenSum(n)); // This code is contributed// by gfgking</script> Sum of first 20 Even numbers is: 420 Time Complexity: O(1). Space Complexity: O(1) since using constant variables Another method: In this method, we have to calculate the Nth term, The formula for finding Nth term ,Tn = a+(n-1)d, here, a= first term, d= common difference, n= number of term And then we have to apply the formula for finding the sum, the formula is, Sn=(N/2) * (a + Tn), here a= first term, Tn= last term, n= number of term This formula also can be applied for the sum of odd numbers, but the series must have a same common difference. C++ // C++ implementation to find sum of// first n even numbers#include <bits/stdc++.h>using namespace std; // function to find sum of// first n even numbersint evenSum(int n){ int tn = 2+(n-1)*2; //find Nth Term //calculate a+(n-1)d //first term is = 2 //common difference is 2 //first term and common difference is same all time // required sum return (n/2) * (2 + tn); //calculate (N/2) * (a + Tn)} // Driver program to test aboveint main(){ int n = 20; cout << "Sum of first " << n << " Even numbers is: " << evenSum(n); return 0;}//Contributed by SoumikMondal Sum of first 20 Even numbers is: 420 Time Complexity: O(1). Space Complexity: O(1) since using constant variables jit_t Mithun Kumar surbhityagi15 gfgking SoumikMondal kumargaurav97520 series Mathematical Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Jun, 2022" }, { "code": null, "e": 137, "s": 52, "text": "Given a number n. The problem is to find the sum of first n even numbers.Examples: " }, { "code": null, "e": 244, "s": 137, "text": "Input : n = 4\nOutput : 20\nSum of first 4 even numbers\n= (2 + 4 + 6 + 8) = 20 \n\nInput : n = 20\nOutput : 420" }, { "code": null, "e": 318, "s": 246, "text": "Naive Approach: Iterate through the first n even numbers and add them. " }, { "code": null, "e": 322, "s": 318, "text": "C++" }, { "code": null, "e": 327, "s": 322, "text": "Java" }, { "code": null, "e": 335, "s": 327, "text": "Python3" }, { "code": null, "e": 338, "s": 335, "text": "C#" }, { "code": null, "e": 342, "s": 338, "text": "PHP" }, { "code": null, "e": 353, "s": 342, "text": "Javascript" }, { "code": "// C++ implementation to find sum of// first n even numbers#include <bits/stdc++.h> using namespace std; // function to find sum of// first n even numbersint evenSum(int n){ int curr = 2, sum = 0; // sum of first n even numbers for (int i = 1; i <= n; i++) { sum += curr; // next even number curr += 2; } // required sum return sum;} // Driver program to test aboveint main(){ int n = 20; cout << \"Sum of first \" << n << \" Even numbers is: \" << evenSum(n); return 0;}", "e": 880, "s": 353, "text": null }, { "code": "// Java implementation to find sum// of first n even numbersimport java.util.*;import java.lang.*; public class GfG{ // function to find sum of // first n even numbers static int evenSum(int n) { int curr = 2, sum = 0; // sum of first n even numbers for (int i = 1; i <= n; i++) { sum += curr; // next even number curr += 2; } // required sum return sum; } // driver function public static void main(String argc[]) { int n = 20; System.out.println(\"Sum of first \" + n + \" Even numbers is: \" + evenSum(n)); } } // This code is contributed by Prerna Saini", "e": 1617, "s": 880, "text": null }, { "code": "# Python3 implementation to find sum of# first n even numbers # function to find sum of# first n even numbersdef evensum(n): curr = 2 sum = 0 i = 1 # sum of first n even numbers while i <= n: sum += curr # next even number curr += 2 i = i + 1 return sum # Driver Coden = 20print(\"sum of first \", n, \"even number is: \", evensum(n)) # This article is contributed by rishabh_jain", "e": 2063, "s": 1617, "text": null }, { "code": "// C# implementation to find sum// of first n even numbersusing System; public class GfG { // function to find sum of // first n even numbers static int evenSum(int n) { int curr = 2, sum = 0; // sum of first n even numbers for (int i = 1; i <= n; i++) { sum += curr; // next even number curr += 2; } // required sum return sum; } // driver function public static void Main() { int n = 20; Console.WriteLine(\"Sum of first \" + n + \" Even numbers is: \" + evenSum(n)); }} // This code is contributed by vt-m.", "e": 2707, "s": 2063, "text": null }, { "code": "<?php// PHP implementation to find sum of// first n even numbers // function to find sum of// first n even numbersfunction evenSum($n){ $curr = 2; $sum = 0; // sum of first n even numbers for ($i = 1; $i <= $n; $i++) { $sum += $curr; // next even number $curr += 2; } // required sum return $sum;} // Driver program to test above $n = 20; echo \"Sum of first \".$n.\" Even numbers is: \".evenSum($n); // this code is contributed by mits?>", "e": 3198, "s": 2707, "text": null }, { "code": "<script> // JavaScript implementation to find sum of// first n even numbers // function to find sum of // first n even numbers function evenSum(n) { let curr = 2, sum = 0; // sum of first n even numbers for (let i = 1; i <= n; i++) { sum += curr; // next even number curr += 2; } // required sum return sum; } // Driver program to test above let n = 20; document.write(\"Sum of first \" + n + \" Even numbers is: \" + evenSum(n)); //This code is contributed by Surbhi Tyagi </script>", "e": 3805, "s": 3198, "text": null }, { "code": null, "e": 3842, "s": 3805, "text": "Sum of first 20 Even numbers is: 420" }, { "code": null, "e": 3864, "s": 3842, "text": "Time Complexity: O(n)" }, { "code": null, "e": 3886, "s": 3864, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 3945, "s": 3886, "text": "Efficient Approach: By applying the formula given below. " }, { "code": null, "e": 4005, "s": 3945, "text": " Sum of first n even numbers = n * (n + 1)." }, { "code": null, "e": 4014, "s": 4005, "text": "Proof: " }, { "code": null, "e": 4372, "s": 4014, "text": "Sum of first n terms of an A.P.(Arithmetic Progression)\n= (n/2) * [2*a + (n-1)*d].....(i)\nwhere, a is the first term of the series and d is\nthe difference between the adjacent terms of the series.\n\nHere, a = 2, d = 2, applying these values to eq.(i), we get\nSum = (n/2) * [2*2 + (n-1)*2]\n = (n/2) * [4 + 2*n - 2]\n = (n/2) * (2*n + 2)\n = n * (n + 1)" }, { "code": null, "e": 4378, "s": 4374, "text": "C++" }, { "code": null, "e": 4383, "s": 4378, "text": "Java" }, { "code": null, "e": 4391, "s": 4383, "text": "Python3" }, { "code": null, "e": 4394, "s": 4391, "text": "C#" }, { "code": null, "e": 4398, "s": 4394, "text": "PHP" }, { "code": null, "e": 4409, "s": 4398, "text": "Javascript" }, { "code": "// C++ implementation to find sum of// first n even numbers#include <bits/stdc++.h>using namespace std; // function to find sum of// first n even numbersint evenSum(int n){ // required sum return (n * (n + 1));} // Driver program to test aboveint main(){ int n = 20; cout << \"Sum of first \" << n << \" Even numbers is: \" << evenSum(n); return 0;}", "e": 4778, "s": 4409, "text": null }, { "code": "// Java implementation to find sum// of first n even numbersimport java.util.*;import java.lang.*; public class GfG{ // function to find sum of // first n even numbers static int evenSum(int n) { // required sum return (n * (n + 1)); } // driver function public static void main(String argc[]) { int n = 20; System.out.println(\"Sum of first \" + n + \" Even numbers is: \" + evenSum(n)); }} // This code is contributed by Prerna Saini", "e": 5328, "s": 4778, "text": null }, { "code": "# Python3 implementation to find# sum of first n even numbers # function to find sum of# first n even numbersdef evensum(n): return n * (n + 1) # Driver Coden = 20print(\"sum of first\", n, \"even number is: \", evensum(n)) # This article is contributed by rishabh_jain", "e": 5607, "s": 5328, "text": null }, { "code": "// C# implementation to find sum// of first n even numbers'using System; public class GfG { // function to find sum of // first n even numbers static int evenSum(int n) { // required sum return (n * (n + 1)); } // driver function public static void Main() { int n = 20; Console.WriteLine(\"Sum of first \" + n + \" Even numbers is: \" + evenSum(n)); }} // This code is contributed by vt_m", "e": 6074, "s": 5607, "text": null }, { "code": "<?php// PHP implementation// to find sum of// first n even numbers // function to find sum of// first n even numbersfunction evenSum($n){ // required sum return ($n * ($n + 1));} // Driver Code$n = 20;echo \"Sum of first \" , $n, \" Even numbers is: \" , evenSum($n); // This code is contributed// by akt_mit?>", "e": 6403, "s": 6074, "text": null }, { "code": "<script>// Javascript implementation// to find sum of// first n even numbers // function to find sum of// first n even numbersfunction evenSum(n){ // required sum return (n * (n + 1));} // Driver Codelet n = 20;document.write(\"Sum of first \" + n + \" Even numbers is: \" , evenSum(n)); // This code is contributed// by gfgking</script>", "e": 6760, "s": 6403, "text": null }, { "code": null, "e": 6797, "s": 6760, "text": "Sum of first 20 Even numbers is: 420" }, { "code": null, "e": 6820, "s": 6797, "text": "Time Complexity: O(1)." }, { "code": null, "e": 6874, "s": 6820, "text": "Space Complexity: O(1) since using constant variables" }, { "code": null, "e": 6890, "s": 6874, "text": "Another method:" }, { "code": null, "e": 6941, "s": 6890, "text": "In this method, we have to calculate the Nth term," }, { "code": null, "e": 7051, "s": 6941, "text": "The formula for finding Nth term ,Tn = a+(n-1)d, here, a= first term, d= common difference, n= number of term" }, { "code": null, "e": 7111, "s": 7051, "text": "And then we have to apply the formula for finding the sum, " }, { "code": null, "e": 7201, "s": 7111, "text": "the formula is, Sn=(N/2) * (a + Tn), here a= first term, Tn= last term, n= number of term" }, { "code": null, "e": 7313, "s": 7201, "text": "This formula also can be applied for the sum of odd numbers, but the series must have a same common difference." }, { "code": null, "e": 7317, "s": 7313, "text": "C++" }, { "code": "// C++ implementation to find sum of// first n even numbers#include <bits/stdc++.h>using namespace std; // function to find sum of// first n even numbersint evenSum(int n){ int tn = 2+(n-1)*2; //find Nth Term //calculate a+(n-1)d //first term is = 2 //common difference is 2 //first term and common difference is same all time // required sum return (n/2) * (2 + tn); //calculate (N/2) * (a + Tn)} // Driver program to test aboveint main(){ int n = 20; cout << \"Sum of first \" << n << \" Even numbers is: \" << evenSum(n); return 0;}//Contributed by SoumikMondal", "e": 7927, "s": 7317, "text": null }, { "code": null, "e": 7964, "s": 7927, "text": "Sum of first 20 Even numbers is: 420" }, { "code": null, "e": 7987, "s": 7964, "text": "Time Complexity: O(1)." }, { "code": null, "e": 8042, "s": 7987, "text": "Space Complexity: O(1) since using constant variables " }, { "code": null, "e": 8048, "s": 8042, "text": "jit_t" }, { "code": null, "e": 8061, "s": 8048, "text": "Mithun Kumar" }, { "code": null, "e": 8075, "s": 8061, "text": "surbhityagi15" }, { "code": null, "e": 8083, "s": 8075, "text": "gfgking" }, { "code": null, "e": 8096, "s": 8083, "text": "SoumikMondal" }, { "code": null, "e": 8113, "s": 8096, "text": "kumargaurav97520" }, { "code": null, "e": 8120, "s": 8113, "text": "series" }, { "code": null, "e": 8133, "s": 8120, "text": "Mathematical" }, { "code": null, "e": 8146, "s": 8133, "text": "Mathematical" }, { "code": null, "e": 8153, "s": 8146, "text": "series" } ]
Plot multiple plots in Matplotlib
03 Jan, 2021 Prerequisites: Matplotlib In Matplotlib, we can draw multiple graphs in a single plot in two ways. One is by using subplot() function and other by superimposition of second graph on the first i.e, all graphs will appear on the same plot. We will look into both the ways one by one. A subplot () function is a wrapper function which allows the programmer to plot more than one graph in a single figure by just calling it once. Syntax: matplotlib.pyplot.subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None, **fig_kw) Parameters: nrows, ncols: These gives the number of rows and columns respectively. Also, it must be noted that both these parameters are optional and the default value is 1.sharex, sharey: These parameters specify about the properties that are shared among a and y axis.Possible values for them can be, row, col, none or default value which is False.squeeze: This parameter is a boolean value specified, which asks the programmer whether to squeeze out, meaning remove the extra dimension from the array. It has a default value False.subplot_kw: This parameters allow us to add keywords to each subplot and its default value is None.gridspec_kw: This allows us to add grids on each subplot and has a default value of None.**fig_kw: This allows us to pass any other additional keyword argument to the function call and has a default value of None. nrows, ncols: These gives the number of rows and columns respectively. Also, it must be noted that both these parameters are optional and the default value is 1. sharex, sharey: These parameters specify about the properties that are shared among a and y axis.Possible values for them can be, row, col, none or default value which is False. squeeze: This parameter is a boolean value specified, which asks the programmer whether to squeeze out, meaning remove the extra dimension from the array. It has a default value False. subplot_kw: This parameters allow us to add keywords to each subplot and its default value is None. gridspec_kw: This allows us to add grids on each subplot and has a default value of None. **fig_kw: This allows us to pass any other additional keyword argument to the function call and has a default value of None. Example : Python3 # importing librariesimport matplotlib.pyplot as pltimport numpy as npimport math # Get the angles from 0 to 2 pie (360 degree) in narray objectX = np.arange(0, math.pi*2, 0.05) # Using built-in trigonometric function we can directly plot# the given cosine wave for the given anglesY1 = np.sin(X)Y2 = np.cos(X)Y3 = np.tan(X)Y4 = np.tanh(X) # Initialise the subplot function using number of rows and columnsfigure, axis = plt.subplots(2, 2) # For Sine Functionaxis[0, 0].plot(X, Y1)axis[0, 0].set_title("Sine Function") # For Cosine Functionaxis[0, 1].plot(X, Y2)axis[0, 1].set_title("Cosine Function") # For Tangent Functionaxis[1, 0].plot(X, Y3)axis[1, 0].set_title("Tangent Function") # For Tanh Functionaxis[1, 1].plot(X, Y4)axis[1, 1].set_title("Tanh Function") # Combine all the operations and displayplt.show() Output Multiple plots using subplot() function In Matplotlib, there is another function very similar to subplot which is subplot2grid (). It is same almost same as subplot function but provides more flexibility to arrange the plot objects according to the need of the programmer. This function is written as follows: Syntax: matplotlib.pyplot.subplot2grid(shape, loc, rowspan=1, colspan=1, fig=None, **kwargs) Parameter: shapeThis parameter is a sequence of two integer values which tells the shape of the grid for which we need to place the axes. The first entry is for row, whereas the second entry is for column.locLike shape parameter, even Ioc is a sequence of 2 integer values, where first entry remains for the row and the second is for column to place axis within grid.rowspanThis parameter takes integer value and the number which indicates the number of rows for the axis to span to or increase towards right side.colspanThis parameter takes integer value and the number which indicates the number of columns for the axis to span to or increase the length downwards.figThis is an optional parameter and takes Figure to place axis in. It defaults to current figure.**kwargsThis allows us to pass any other additional keyword argument to the function call and has a default value of None. shapeThis parameter is a sequence of two integer values which tells the shape of the grid for which we need to place the axes. The first entry is for row, whereas the second entry is for column. locLike shape parameter, even Ioc is a sequence of 2 integer values, where first entry remains for the row and the second is for column to place axis within grid. rowspanThis parameter takes integer value and the number which indicates the number of rows for the axis to span to or increase towards right side. colspanThis parameter takes integer value and the number which indicates the number of columns for the axis to span to or increase the length downwards. figThis is an optional parameter and takes Figure to place axis in. It defaults to current figure. **kwargsThis allows us to pass any other additional keyword argument to the function call and has a default value of None. Example : Python3 # Importing librariesimport matplotlib.pyplot as pltimport numpy as npimport math # Placing the plots in the planeplot1 = plt.subplot2grid((3, 3), (0, 0), colspan=2)plot2 = plt.subplot2grid((3, 3), (0, 2), rowspan=3, colspan=2)plot3 = plt.subplot2grid((3, 3), (1, 0), rowspan=2) # Using Numpy to create an array xx = np.arange(1, 10) # Plot for square rootplot2.plot(x, x**0.5)plot2.set_title('Square Root') # Plot for exponentplot1.plot(x, np.exp(x))plot1.set_title('Exponent') # Plot for Squareplot3.plot(x, x*x)plot.set_title('Square') # Packing all the plots and displaying themplt.tight_layout()plt.show() Output Multiple Plots using subplot2grid() function We have now learnt about plotting multiple graphs using subplot and subplot2grid function of Matplotlib library. As mentioned earlier, we will now have a look at plotting multiple curves by superimposing them. In this method we do not use any special function instead we directly plot the curves one above other and try to set the scale. Example : Python3 # Importing librariesimport matplotlib.pyplot as pltimport numpy as npimport math # Using Numpy to create an array XX = np.arange(0, math.pi*2, 0.05) # Assign variables to the y axis part of the curvey = np.sin(X)z = np.cos(X) # Plotting both the curves simultaneouslyplt.plot(X, y, color='r', label='sin')plt.plot(X, z, color='g', label='cos') # Naming the x-axis, y-axis and the whole graphplt.xlabel("Angle")plt.ylabel("Magnitude")plt.title("Sine and Cosine functions") # Adding legend, which helps us recognize the curve according to it's colorplt.legend() # To load the display windowplt.show() Output sine and cosine function curve in one graph Picked Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n03 Jan, 2021" }, { "code": null, "e": 80, "s": 54, "text": "Prerequisites: Matplotlib" }, { "code": null, "e": 336, "s": 80, "text": "In Matplotlib, we can draw multiple graphs in a single plot in two ways. One is by using subplot() function and other by superimposition of second graph on the first i.e, all graphs will appear on the same plot. We will look into both the ways one by one." }, { "code": null, "e": 480, "s": 336, "text": "A subplot () function is a wrapper function which allows the programmer to plot more than one graph in a single figure by just calling it once." }, { "code": null, "e": 620, "s": 480, "text": "Syntax: matplotlib.pyplot.subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None, **fig_kw)" }, { "code": null, "e": 632, "s": 620, "text": "Parameters:" }, { "code": null, "e": 1470, "s": 632, "text": "nrows, ncols: These gives the number of rows and columns respectively. Also, it must be noted that both these parameters are optional and the default value is 1.sharex, sharey: These parameters specify about the properties that are shared among a and y axis.Possible values for them can be, row, col, none or default value which is False.squeeze: This parameter is a boolean value specified, which asks the programmer whether to squeeze out, meaning remove the extra dimension from the array. It has a default value False.subplot_kw: This parameters allow us to add keywords to each subplot and its default value is None.gridspec_kw: This allows us to add grids on each subplot and has a default value of None.**fig_kw: This allows us to pass any other additional keyword argument to the function call and has a default value of None." }, { "code": null, "e": 1634, "s": 1470, "text": "nrows, ncols: These gives the number of rows and columns respectively. Also, it must be noted that both these parameters are optional and the default value is 1." }, { "code": null, "e": 1813, "s": 1634, "text": "sharex, sharey: These parameters specify about the properties that are shared among a and y axis.Possible values for them can be, row, col, none or default value which is False." }, { "code": null, "e": 1998, "s": 1813, "text": "squeeze: This parameter is a boolean value specified, which asks the programmer whether to squeeze out, meaning remove the extra dimension from the array. It has a default value False." }, { "code": null, "e": 2098, "s": 1998, "text": "subplot_kw: This parameters allow us to add keywords to each subplot and its default value is None." }, { "code": null, "e": 2188, "s": 2098, "text": "gridspec_kw: This allows us to add grids on each subplot and has a default value of None." }, { "code": null, "e": 2313, "s": 2188, "text": "**fig_kw: This allows us to pass any other additional keyword argument to the function call and has a default value of None." }, { "code": null, "e": 2323, "s": 2313, "text": "Example :" }, { "code": null, "e": 2331, "s": 2323, "text": "Python3" }, { "code": "# importing librariesimport matplotlib.pyplot as pltimport numpy as npimport math # Get the angles from 0 to 2 pie (360 degree) in narray objectX = np.arange(0, math.pi*2, 0.05) # Using built-in trigonometric function we can directly plot# the given cosine wave for the given anglesY1 = np.sin(X)Y2 = np.cos(X)Y3 = np.tan(X)Y4 = np.tanh(X) # Initialise the subplot function using number of rows and columnsfigure, axis = plt.subplots(2, 2) # For Sine Functionaxis[0, 0].plot(X, Y1)axis[0, 0].set_title(\"Sine Function\") # For Cosine Functionaxis[0, 1].plot(X, Y2)axis[0, 1].set_title(\"Cosine Function\") # For Tangent Functionaxis[1, 0].plot(X, Y3)axis[1, 0].set_title(\"Tangent Function\") # For Tanh Functionaxis[1, 1].plot(X, Y4)axis[1, 1].set_title(\"Tanh Function\") # Combine all the operations and displayplt.show()", "e": 3156, "s": 2331, "text": null }, { "code": null, "e": 3163, "s": 3156, "text": "Output" }, { "code": null, "e": 3203, "s": 3163, "text": "Multiple plots using subplot() function" }, { "code": null, "e": 3436, "s": 3203, "text": "In Matplotlib, there is another function very similar to subplot which is subplot2grid (). It is same almost same as subplot function but provides more flexibility to arrange the plot objects according to the need of the programmer." }, { "code": null, "e": 3473, "s": 3436, "text": "This function is written as follows:" }, { "code": null, "e": 3566, "s": 3473, "text": "Syntax: matplotlib.pyplot.subplot2grid(shape, loc, rowspan=1, colspan=1, fig=None, **kwargs)" }, { "code": null, "e": 3577, "s": 3566, "text": "Parameter:" }, { "code": null, "e": 4453, "s": 3577, "text": "shapeThis parameter is a sequence of two integer values which tells the shape of the grid for which we need to place the axes. The first entry is for row, whereas the second entry is for column.locLike shape parameter, even Ioc is a sequence of 2 integer values, where first entry remains for the row and the second is for column to place axis within grid.rowspanThis parameter takes integer value and the number which indicates the number of rows for the axis to span to or increase towards right side.colspanThis parameter takes integer value and the number which indicates the number of columns for the axis to span to or increase the length downwards.figThis is an optional parameter and takes Figure to place axis in. It defaults to current figure.**kwargsThis allows us to pass any other additional keyword argument to the function call and has a default value of None." }, { "code": null, "e": 4648, "s": 4453, "text": "shapeThis parameter is a sequence of two integer values which tells the shape of the grid for which we need to place the axes. The first entry is for row, whereas the second entry is for column." }, { "code": null, "e": 4811, "s": 4648, "text": "locLike shape parameter, even Ioc is a sequence of 2 integer values, where first entry remains for the row and the second is for column to place axis within grid." }, { "code": null, "e": 4959, "s": 4811, "text": "rowspanThis parameter takes integer value and the number which indicates the number of rows for the axis to span to or increase towards right side." }, { "code": null, "e": 5112, "s": 4959, "text": "colspanThis parameter takes integer value and the number which indicates the number of columns for the axis to span to or increase the length downwards." }, { "code": null, "e": 5211, "s": 5112, "text": "figThis is an optional parameter and takes Figure to place axis in. It defaults to current figure." }, { "code": null, "e": 5334, "s": 5211, "text": "**kwargsThis allows us to pass any other additional keyword argument to the function call and has a default value of None." }, { "code": null, "e": 5344, "s": 5334, "text": "Example :" }, { "code": null, "e": 5352, "s": 5344, "text": "Python3" }, { "code": "# Importing librariesimport matplotlib.pyplot as pltimport numpy as npimport math # Placing the plots in the planeplot1 = plt.subplot2grid((3, 3), (0, 0), colspan=2)plot2 = plt.subplot2grid((3, 3), (0, 2), rowspan=3, colspan=2)plot3 = plt.subplot2grid((3, 3), (1, 0), rowspan=2) # Using Numpy to create an array xx = np.arange(1, 10) # Plot for square rootplot2.plot(x, x**0.5)plot2.set_title('Square Root') # Plot for exponentplot1.plot(x, np.exp(x))plot1.set_title('Exponent') # Plot for Squareplot3.plot(x, x*x)plot.set_title('Square') # Packing all the plots and displaying themplt.tight_layout()plt.show()", "e": 5969, "s": 5352, "text": null }, { "code": null, "e": 5976, "s": 5969, "text": "Output" }, { "code": null, "e": 6021, "s": 5976, "text": "Multiple Plots using subplot2grid() function" }, { "code": null, "e": 6359, "s": 6021, "text": "We have now learnt about plotting multiple graphs using subplot and subplot2grid function of Matplotlib library. As mentioned earlier, we will now have a look at plotting multiple curves by superimposing them. In this method we do not use any special function instead we directly plot the curves one above other and try to set the scale." }, { "code": null, "e": 6369, "s": 6359, "text": "Example :" }, { "code": null, "e": 6377, "s": 6369, "text": "Python3" }, { "code": "# Importing librariesimport matplotlib.pyplot as pltimport numpy as npimport math # Using Numpy to create an array XX = np.arange(0, math.pi*2, 0.05) # Assign variables to the y axis part of the curvey = np.sin(X)z = np.cos(X) # Plotting both the curves simultaneouslyplt.plot(X, y, color='r', label='sin')plt.plot(X, z, color='g', label='cos') # Naming the x-axis, y-axis and the whole graphplt.xlabel(\"Angle\")plt.ylabel(\"Magnitude\")plt.title(\"Sine and Cosine functions\") # Adding legend, which helps us recognize the curve according to it's colorplt.legend() # To load the display windowplt.show()", "e": 6983, "s": 6377, "text": null }, { "code": null, "e": 6990, "s": 6983, "text": "Output" }, { "code": null, "e": 7034, "s": 6990, "text": "sine and cosine function curve in one graph" }, { "code": null, "e": 7041, "s": 7034, "text": "Picked" }, { "code": null, "e": 7059, "s": 7041, "text": "Python-matplotlib" }, { "code": null, "e": 7066, "s": 7059, "text": "Python" } ]
Count pairs from two linked lists whose sum is equal to a given value
14 Jun, 2022 Given two linked lists(can be sorted or unsorted) of size n1 and n2 of distinct elements. Given a value x. The problem is to count all pairs from both lists whose sum is equal to the given value x. Note: The pair has an element from each linked list. Examples: Input : list1 = 3->1->5->7 list2 = 8->2->5->3 x = 10 Output : 2 The pairs are: (5, 5) and (7, 3) Input : list1 = 4->3->5->7->11->2->1 list2 = 2->3->4->5->6->8-12 x = 9 Output : 5 Method 1 (Naive Approach): Using two loops pick elements from both the linked lists and check whether the sum of the pair is equal to x or not. C++ Java Python3 C# Javascript // C++ implementation to count pairs from both linked// lists whose sum is equal to a given value#include <bits/stdc++.h>using namespace std; /* A Linked list node */struct Node{ int data; struct Node* next;}; // function to insert a node at the// beginning of the linked listvoid push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list to the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} // function to count all pairs from both the linked lists// whose sum is equal to a given valueint countPairs(struct Node* head1, struct Node* head2, int x){ int count = 0; struct Node *p1, *p2; // traverse the 1st linked list for (p1 = head1; p1 != NULL; p1 = p1->next) // for each node of 1st list // traverse the 2nd list for (p2 = head2; p2 != NULL; p2 = p2->next) // if sum of pair is equal to 'x' // increment count if ((p1->data + p2->data) == x) count++; // required count of pairs return count;} // Driver program to test aboveint main(){ struct Node* head1 = NULL; struct Node* head2 = NULL; // create linked list1 3->1->5->7 push(&head1, 7); push(&head1, 5); push(&head1, 1); push(&head1, 3); // create linked list2 8->2->5->3 push(&head2, 3); push(&head2, 5); push(&head2, 2); push(&head2, 8); int x = 10; cout << "Count = " << countPairs(head1, head2, x); return 0;} // Java implementation to count pairs from both linked// lists whose sum is equal to a given value // Note : here we use java.util.LinkedList for// linked list implementation import java.util.Arrays;import java.util.Iterator;import java.util.LinkedList; class GFG{ // method to count all pairs from both the linked lists // whose sum is equal to a given value static int countPairs(LinkedList<Integer> head1, LinkedList<Integer> head2, int x) { int count = 0; // traverse the 1st linked list Iterator<Integer> itr1 = head1.iterator(); while(itr1.hasNext()) { // for each node of 1st list // traverse the 2nd list Iterator<Integer> itr2 = head2.iterator(); Integer t = itr1.next(); while(itr2.hasNext()) { // if sum of pair is equal to 'x' // increment count if ((t + itr2.next()) == x) count++; } } // required count of pairs return count; } // Driver method public static void main(String[] args) { Integer arr1[] = {3, 1, 5, 7}; Integer arr2[] = {8, 2, 5, 3}; // create linked list1 3->1->5->7 LinkedList<Integer> head1 = new LinkedList<>(Arrays.asList(arr1)); // create linked list2 8->2->5->3 LinkedList<Integer> head2 = new LinkedList<>(Arrays.asList(arr2)); int x = 10; System.out.println("Count = " + countPairs(head1, head2, x)); } } # Python3 implementation to count pairs from both linked# lists whose sum is equal to a given value # A Linked list nodeclass Node: def __init__(self,data): self.data = data self.next = None # function to insert a node at the# beginning of the linked list def push(head_ref,new_data): new_node=Node(new_data) #new_node.data = new_data new_node.next = head_ref head_ref = new_node return head_ref # function to count all pairs from both the linked lists# whose sum is equal to a given valuedef countPairs(head1, head2, x): count = 0 #struct Node p1, p2 # traverse the 1st linked list p1 = head1 while(p1 != None): # for each node of 1st list # traverse the 2nd list p2 = head2 while(p2 != None): # if sum of pair is equal to 'x' # increment count if ((p1.data + p2.data) == x): count+=1 p2 = p2.next p1 = p1.next # required count of pairs return count # Driver program to test aboveif __name__=='__main__': head1 = None head2 = None # create linked list1 3.1.5.7 head1=push(head1, 7) head1=push(head1, 5) head1=push(head1, 1) head1=push(head1, 3) # create linked list2 8.2.5.3 head2=push(head2, 3) head2=push(head2, 5) head2=push(head2, 2) head2=push(head2, 8) x = 10 print("Count = ",countPairs(head1, head2, x)) # This code is contributed by AbhiThakur // C# implementation to count pairs from both linked// lists whose sum is equal to a given valueusing System;using System.Collections.Generic; // Note : here we use using System.Collections.Generic for// linked list implementationclass GFG{ // method to count all pairs from both the linked lists // whose sum is equal to a given value static int countPairs(List<int> head1, List<int> head2, int x) { int count = 0; // traverse the 1st linked list foreach(int itr1 in head1) { // for each node of 1st list // traverse the 2nd list int t = itr1; foreach(int itr2 in head2) { // if sum of pair is equal to 'x' // increment count if ((t + itr2) == x) count++; } } // required count of pairs return count; } // Driver code public static void Main(String []args) { int []arr1 = {3, 1, 5, 7}; int []arr2 = {8, 2, 5, 3}; // create linked list1 3->1->5->7 List<int> head1 = new List<int>(arr1); // create linked list2 8->2->5->3 List<int> head2 = new List<int>(arr2); int x = 10; Console.WriteLine("Count = " + countPairs(head1, head2, x)); }} // This code is contributed by 29AjayKumar <script>// javascript implementation to count pairs from both linked// lists whose sum is equal to a given value // Note : here we use java.util.LinkedList for// linked list implementation // method to count all pairs from both the linked lists // whose sum is equal to a given value function countPairs( head1, head2 , x) { var count = 0; // traverse the 1st linked list for (var itr1 of head1) { // for each node of 1st list // traverse the 2nd list for (var itr2 of head2) { // if sum of pair is equal to 'x' // increment count if ((itr1 + itr2) == x) count++; } } // required count of pairs return count; } // Driver method var arr1 = [ 3, 1, 5, 7 ]; var arr2 = [ 8, 2, 5, 3 ]; // create linked list1 3->1->5->7 var head1 = (arr1); // create linked list2 8->2->5->3 var head2 = arr2; var x = 10; document.write("Count = " + countPairs(head1, head2, x)); // This code is contributed by Rajput-Ji</script> Count = 2 Time Complexity: O(n1*n2) Auxiliary Space: O(1) Method 2 (Sorting): Sort the 1st linked list in ascending order and the 2nd linked list in descending order using merge sort technique. Now traverse both the lists from left to right in the following way: Algorithm: countPairs(list1, list2, x) Initialize count = 0 while list1 != NULL and list2 != NULL if (list1->data + list2->data) == x list1 = list1->next list2 = list2->next count++ else if (list1->data + list2->data) > x list2 = list2->next else list1 = list1->next return count For simplicity, the implementation given below assumes that list1 is sorted in ascending order and list2 is sorted in descending order. C++ Java // C++ implementation to count pairs from both linked// lists whose sum is equal to a given value#include <bits/stdc++.h>using namespace std; /* A Linked list node */struct Node{ int data; struct Node* next;}; // function to insert a node at the// beginning of the linked listvoid push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list to the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} // function to count all pairs from both the linked// lists whose sum is equal to a given valueint countPairs(struct Node* head1, struct Node* head2, int x){ int count = 0; // sort head1 in ascending order and // head2 in descending order // sort (head1), sort (head2) // For simplicity both lists are considered to be // sorted in the respective orders // traverse both the lists from left to right while (head1 != NULL && head2 != NULL) { // if this sum is equal to 'x', then move both // the lists to next nodes and increment 'count' if ((head1->data + head2->data) == x) { head1 = head1->next; head2 = head2->next; count++; } // if this sum is greater than x, then // move head2 to next node else if ((head1->data + head2->data) > x) head2 = head2->next; // else move head1 to next node else head1 = head1->next; } // required count of pairs return count;} // Driver program to test aboveint main(){ struct Node* head1 = NULL; struct Node* head2 = NULL; // create linked list1 1->3->5->7 // assumed to be in ascending order push(&head1, 7); push(&head1, 5); push(&head1, 3); push(&head1, 1); // create linked list2 8->5->3->2 // assumed to be in descending order push(&head2, 2); push(&head2, 3); push(&head2, 5); push(&head2, 8); int x = 10; cout << "Count = " << countPairs(head1, head2, x); return 0;} // Java implementation to count pairs from both linked// lists whose sum is equal to a given value // Note : here we use java.util.LinkedList for// linked list implementation import java.util.Arrays;import java.util.Collections;import java.util.Iterator;import java.util.LinkedList; class GFG{ // method to count all pairs from both the linked lists // whose sum is equal to a given value static int countPairs(LinkedList<Integer> head1, LinkedList<Integer> head2, int x) { int count = 0; // sort head1 in ascending order and // head2 in descending order Collections.sort(head1); Collections.sort(head2,Collections.reverseOrder()); // traverse both the lists from left to right Iterator<Integer> itr1 = head1.iterator(); Iterator<Integer> itr2 = head2.iterator(); Integer num1 = itr1.hasNext() ? itr1.next() : null; Integer num2 = itr2.hasNext() ? itr2.next() : null; while(num1 != null && num2 != null) { // if this sum is equal to 'x', then move both // the lists to next nodes and increment 'count' if ((num1 + num2) == x) { num1 = itr1.hasNext() ? itr1.next() : null; num2 = itr2.hasNext() ? itr2.next() : null; count++; } // if this sum is greater than x, then // move itr2 to next node else if ((num1 + num2) > x) num2 = itr2.hasNext() ? itr2.next() : null; // else move itr1 to next node else num1 = itr1.hasNext() ? itr1.next() : null; } // required count of pairs return count; } // Driver method public static void main(String[] args) { Integer arr1[] = {3, 1, 5, 7}; Integer arr2[] = {8, 2, 5, 3}; // create linked list1 3->1->5->7 LinkedList<Integer> head1 = new LinkedList<>(Arrays.asList(arr1)); // create linked list2 8->2->5->3 LinkedList<Integer> head2 = new LinkedList<>(Arrays.asList(arr2)); int x = 10; System.out.println("Count = " + countPairs(head1, head2, x)); } } Count = 2 Time Complexity: O(n1*logn1) + O(n2*logn2) Auxiliary Space: O(1) Sorting will change the order of nodes. If order is important, then copy of the linked lists can be created and used. Method 3 (Hashing): Hash table is implemented using unordered_set in C++. We store all first linked list elements in hash table. For elements of second linked list, we subtract every element from x and check the result in hash table. If result is present, we increment the count. C++ Java Python3 C# Javascript // C++ implementation to count pairs from both linked // lists whose sum is equal to a given value#include <bits/stdc++.h>using namespace std; /* A Linked list node */struct Node{ int data; struct Node* next;}; // function to insert a node at the// beginning of the linked listvoid push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list to the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} // function to count all pairs from both the linked// lists whose sum is equal to a given valueint countPairs(struct Node* head1, struct Node* head2, int x){ int count = 0; unordered_set<int> us; // insert all the elements of 1st list // in the hash table(unordered_set 'us') while (head1 != NULL) { us.insert(head1->data); // move to next node head1 = head1->next; } // for each element of 2nd list while (head2 != NULL) { // find (x - head2->data) in 'us' if (us.find(x - head2->data) != us.end()) count++; // move to next node head2 = head2->next; } // required count of pairs return count;} // Driver program to test aboveint main(){ struct Node* head1 = NULL; struct Node* head2 = NULL; // create linked list1 3->1->5->7 push(&head1, 7); push(&head1, 5); push(&head1, 1); push(&head1, 3); // create linked list2 8->2->5->3 push(&head2, 3); push(&head2, 5); push(&head2, 2); push(&head2, 8); int x = 10; cout << "Count = " << countPairs(head1, head2, x); return 0;} // Java implementation to count pairs from both linked// lists whose sum is equal to a given value // Note : here we use java.util.LinkedList for// linked list implementation import java.util.Arrays;import java.util.HashSet;import java.util.Iterator;import java.util.LinkedList; class GFG{ // method to count all pairs from both the linked lists // whose sum is equal to a given value static int countPairs(LinkedList<Integer> head1, LinkedList<Integer> head2, int x) { int count = 0; HashSet<Integer> us = new HashSet<Integer>(); // insert all the elements of 1st list // in the hash table(unordered_set 'us') Iterator<Integer> itr1 = head1.iterator(); while (itr1.hasNext()) { us.add(itr1.next()); } Iterator<Integer> itr2 = head2.iterator(); // for each element of 2nd list while (itr2.hasNext()) { // find (x - head2->data) in 'us' if (!(us.add(x - itr2.next()))) count++; } // required count of pairs return count; } // Driver method public static void main(String[] args) { Integer arr1[] = {3, 1, 5, 7}; Integer arr2[] = {8, 2, 5, 3}; // create linked list1 3->1->5->7 LinkedList<Integer> head1 = new LinkedList<>(Arrays.asList(arr1)); // create linked list2 8->2->5->3 LinkedList<Integer> head2 = new LinkedList<>(Arrays.asList(arr2)); int x = 10; System.out.println("Count = " + countPairs(head1, head2, x)); } } # Python3 implementation to count pairs from both linked # lists whose sum is equal to a given value ''' A Linked list node '''class Node: def __init__(self): self.data = 0 self.next = None # function to add a node at the# beginning of the linked listdef push(head_ref, new_data): ''' allocate node ''' new_node =Node() ''' put in the data ''' new_node.data = new_data; ''' link the old list to 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 count all pairs from both the linked# lists whose sum is equal to a given valuedef countPairs(head1, head2, x): count = 0; us = set() # add all the elements of 1st list # in the hash table(unordered_set 'us') while (head1 != None): us.add(head1.data); # move to next node head1 = head1.next; # for each element of 2nd list while (head2 != None): # find (x - head2.data) in 'us' if ((x - head2.data) in us): count += 1 # move to next node head2 = head2.next; # required count of pairs return count; # Driver program to test aboveif __name__=='__main__': head1 = None; head2 = None; # create linked list1 3.1.5.7 head1 = push(head1, 7); head1 = push(head1, 5); head1 = push(head1, 1); head1 = push(head1, 3); # create linked list2 8.2.5.3 head2 = push(head2, 3); head2 = push(head2, 5); head2 = push(head2, 2); head2 = push(head2, 8); x = 10; print("Count =", countPairs(head1, head2, x)); # This code is contributed by rutvik_56 // C# implementation to count pairs from both linked// lists whose sum is equal to a given value // Note : here we use java.util.LinkedList for// linked list implementationusing System;using System.Collections.Generic; class GFG{ // method to count all pairs from both the linked lists // whose sum is equal to a given value static int countPairs(List<int> head1, List<int> head2, int x) { int count = 0; HashSet<int> us = new HashSet<int>(); // insert all the elements of 1st list // in the hash table(unordered_set 'us') foreach(int itr1 in head1) { us.Add(itr1); } // for each element of 2nd list foreach(int itr2 in head2) { // find (x - head2->data) in 'us' if (!(us.Contains(x - itr2))) count++; } // required count of pairs return count; } // Driver code public static void Main(String[] args) { int []arr1 = {3, 1, 5, 7}; int []arr2 = {8, 2, 5, 3}; // create linked list1 3->1->5->7 List<int> head1 = new List<int>(arr1); // create linked list2 8->2->5->3 List<int> head2 = new List<int>(arr2); int x = 10; Console.WriteLine("Count = " + countPairs(head1, head2, x)); }} // This code is contributed by Princi Singh <script> // JavaScript implementation to count pairs// from both linked lists whose sum is equal// to a given value // A Linked list nodeclass Node{ constructor(new_data) { this.data = new_data; this.next = null; }}; // Function to count all pairs from both the linked// lists whose sum is equal to a given valuefunction countPairs(head1, head2, x){ let count = 0; let us = new Set(); // Insert all the elements of 1st list // in the hash table(unordered_set 'us') while (head1 != null) { us.add(head1.data); // Move to next node head1 = head1.next; } // For each element of 2nd list while (head2 != null) { // Find (x - head2.data) in 'us' if (us.has(x - head2.data)) count++; // Move to next node head2 = head2.next; } // Required count of pairs return count;} // Driver codelet head1 = null;let head2 = null; // Create linked list1 3.1.5.7head1 = new Node(3)head1.next = new Node(1)head1.next.next = new Node(5)head1.next.next.next = new Node(7) // Create linked list2 8.2.5.3head2 = new Node(8)head2.next = new Node(2)head2.next.next = new Node(5)head2.next.next.next = new Node(3) let x = 10; document.write("Count = " + countPairs(head1, head2, x)); // This code is contributed by Potta Lokesh </script> Count = 2 Time Complexity: O(n1 + n2) Auxiliary Space: O(n1), hash table should be created of the array having smaller size so as to reduce the space complexity.This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Swanitha KVN 29AjayKumar princi singh abhaysingh290895 rutvik_56 lokeshpotta20 Rajput-Ji adityadixit7054 Hash Linked List Sorting Linked List Hash Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) What is Hashing | A Complete Tutorial Internal Working of HashMap in Java Count pairs with given sum Longest Consecutive Subsequence Linked List | Set 1 (Introduction) Linked List | Set 2 (Inserting a node) Reverse a linked list Stack Data Structure (Introduction and Program) LinkedList in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n14 Jun, 2022" }, { "code": null, "e": 250, "s": 52, "text": "Given two linked lists(can be sorted or unsorted) of size n1 and n2 of distinct elements. Given a value x. The problem is to count all pairs from both lists whose sum is equal to the given value x." }, { "code": null, "e": 303, "s": 250, "text": "Note: The pair has an element from each linked list." }, { "code": null, "e": 314, "s": 303, "text": "Examples: " }, { "code": null, "e": 535, "s": 314, "text": "Input : list1 = 3->1->5->7\n list2 = 8->2->5->3\n x = 10\nOutput : 2\nThe pairs are:\n(5, 5) and (7, 3)\n\nInput : list1 = 4->3->5->7->11->2->1\n list2 = 2->3->4->5->6->8-12\n x = 9 \nOutput : 5" }, { "code": null, "e": 679, "s": 535, "text": "Method 1 (Naive Approach): Using two loops pick elements from both the linked lists and check whether the sum of the pair is equal to x or not." }, { "code": null, "e": 683, "s": 679, "text": "C++" }, { "code": null, "e": 688, "s": 683, "text": "Java" }, { "code": null, "e": 696, "s": 688, "text": "Python3" }, { "code": null, "e": 699, "s": 696, "text": "C#" }, { "code": null, "e": 710, "s": 699, "text": "Javascript" }, { "code": "// C++ implementation to count pairs from both linked// lists whose sum is equal to a given value#include <bits/stdc++.h>using namespace std; /* A Linked list node */struct Node{ int data; struct Node* next;}; // function to insert a node at the// beginning of the linked listvoid push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list to the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} // function to count all pairs from both the linked lists// whose sum is equal to a given valueint countPairs(struct Node* head1, struct Node* head2, int x){ int count = 0; struct Node *p1, *p2; // traverse the 1st linked list for (p1 = head1; p1 != NULL; p1 = p1->next) // for each node of 1st list // traverse the 2nd list for (p2 = head2; p2 != NULL; p2 = p2->next) // if sum of pair is equal to 'x' // increment count if ((p1->data + p2->data) == x) count++; // required count of pairs return count;} // Driver program to test aboveint main(){ struct Node* head1 = NULL; struct Node* head2 = NULL; // create linked list1 3->1->5->7 push(&head1, 7); push(&head1, 5); push(&head1, 1); push(&head1, 3); // create linked list2 8->2->5->3 push(&head2, 3); push(&head2, 5); push(&head2, 2); push(&head2, 8); int x = 10; cout << \"Count = \" << countPairs(head1, head2, x); return 0;}", "e": 2423, "s": 710, "text": null }, { "code": "// Java implementation to count pairs from both linked// lists whose sum is equal to a given value // Note : here we use java.util.LinkedList for// linked list implementation import java.util.Arrays;import java.util.Iterator;import java.util.LinkedList; class GFG{ // method to count all pairs from both the linked lists // whose sum is equal to a given value static int countPairs(LinkedList<Integer> head1, LinkedList<Integer> head2, int x) { int count = 0; // traverse the 1st linked list Iterator<Integer> itr1 = head1.iterator(); while(itr1.hasNext()) { // for each node of 1st list // traverse the 2nd list Iterator<Integer> itr2 = head2.iterator(); Integer t = itr1.next(); while(itr2.hasNext()) { // if sum of pair is equal to 'x' // increment count if ((t + itr2.next()) == x) count++; } } // required count of pairs return count; } // Driver method public static void main(String[] args) { Integer arr1[] = {3, 1, 5, 7}; Integer arr2[] = {8, 2, 5, 3}; // create linked list1 3->1->5->7 LinkedList<Integer> head1 = new LinkedList<>(Arrays.asList(arr1)); // create linked list2 8->2->5->3 LinkedList<Integer> head2 = new LinkedList<>(Arrays.asList(arr2)); int x = 10; System.out.println(\"Count = \" + countPairs(head1, head2, x)); } }", "e": 4031, "s": 2423, "text": null }, { "code": "# Python3 implementation to count pairs from both linked# lists whose sum is equal to a given value # A Linked list nodeclass Node: def __init__(self,data): self.data = data self.next = None # function to insert a node at the# beginning of the linked list def push(head_ref,new_data): new_node=Node(new_data) #new_node.data = new_data new_node.next = head_ref head_ref = new_node return head_ref # function to count all pairs from both the linked lists# whose sum is equal to a given valuedef countPairs(head1, head2, x): count = 0 #struct Node p1, p2 # traverse the 1st linked list p1 = head1 while(p1 != None): # for each node of 1st list # traverse the 2nd list p2 = head2 while(p2 != None): # if sum of pair is equal to 'x' # increment count if ((p1.data + p2.data) == x): count+=1 p2 = p2.next p1 = p1.next # required count of pairs return count # Driver program to test aboveif __name__=='__main__': head1 = None head2 = None # create linked list1 3.1.5.7 head1=push(head1, 7) head1=push(head1, 5) head1=push(head1, 1) head1=push(head1, 3) # create linked list2 8.2.5.3 head2=push(head2, 3) head2=push(head2, 5) head2=push(head2, 2) head2=push(head2, 8) x = 10 print(\"Count = \",countPairs(head1, head2, x)) # This code is contributed by AbhiThakur", "e": 5530, "s": 4031, "text": null }, { "code": "// C# implementation to count pairs from both linked// lists whose sum is equal to a given valueusing System;using System.Collections.Generic; // Note : here we use using System.Collections.Generic for// linked list implementationclass GFG{ // method to count all pairs from both the linked lists // whose sum is equal to a given value static int countPairs(List<int> head1, List<int> head2, int x) { int count = 0; // traverse the 1st linked list foreach(int itr1 in head1) { // for each node of 1st list // traverse the 2nd list int t = itr1; foreach(int itr2 in head2) { // if sum of pair is equal to 'x' // increment count if ((t + itr2) == x) count++; } } // required count of pairs return count; } // Driver code public static void Main(String []args) { int []arr1 = {3, 1, 5, 7}; int []arr2 = {8, 2, 5, 3}; // create linked list1 3->1->5->7 List<int> head1 = new List<int>(arr1); // create linked list2 8->2->5->3 List<int> head2 = new List<int>(arr2); int x = 10; Console.WriteLine(\"Count = \" + countPairs(head1, head2, x)); }} // This code is contributed by 29AjayKumar", "e": 6964, "s": 5530, "text": null }, { "code": "<script>// javascript implementation to count pairs from both linked// lists whose sum is equal to a given value // Note : here we use java.util.LinkedList for// linked list implementation // method to count all pairs from both the linked lists // whose sum is equal to a given value function countPairs( head1, head2 , x) { var count = 0; // traverse the 1st linked list for (var itr1 of head1) { // for each node of 1st list // traverse the 2nd list for (var itr2 of head2) { // if sum of pair is equal to 'x' // increment count if ((itr1 + itr2) == x) count++; } } // required count of pairs return count; } // Driver method var arr1 = [ 3, 1, 5, 7 ]; var arr2 = [ 8, 2, 5, 3 ]; // create linked list1 3->1->5->7 var head1 = (arr1); // create linked list2 8->2->5->3 var head2 = arr2; var x = 10; document.write(\"Count = \" + countPairs(head1, head2, x)); // This code is contributed by Rajput-Ji</script>", "e": 8128, "s": 6964, "text": null }, { "code": null, "e": 8138, "s": 8128, "text": "Count = 2" }, { "code": null, "e": 8391, "s": 8138, "text": "Time Complexity: O(n1*n2) Auxiliary Space: O(1) Method 2 (Sorting): Sort the 1st linked list in ascending order and the 2nd linked list in descending order using merge sort technique. Now traverse both the lists from left to right in the following way:" }, { "code": null, "e": 8403, "s": 8391, "text": "Algorithm: " }, { "code": null, "e": 8741, "s": 8403, "text": "countPairs(list1, list2, x)\n Initialize count = 0\n while list1 != NULL and list2 != NULL\n if (list1->data + list2->data) == x\n list1 = list1->next \n list2 = list2->next\n count++\n else if (list1->data + list2->data) > x\n list2 = list2->next\n else\n list1 = list1->next\n\n return count " }, { "code": null, "e": 8877, "s": 8741, "text": "For simplicity, the implementation given below assumes that list1 is sorted in ascending order and list2 is sorted in descending order." }, { "code": null, "e": 8881, "s": 8877, "text": "C++" }, { "code": null, "e": 8886, "s": 8881, "text": "Java" }, { "code": "// C++ implementation to count pairs from both linked// lists whose sum is equal to a given value#include <bits/stdc++.h>using namespace std; /* A Linked list node */struct Node{ int data; struct Node* next;}; // function to insert a node at the// beginning of the linked listvoid push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list to the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} // function to count all pairs from both the linked// lists whose sum is equal to a given valueint countPairs(struct Node* head1, struct Node* head2, int x){ int count = 0; // sort head1 in ascending order and // head2 in descending order // sort (head1), sort (head2) // For simplicity both lists are considered to be // sorted in the respective orders // traverse both the lists from left to right while (head1 != NULL && head2 != NULL) { // if this sum is equal to 'x', then move both // the lists to next nodes and increment 'count' if ((head1->data + head2->data) == x) { head1 = head1->next; head2 = head2->next; count++; } // if this sum is greater than x, then // move head2 to next node else if ((head1->data + head2->data) > x) head2 = head2->next; // else move head1 to next node else head1 = head1->next; } // required count of pairs return count;} // Driver program to test aboveint main(){ struct Node* head1 = NULL; struct Node* head2 = NULL; // create linked list1 1->3->5->7 // assumed to be in ascending order push(&head1, 7); push(&head1, 5); push(&head1, 3); push(&head1, 1); // create linked list2 8->5->3->2 // assumed to be in descending order push(&head2, 2); push(&head2, 3); push(&head2, 5); push(&head2, 8); int x = 10; cout << \"Count = \" << countPairs(head1, head2, x); return 0;}", "e": 11177, "s": 8886, "text": null }, { "code": "// Java implementation to count pairs from both linked// lists whose sum is equal to a given value // Note : here we use java.util.LinkedList for// linked list implementation import java.util.Arrays;import java.util.Collections;import java.util.Iterator;import java.util.LinkedList; class GFG{ // method to count all pairs from both the linked lists // whose sum is equal to a given value static int countPairs(LinkedList<Integer> head1, LinkedList<Integer> head2, int x) { int count = 0; // sort head1 in ascending order and // head2 in descending order Collections.sort(head1); Collections.sort(head2,Collections.reverseOrder()); // traverse both the lists from left to right Iterator<Integer> itr1 = head1.iterator(); Iterator<Integer> itr2 = head2.iterator(); Integer num1 = itr1.hasNext() ? itr1.next() : null; Integer num2 = itr2.hasNext() ? itr2.next() : null; while(num1 != null && num2 != null) { // if this sum is equal to 'x', then move both // the lists to next nodes and increment 'count' if ((num1 + num2) == x) { num1 = itr1.hasNext() ? itr1.next() : null; num2 = itr2.hasNext() ? itr2.next() : null; count++; } // if this sum is greater than x, then // move itr2 to next node else if ((num1 + num2) > x) num2 = itr2.hasNext() ? itr2.next() : null; // else move itr1 to next node else num1 = itr1.hasNext() ? itr1.next() : null; } // required count of pairs return count; } // Driver method public static void main(String[] args) { Integer arr1[] = {3, 1, 5, 7}; Integer arr2[] = {8, 2, 5, 3}; // create linked list1 3->1->5->7 LinkedList<Integer> head1 = new LinkedList<>(Arrays.asList(arr1)); // create linked list2 8->2->5->3 LinkedList<Integer> head2 = new LinkedList<>(Arrays.asList(arr2)); int x = 10; System.out.println(\"Count = \" + countPairs(head1, head2, x)); } }", "e": 13538, "s": 11177, "text": null }, { "code": null, "e": 13548, "s": 13538, "text": "Count = 2" }, { "code": null, "e": 13731, "s": 13548, "text": "Time Complexity: O(n1*logn1) + O(n2*logn2) Auxiliary Space: O(1) Sorting will change the order of nodes. If order is important, then copy of the linked lists can be created and used." }, { "code": null, "e": 14011, "s": 13731, "text": "Method 3 (Hashing): Hash table is implemented using unordered_set in C++. We store all first linked list elements in hash table. For elements of second linked list, we subtract every element from x and check the result in hash table. If result is present, we increment the count." }, { "code": null, "e": 14015, "s": 14011, "text": "C++" }, { "code": null, "e": 14020, "s": 14015, "text": "Java" }, { "code": null, "e": 14028, "s": 14020, "text": "Python3" }, { "code": null, "e": 14031, "s": 14028, "text": "C#" }, { "code": null, "e": 14042, "s": 14031, "text": "Javascript" }, { "code": "// C++ implementation to count pairs from both linked // lists whose sum is equal to a given value#include <bits/stdc++.h>using namespace std; /* A Linked list node */struct Node{ int data; struct Node* next;}; // function to insert a node at the// beginning of the linked listvoid push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list to the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} // function to count all pairs from both the linked// lists whose sum is equal to a given valueint countPairs(struct Node* head1, struct Node* head2, int x){ int count = 0; unordered_set<int> us; // insert all the elements of 1st list // in the hash table(unordered_set 'us') while (head1 != NULL) { us.insert(head1->data); // move to next node head1 = head1->next; } // for each element of 2nd list while (head2 != NULL) { // find (x - head2->data) in 'us' if (us.find(x - head2->data) != us.end()) count++; // move to next node head2 = head2->next; } // required count of pairs return count;} // Driver program to test aboveint main(){ struct Node* head1 = NULL; struct Node* head2 = NULL; // create linked list1 3->1->5->7 push(&head1, 7); push(&head1, 5); push(&head1, 1); push(&head1, 3); // create linked list2 8->2->5->3 push(&head2, 3); push(&head2, 5); push(&head2, 2); push(&head2, 8); int x = 10; cout << \"Count = \" << countPairs(head1, head2, x); return 0;}", "e": 15915, "s": 14042, "text": null }, { "code": "// Java implementation to count pairs from both linked// lists whose sum is equal to a given value // Note : here we use java.util.LinkedList for// linked list implementation import java.util.Arrays;import java.util.HashSet;import java.util.Iterator;import java.util.LinkedList; class GFG{ // method to count all pairs from both the linked lists // whose sum is equal to a given value static int countPairs(LinkedList<Integer> head1, LinkedList<Integer> head2, int x) { int count = 0; HashSet<Integer> us = new HashSet<Integer>(); // insert all the elements of 1st list // in the hash table(unordered_set 'us') Iterator<Integer> itr1 = head1.iterator(); while (itr1.hasNext()) { us.add(itr1.next()); } Iterator<Integer> itr2 = head2.iterator(); // for each element of 2nd list while (itr2.hasNext()) { // find (x - head2->data) in 'us' if (!(us.add(x - itr2.next()))) count++; } // required count of pairs return count; } // Driver method public static void main(String[] args) { Integer arr1[] = {3, 1, 5, 7}; Integer arr2[] = {8, 2, 5, 3}; // create linked list1 3->1->5->7 LinkedList<Integer> head1 = new LinkedList<>(Arrays.asList(arr1)); // create linked list2 8->2->5->3 LinkedList<Integer> head2 = new LinkedList<>(Arrays.asList(arr2)); int x = 10; System.out.println(\"Count = \" + countPairs(head1, head2, x)); } }", "e": 17593, "s": 15915, "text": null }, { "code": "# Python3 implementation to count pairs from both linked # lists whose sum is equal to a given value ''' A Linked list node '''class Node: def __init__(self): self.data = 0 self.next = None # function to add a node at the# beginning of the linked listdef push(head_ref, new_data): ''' allocate node ''' new_node =Node() ''' put in the data ''' new_node.data = new_data; ''' link the old list to 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 count all pairs from both the linked# lists whose sum is equal to a given valuedef countPairs(head1, head2, x): count = 0; us = set() # add all the elements of 1st list # in the hash table(unordered_set 'us') while (head1 != None): us.add(head1.data); # move to next node head1 = head1.next; # for each element of 2nd list while (head2 != None): # find (x - head2.data) in 'us' if ((x - head2.data) in us): count += 1 # move to next node head2 = head2.next; # required count of pairs return count; # Driver program to test aboveif __name__=='__main__': head1 = None; head2 = None; # create linked list1 3.1.5.7 head1 = push(head1, 7); head1 = push(head1, 5); head1 = push(head1, 1); head1 = push(head1, 3); # create linked list2 8.2.5.3 head2 = push(head2, 3); head2 = push(head2, 5); head2 = push(head2, 2); head2 = push(head2, 8); x = 10; print(\"Count =\", countPairs(head1, head2, x)); # This code is contributed by rutvik_56", "e": 19337, "s": 17593, "text": null }, { "code": "// C# implementation to count pairs from both linked// lists whose sum is equal to a given value // Note : here we use java.util.LinkedList for// linked list implementationusing System;using System.Collections.Generic; class GFG{ // method to count all pairs from both the linked lists // whose sum is equal to a given value static int countPairs(List<int> head1, List<int> head2, int x) { int count = 0; HashSet<int> us = new HashSet<int>(); // insert all the elements of 1st list // in the hash table(unordered_set 'us') foreach(int itr1 in head1) { us.Add(itr1); } // for each element of 2nd list foreach(int itr2 in head2) { // find (x - head2->data) in 'us' if (!(us.Contains(x - itr2))) count++; } // required count of pairs return count; } // Driver code public static void Main(String[] args) { int []arr1 = {3, 1, 5, 7}; int []arr2 = {8, 2, 5, 3}; // create linked list1 3->1->5->7 List<int> head1 = new List<int>(arr1); // create linked list2 8->2->5->3 List<int> head2 = new List<int>(arr2); int x = 10; Console.WriteLine(\"Count = \" + countPairs(head1, head2, x)); }} // This code is contributed by Princi Singh", "e": 20785, "s": 19337, "text": null }, { "code": "<script> // JavaScript implementation to count pairs// from both linked lists whose sum is equal// to a given value // A Linked list nodeclass Node{ constructor(new_data) { this.data = new_data; this.next = null; }}; // Function to count all pairs from both the linked// lists whose sum is equal to a given valuefunction countPairs(head1, head2, x){ let count = 0; let us = new Set(); // Insert all the elements of 1st list // in the hash table(unordered_set 'us') while (head1 != null) { us.add(head1.data); // Move to next node head1 = head1.next; } // For each element of 2nd list while (head2 != null) { // Find (x - head2.data) in 'us' if (us.has(x - head2.data)) count++; // Move to next node head2 = head2.next; } // Required count of pairs return count;} // Driver codelet head1 = null;let head2 = null; // Create linked list1 3.1.5.7head1 = new Node(3)head1.next = new Node(1)head1.next.next = new Node(5)head1.next.next.next = new Node(7) // Create linked list2 8.2.5.3head2 = new Node(8)head2.next = new Node(2)head2.next.next = new Node(5)head2.next.next.next = new Node(3) let x = 10; document.write(\"Count = \" + countPairs(head1, head2, x)); // This code is contributed by Potta Lokesh </script>", "e": 22171, "s": 20785, "text": null }, { "code": null, "e": 22181, "s": 22171, "text": "Count = 2" }, { "code": null, "e": 22754, "s": 22181, "text": "Time Complexity: O(n1 + n2) Auxiliary Space: O(n1), hash table should be created of the array having smaller size so as to reduce the space complexity.This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 22767, "s": 22754, "text": "Swanitha KVN" }, { "code": null, "e": 22779, "s": 22767, "text": "29AjayKumar" }, { "code": null, "e": 22792, "s": 22779, "text": "princi singh" }, { "code": null, "e": 22809, "s": 22792, "text": "abhaysingh290895" }, { "code": null, "e": 22819, "s": 22809, "text": "rutvik_56" }, { "code": null, "e": 22833, "s": 22819, "text": "lokeshpotta20" }, { "code": null, "e": 22843, "s": 22833, "text": "Rajput-Ji" }, { "code": null, "e": 22859, "s": 22843, "text": "adityadixit7054" }, { "code": null, "e": 22864, "s": 22859, "text": "Hash" }, { "code": null, "e": 22876, "s": 22864, "text": "Linked List" }, { "code": null, "e": 22884, "s": 22876, "text": "Sorting" }, { "code": null, "e": 22896, "s": 22884, "text": "Linked List" }, { "code": null, "e": 22901, "s": 22896, "text": "Hash" }, { "code": null, "e": 22909, "s": 22901, "text": "Sorting" }, { "code": null, "e": 23007, "s": 22909, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 23092, "s": 23007, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 23130, "s": 23092, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 23166, "s": 23130, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 23193, "s": 23166, "text": "Count pairs with given sum" }, { "code": null, "e": 23225, "s": 23193, "text": "Longest Consecutive Subsequence" }, { "code": null, "e": 23260, "s": 23225, "text": "Linked List | Set 1 (Introduction)" }, { "code": null, "e": 23299, "s": 23260, "text": "Linked List | Set 2 (Inserting a node)" }, { "code": null, "e": 23321, "s": 23299, "text": "Reverse a linked list" }, { "code": null, "e": 23369, "s": 23321, "text": "Stack Data Structure (Introduction and Program)" } ]
Writing to an excel sheet using Python
29 Jul, 2019 Using xlwt module, one can perform multiple operations on spreadsheet. For example, writing or modifying the data can be done in Python. Also, the user might have to go through various sheets and retrieve data based on some criteria or modify some rows and columns and do a lot of work. Let’s see how to create and write to an excel-sheet using Python. # Writing to an excel # sheet using Pythonimport xlwtfrom xlwt import Workbook # Workbook is createdwb = Workbook() # add_sheet is used to create sheet.sheet1 = wb.add_sheet('Sheet 1') sheet1.write(1, 0, 'ISBT DEHRADUN')sheet1.write(2, 0, 'SHASTRADHARA')sheet1.write(3, 0, 'CLEMEN TOWN')sheet1.write(4, 0, 'RAJPUR ROAD')sheet1.write(5, 0, 'CLOCK TOWER')sheet1.write(0, 1, 'ISBT DEHRADUN')sheet1.write(0, 2, 'SHASTRADHARA')sheet1.write(0, 3, 'CLEMEN TOWN')sheet1.write(0, 4, 'RAJPUR ROAD')sheet1.write(0, 5, 'CLOCK TOWER') wb.save('xlwt example.xls') Output : # importing xlwt moduleimport xlwt workbook = xlwt.Workbook() sheet = workbook.add_sheet("Sheet Name") # Specifying stylestyle = xlwt.easyxf('font: bold 1') # Specifying columnsheet.write(0, 0, 'SAMPLE', style)workbook.save("sample.xls") Output : Code #3 : Adding multiple styles to a cell # importing xlwt moduleimport xlwt workbook = xlwt.Workbook() sheet = workbook.add_sheet("Sheet Name") # Applying multiple stylesstyle = xlwt.easyxf('font: bold 1, color red;') # Writing on specified sheetsheet.write(0, 0, 'SAMPLE', style) workbook.save("sample.xls") Output : shubham_singh python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Convert integer to string in Python Python | os.path.join() method Python OOPs Concepts Introduction To PYTHON
[ { "code": null, "e": 53, "s": 25, "text": "\n29 Jul, 2019" }, { "code": null, "e": 340, "s": 53, "text": "Using xlwt module, one can perform multiple operations on spreadsheet. For example, writing or modifying the data can be done in Python. Also, the user might have to go through various sheets and retrieve data based on some criteria or modify some rows and columns and do a lot of work." }, { "code": null, "e": 407, "s": 340, "text": "Let’s see how to create and write to an excel-sheet using Python. " }, { "code": "# Writing to an excel # sheet using Pythonimport xlwtfrom xlwt import Workbook # Workbook is createdwb = Workbook() # add_sheet is used to create sheet.sheet1 = wb.add_sheet('Sheet 1') sheet1.write(1, 0, 'ISBT DEHRADUN')sheet1.write(2, 0, 'SHASTRADHARA')sheet1.write(3, 0, 'CLEMEN TOWN')sheet1.write(4, 0, 'RAJPUR ROAD')sheet1.write(5, 0, 'CLOCK TOWER')sheet1.write(0, 1, 'ISBT DEHRADUN')sheet1.write(0, 2, 'SHASTRADHARA')sheet1.write(0, 3, 'CLEMEN TOWN')sheet1.write(0, 4, 'RAJPUR ROAD')sheet1.write(0, 5, 'CLOCK TOWER') wb.save('xlwt example.xls')", "e": 961, "s": 407, "text": null }, { "code": null, "e": 971, "s": 961, "text": "Output : " }, { "code": "# importing xlwt moduleimport xlwt workbook = xlwt.Workbook() sheet = workbook.add_sheet(\"Sheet Name\") # Specifying stylestyle = xlwt.easyxf('font: bold 1') # Specifying columnsheet.write(0, 0, 'SAMPLE', style)workbook.save(\"sample.xls\")", "e": 1214, "s": 971, "text": null }, { "code": null, "e": 1266, "s": 1214, "text": "Output : Code #3 : Adding multiple styles to a cell" }, { "code": "# importing xlwt moduleimport xlwt workbook = xlwt.Workbook() sheet = workbook.add_sheet(\"Sheet Name\") # Applying multiple stylesstyle = xlwt.easyxf('font: bold 1, color red;') # Writing on specified sheetsheet.write(0, 0, 'SAMPLE', style) workbook.save(\"sample.xls\")", "e": 1540, "s": 1266, "text": null }, { "code": null, "e": 1549, "s": 1540, "text": "Output :" }, { "code": null, "e": 1563, "s": 1549, "text": "shubham_singh" }, { "code": null, "e": 1578, "s": 1563, "text": "python-modules" }, { "code": null, "e": 1585, "s": 1578, "text": "Python" }, { "code": null, "e": 1683, "s": 1585, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1725, "s": 1683, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1747, "s": 1725, "text": "Enumerate() in Python" }, { "code": null, "e": 1773, "s": 1747, "text": "Python String | replace()" }, { "code": null, "e": 1805, "s": 1773, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1834, "s": 1805, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1861, "s": 1834, "text": "Python Classes and Objects" }, { "code": null, "e": 1897, "s": 1861, "text": "Convert integer to string in Python" }, { "code": null, "e": 1928, "s": 1897, "text": "Python | os.path.join() method" }, { "code": null, "e": 1949, "s": 1928, "text": "Python OOPs Concepts" } ]
C# | Remove all objects from the Queue
01 Feb, 2019 Queue represents a first-in, first out collection of object. It is used when you need a first-in, first-out access of items. When you add an item in the list, it is called enqueue, and when you remove an item, it is called deque. Queue. Clear Method is used to remove the objects from the Queue. This method is an O(n) operation, where n is total count of elements. Properties: Enqueue adds an element to the end of the Queue. Dequeue removes the oldest element from the start of the Queue. Peek returns the oldest element that is at the start of the Queue but does not remove it from the Queue. The capacity of a Queue is the number of elements the Queue can hold. As elements are added to a Queue, the capacity is automatically increased as required by reallocating the internal array. Queue accepts null as a valid value for reference types and allows duplicate elements. Syntax : public virtual void Clear(); Below given are some examples to understand the implementation in a better way: Example 1: // C# code to Remove all// objects from the Queueusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a Queue of strings Queue<string> myQueue = new Queue<string>(); // Inserting the elements into the Queue myQueue.Enqueue("1st Element"); myQueue.Enqueue("2nd Element"); myQueue.Enqueue("3rd Element"); myQueue.Enqueue("4th Element"); myQueue.Enqueue("5th Element"); myQueue.Enqueue("6th Element"); // Displaying the count of elements // contained in the Queue before // removing all the elements Console.Write("Total number of elements in the Queue are : "); Console.WriteLine(myQueue.Count); // Removing all elements from Queue myQueue.Clear(); // Displaying the count of elements // contained in the Queue after // removing all the elements Console.Write("Total number of elements in the Queue are : "); Console.WriteLine(myQueue.Count); }} Total number of elements in the Queue are : 6 Total number of elements in the Queue are : 0 Example 2: // C# code to Remove all// objects from the Queueusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a Queue of Integers Queue<int> myQueue = new Queue<int>(); // Inserting the elements into the Queue myQueue.Enqueue(3); myQueue.Enqueue(5); myQueue.Enqueue(7); myQueue.Enqueue(9); myQueue.Enqueue(11); // Displaying the count of elements // contained in the Queue before // removing all the elements Console.Write("Total number of elements in the Queue are : "); Console.WriteLine(myQueue.Count); // Removing all elements from Queue myQueue.Clear(); // Displaying the count of elements // contained in the Queue after // removing all the elements Console.Write("Total number of elements in the Queue are : "); Console.WriteLine(myQueue.Count); }} Total number of elements in the Queue are : 5 Total number of elements in the Queue are : 0 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.queue-1.clear?view=netframework-4.7.2 CSharp-Collections-Namespace CSharp-Generic-Namespace CSharp-Generic-Queue CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Multiple inheritance using interfaces Introduction to .NET Framework C# | Delegates Differences Between .NET Core and .NET Framework C# | Data Types C# | Method Overriding C# | Class and Object C# | Constructors C# | Replace() Method C# | Encapsulation
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Feb, 2019" }, { "code": null, "e": 394, "s": 28, "text": "Queue represents a first-in, first out collection of object. It is used when you need a first-in, first-out access of items. When you add an item in the list, it is called enqueue, and when you remove an item, it is called deque. Queue. Clear Method is used to remove the objects from the Queue. This method is an O(n) operation, where n is total count of elements." }, { "code": null, "e": 406, "s": 394, "text": "Properties:" }, { "code": null, "e": 455, "s": 406, "text": "Enqueue adds an element to the end of the Queue." }, { "code": null, "e": 519, "s": 455, "text": "Dequeue removes the oldest element from the start of the Queue." }, { "code": null, "e": 624, "s": 519, "text": "Peek returns the oldest element that is at the start of the Queue but does not remove it from the Queue." }, { "code": null, "e": 694, "s": 624, "text": "The capacity of a Queue is the number of elements the Queue can hold." }, { "code": null, "e": 816, "s": 694, "text": "As elements are added to a Queue, the capacity is automatically increased as required by reallocating the internal array." }, { "code": null, "e": 903, "s": 816, "text": "Queue accepts null as a valid value for reference types and allows duplicate elements." }, { "code": null, "e": 912, "s": 903, "text": "Syntax :" }, { "code": null, "e": 942, "s": 912, "text": "public virtual void Clear();\n" }, { "code": null, "e": 1022, "s": 942, "text": "Below given are some examples to understand the implementation in a better way:" }, { "code": null, "e": 1033, "s": 1022, "text": "Example 1:" }, { "code": "// C# code to Remove all// objects from the Queueusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a Queue of strings Queue<string> myQueue = new Queue<string>(); // Inserting the elements into the Queue myQueue.Enqueue(\"1st Element\"); myQueue.Enqueue(\"2nd Element\"); myQueue.Enqueue(\"3rd Element\"); myQueue.Enqueue(\"4th Element\"); myQueue.Enqueue(\"5th Element\"); myQueue.Enqueue(\"6th Element\"); // Displaying the count of elements // contained in the Queue before // removing all the elements Console.Write(\"Total number of elements in the Queue are : \"); Console.WriteLine(myQueue.Count); // Removing all elements from Queue myQueue.Clear(); // Displaying the count of elements // contained in the Queue after // removing all the elements Console.Write(\"Total number of elements in the Queue are : \"); Console.WriteLine(myQueue.Count); }}", "e": 2114, "s": 1033, "text": null }, { "code": null, "e": 2207, "s": 2114, "text": "Total number of elements in the Queue are : 6\nTotal number of elements in the Queue are : 0\n" }, { "code": null, "e": 2218, "s": 2207, "text": "Example 2:" }, { "code": "// C# code to Remove all// objects from the Queueusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a Queue of Integers Queue<int> myQueue = new Queue<int>(); // Inserting the elements into the Queue myQueue.Enqueue(3); myQueue.Enqueue(5); myQueue.Enqueue(7); myQueue.Enqueue(9); myQueue.Enqueue(11); // Displaying the count of elements // contained in the Queue before // removing all the elements Console.Write(\"Total number of elements in the Queue are : \"); Console.WriteLine(myQueue.Count); // Removing all elements from Queue myQueue.Clear(); // Displaying the count of elements // contained in the Queue after // removing all the elements Console.Write(\"Total number of elements in the Queue are : \"); Console.WriteLine(myQueue.Count); }}", "e": 3196, "s": 2218, "text": null }, { "code": null, "e": 3289, "s": 3196, "text": "Total number of elements in the Queue are : 5\nTotal number of elements in the Queue are : 0\n" }, { "code": null, "e": 3300, "s": 3289, "text": "Reference:" }, { "code": null, "e": 3409, "s": 3300, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.queue-1.clear?view=netframework-4.7.2" }, { "code": null, "e": 3438, "s": 3409, "text": "CSharp-Collections-Namespace" }, { "code": null, "e": 3463, "s": 3438, "text": "CSharp-Generic-Namespace" }, { "code": null, "e": 3484, "s": 3463, "text": "CSharp-Generic-Queue" }, { "code": null, "e": 3498, "s": 3484, "text": "CSharp-method" }, { "code": null, "e": 3501, "s": 3498, "text": "C#" }, { "code": null, "e": 3599, "s": 3501, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3642, "s": 3599, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 3673, "s": 3642, "text": "Introduction to .NET Framework" }, { "code": null, "e": 3688, "s": 3673, "text": "C# | Delegates" }, { "code": null, "e": 3737, "s": 3688, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 3753, "s": 3737, "text": "C# | Data Types" }, { "code": null, "e": 3776, "s": 3753, "text": "C# | Method Overriding" }, { "code": null, "e": 3798, "s": 3776, "text": "C# | Class and Object" }, { "code": null, "e": 3816, "s": 3798, "text": "C# | Constructors" }, { "code": null, "e": 3838, "s": 3816, "text": "C# | Replace() Method" } ]
Hugging Face: A Step Towards Democratizing NLP | by Anuj Syal | Towards Data Science
Hugging face; no, I am not referring to one of our favorite emoji to express thankfulness, love, or appreciation. In the world of data science, Hugging Face is a startup in the Natural Language Processing (NLP) domain, offering its library of models for use by some of the A-listers including Apple and Bing. For those wondering why the focus of today’s blog is on a startup, let me first take you through what Hugging Face is all about and why it matters for fellow data scientists. Hugging Face, a company that first built a chat app for bored teens provides open-source NLP technologies, and last year, it raised $15 million to build a definitive NLP library. From its chat app to this day, Hugging Face has been able to swiftly develop language processing expertise. The company’s aim is to advance NLP and democratize it for use by everyone. In a bid to make it easier for humans to communicate with machines, technologies such as NLP are crucial. For instance, with NLP, it is possible for computers to read text, hear speech, interpret it, measure sentiment, and even determine which parts of the text or speech are important. As more companies increasingly add NLP technologies for enhanced interactions, it becomes imperative to have ready libraries on which language models can be trained, saving time and cost. This is where companies like Hugging Face come into play. Its BERT models are considered highly effective and you can see them everywhere. Bidirectional Encoder Representations from Transformers or BERT is a technique used in NLP pre-training and is developed by Google. Hugging Face offers models based on Transformers for PyTorch and TensorFlow 2.0. There are thousands of pre-trained models to perform tasks such as text classification, extraction, question answering, and more. With its low compute costs, it is considered a low barrier entry for educators and practitioners. The company also offers inference API to use those models. Hugging Face provides a number of models popular for their effectiveness and seamless implementation. Now that we have a fair idea about Hugging Face and its BERT models, let me give you a brief overview of two of its popular models for language processing. One of the popular models by Hugging Face is the bert-base-uncased model, which is a pre-trained model in the English language that uses raw texts to generate inputs and labels from those texts. It was pre-trained with two objectives: Masked Language Modeling (MLM) and Next Sentence Prediction (NSP). In MLM objective, the model randomly masks 15% of the words in a sentence and then the masked sentence is run through the model to predict the masked words. It allows the model to learn a bidirectional representation of the sentence. In NSP objective, the model concatenates two masked sentences as inputs during pre-training. The model has to predict if two sentences were following each other or not. In this way, it learns an inner representation of the English language which can be leveraged for downstream tasks such as training a standard classifier if the dataset is of labeled sentences. This bert-base-uncased model is intended to be fine-tuned on a downstream task, but it can be used for either masked language modeling or next sentence prediction. You can use this model with a pipeline for masked language modeling: >> from transformers import pipeline>>> unmasker = pipeline('fill-mask', model='bert-base-uncased')>>> unmasker("Hello I'm a [MASK] model.")[{'sequence': "[CLS] hello i'm a fashion model. [SEP]",'score': 0.1073106899857521,'token': 4827,'token_str': 'fashion'},{'sequence': "[CLS] hello i'm a role model. [SEP]",'score': 0.08774490654468536,'token': 2535,'token_str': 'role'},{'sequence': "[CLS] hello i'm a new model. [SEP]",'score': 0.05338378623127937,'token': 2047,'token_str': 'new'},{'sequence': "[CLS] hello i'm a super model. [SEP]",'score': 0.04667217284440994,'token': 3565,'token_str': 'super'},{'sequence': "[CLS] hello i'm a fine model. [SEP]",'score': 0.027095865458250046,'token': 2986,'token_str': 'fine'}] To use this model to get the features of a given text in PyTorch: from transformers import BertTokenizer, BertModeltokenizer = BertTokenizer.from_pretrained('bert-base-uncased')model = BertModel.from_pretrained("bert-base-uncased")text = "Replace me by any text you'd like."encoded_input = tokenizer(text, return_tensors='pt')output = model(**encoded_input) To use this model in TensorFlow: from transformers import BertTokenizer, TFBertModeltokenizer = BertTokenizer.from_pretrained('bert-base-uncased')model = TFBertModel.from_pretrained("bert-base-uncased")text = "Replace me by any text you'd like."encoded_input = tokenizer(text, return_tensors='tf')output = model(encoded_input) Another very popular model by Hugging Face is the xlm-roberta model. This is a multilingual model trained on 100 different languages, including Hindi, Japanese, Welsh, and Hebrew. It is capable of determining the correct language from input ids; all without requiring the use of lang tensors. Trained on 2.5T of filtered CommonCrawl data in different languages, the xlm-robeta model is capable of obtaining state-of-the-art results on many cross-lingual understanding benchmarks. It is also a PyTorch subclass model and you can use it as a regular PyTorch module. You can check the two pre-trained models here; one is the XLM-R using the BERT base architecture and the other is the XLM-R using the BERT large architecture. To use this model for PyTorch 1.0: Load XLM-R (for PyTorch 1.0 or custom models): # Download xlmr.large modelwget https://dl.fbaipublicfiles.com/fairseq/models/xlmr.large.tar.gztar -xzvf xlmr.large.tar.gz# Load the model in fairseqfrom fairseq.models.roberta import XLMRModelxlmr = XLMRModel.from_pretrained('/path/to/xlmr.large', checkpoint_file='model.pt')xlmr.eval() # disable dropout (or leave in train mode to finetune) To apply sentence-piece-model (SPM) encoding to input text: en_tokens = xlmr.encode('Hello world!')assert en_tokens.tolist() == [0, 35378, 8999, 38, 2]xlmr.decode(en_tokens) # 'Hello world!'zh_tokens = xlmr.encode('你好,世界')assert zh_tokens.tolist() == [0, 6, 124084, 4, 3221, 2]xlmr.decode(zh_tokens) # '你好,世界'hi_tokens = xlmr.encode('नमस्ते दुनिया')assert hi_tokens.tolist() == [0, 68700, 97883, 29405, 2]xlmr.decode(hi_tokens) # 'नमस्ते दुनिया'ar_tokens = xlmr.encode('مرحبا بالعالم')assert ar_tokens.tolist() == [0, 665, 193478, 258, 1705, 77796, 2]xlmr.decode(ar_tokens) # 'مرحبا بالعالم'fr_tokens = xlmr.encode('Bonjour le monde')assert fr_tokens.tolist() == [0, 84602, 95, 11146, 2]xlmr.decode(fr_tokens) # 'Bonjour le monde' To extract features from XLM-R: # Extract the last layer's featureslast_layer_features = xlmr.extract_features(zh_tokens)assert last_layer_features.size() == torch.Size([1, 6, 1024])# Extract all layer's features (layer 0 is the embedding layer)all_layers = xlmr.extract_features(zh_tokens, return_all_hiddens=True)assert len(all_layers) == 25assert torch.all(all_layers[-1] == last_layer_features) With companies such as Hugging Face providing their pre-trained language models, it becomes easier for businesses to extract easily decodable information on how well their product is functioning instead of deciphering graphs and reports. At the core of NLP is having the technology to understand the very language or inputs the human world functions upon and democratizing it only makes the process more seamless and effective. If you are interested in similar content do follow me on Twitter and Linkedin
[ { "code": null, "e": 481, "s": 172, "text": "Hugging face; no, I am not referring to one of our favorite emoji to express thankfulness, love, or appreciation. In the world of data science, Hugging Face is a startup in the Natural Language Processing (NLP) domain, offering its library of models for use by some of the A-listers including Apple and Bing." }, { "code": null, "e": 656, "s": 481, "text": "For those wondering why the focus of today’s blog is on a startup, let me first take you through what Hugging Face is all about and why it matters for fellow data scientists." }, { "code": null, "e": 1019, "s": 656, "text": "Hugging Face, a company that first built a chat app for bored teens provides open-source NLP technologies, and last year, it raised $15 million to build a definitive NLP library. From its chat app to this day, Hugging Face has been able to swiftly develop language processing expertise. The company’s aim is to advance NLP and democratize it for use by everyone." }, { "code": null, "e": 1633, "s": 1019, "text": "In a bid to make it easier for humans to communicate with machines, technologies such as NLP are crucial. For instance, with NLP, it is possible for computers to read text, hear speech, interpret it, measure sentiment, and even determine which parts of the text or speech are important. As more companies increasingly add NLP technologies for enhanced interactions, it becomes imperative to have ready libraries on which language models can be trained, saving time and cost. This is where companies like Hugging Face come into play. Its BERT models are considered highly effective and you can see them everywhere." }, { "code": null, "e": 2133, "s": 1633, "text": "Bidirectional Encoder Representations from Transformers or BERT is a technique used in NLP pre-training and is developed by Google. Hugging Face offers models based on Transformers for PyTorch and TensorFlow 2.0. There are thousands of pre-trained models to perform tasks such as text classification, extraction, question answering, and more. With its low compute costs, it is considered a low barrier entry for educators and practitioners. The company also offers inference API to use those models." }, { "code": null, "e": 2391, "s": 2133, "text": "Hugging Face provides a number of models popular for their effectiveness and seamless implementation. Now that we have a fair idea about Hugging Face and its BERT models, let me give you a brief overview of two of its popular models for language processing." }, { "code": null, "e": 2693, "s": 2391, "text": "One of the popular models by Hugging Face is the bert-base-uncased model, which is a pre-trained model in the English language that uses raw texts to generate inputs and labels from those texts. It was pre-trained with two objectives: Masked Language Modeling (MLM) and Next Sentence Prediction (NSP)." }, { "code": null, "e": 2927, "s": 2693, "text": "In MLM objective, the model randomly masks 15% of the words in a sentence and then the masked sentence is run through the model to predict the masked words. It allows the model to learn a bidirectional representation of the sentence." }, { "code": null, "e": 3290, "s": 2927, "text": "In NSP objective, the model concatenates two masked sentences as inputs during pre-training. The model has to predict if two sentences were following each other or not. In this way, it learns an inner representation of the English language which can be leveraged for downstream tasks such as training a standard classifier if the dataset is of labeled sentences." }, { "code": null, "e": 3454, "s": 3290, "text": "This bert-base-uncased model is intended to be fine-tuned on a downstream task, but it can be used for either masked language modeling or next sentence prediction." }, { "code": null, "e": 3523, "s": 3454, "text": "You can use this model with a pipeline for masked language modeling:" }, { "code": null, "e": 4246, "s": 3523, "text": ">> from transformers import pipeline>>> unmasker = pipeline('fill-mask', model='bert-base-uncased')>>> unmasker(\"Hello I'm a [MASK] model.\")[{'sequence': \"[CLS] hello i'm a fashion model. [SEP]\",'score': 0.1073106899857521,'token': 4827,'token_str': 'fashion'},{'sequence': \"[CLS] hello i'm a role model. [SEP]\",'score': 0.08774490654468536,'token': 2535,'token_str': 'role'},{'sequence': \"[CLS] hello i'm a new model. [SEP]\",'score': 0.05338378623127937,'token': 2047,'token_str': 'new'},{'sequence': \"[CLS] hello i'm a super model. [SEP]\",'score': 0.04667217284440994,'token': 3565,'token_str': 'super'},{'sequence': \"[CLS] hello i'm a fine model. [SEP]\",'score': 0.027095865458250046,'token': 2986,'token_str': 'fine'}]" }, { "code": null, "e": 4312, "s": 4246, "text": "To use this model to get the features of a given text in PyTorch:" }, { "code": null, "e": 4604, "s": 4312, "text": "from transformers import BertTokenizer, BertModeltokenizer = BertTokenizer.from_pretrained('bert-base-uncased')model = BertModel.from_pretrained(\"bert-base-uncased\")text = \"Replace me by any text you'd like.\"encoded_input = tokenizer(text, return_tensors='pt')output = model(**encoded_input)" }, { "code": null, "e": 4637, "s": 4604, "text": "To use this model in TensorFlow:" }, { "code": null, "e": 4931, "s": 4637, "text": "from transformers import BertTokenizer, TFBertModeltokenizer = BertTokenizer.from_pretrained('bert-base-uncased')model = TFBertModel.from_pretrained(\"bert-base-uncased\")text = \"Replace me by any text you'd like.\"encoded_input = tokenizer(text, return_tensors='tf')output = model(encoded_input)" }, { "code": null, "e": 5224, "s": 4931, "text": "Another very popular model by Hugging Face is the xlm-roberta model. This is a multilingual model trained on 100 different languages, including Hindi, Japanese, Welsh, and Hebrew. It is capable of determining the correct language from input ids; all without requiring the use of lang tensors." }, { "code": null, "e": 5495, "s": 5224, "text": "Trained on 2.5T of filtered CommonCrawl data in different languages, the xlm-robeta model is capable of obtaining state-of-the-art results on many cross-lingual understanding benchmarks. It is also a PyTorch subclass model and you can use it as a regular PyTorch module." }, { "code": null, "e": 5654, "s": 5495, "text": "You can check the two pre-trained models here; one is the XLM-R using the BERT base architecture and the other is the XLM-R using the BERT large architecture." }, { "code": null, "e": 5689, "s": 5654, "text": "To use this model for PyTorch 1.0:" }, { "code": null, "e": 5736, "s": 5689, "text": "Load XLM-R (for PyTorch 1.0 or custom models):" }, { "code": null, "e": 6080, "s": 5736, "text": "# Download xlmr.large modelwget https://dl.fbaipublicfiles.com/fairseq/models/xlmr.large.tar.gztar -xzvf xlmr.large.tar.gz# Load the model in fairseqfrom fairseq.models.roberta import XLMRModelxlmr = XLMRModel.from_pretrained('/path/to/xlmr.large', checkpoint_file='model.pt')xlmr.eval() # disable dropout (or leave in train mode to finetune)" }, { "code": null, "e": 6140, "s": 6080, "text": "To apply sentence-piece-model (SPM) encoding to input text:" }, { "code": null, "e": 6815, "s": 6140, "text": "en_tokens = xlmr.encode('Hello world!')assert en_tokens.tolist() == [0, 35378, 8999, 38, 2]xlmr.decode(en_tokens) # 'Hello world!'zh_tokens = xlmr.encode('你好,世界')assert zh_tokens.tolist() == [0, 6, 124084, 4, 3221, 2]xlmr.decode(zh_tokens) # '你好,世界'hi_tokens = xlmr.encode('नमस्ते दुनिया')assert hi_tokens.tolist() == [0, 68700, 97883, 29405, 2]xlmr.decode(hi_tokens) # 'नमस्ते दुनिया'ar_tokens = xlmr.encode('مرحبا بالعالم')assert ar_tokens.tolist() == [0, 665, 193478, 258, 1705, 77796, 2]xlmr.decode(ar_tokens) # 'مرحبا بالعالم'fr_tokens = xlmr.encode('Bonjour le monde')assert fr_tokens.tolist() == [0, 84602, 95, 11146, 2]xlmr.decode(fr_tokens) # 'Bonjour le monde'" }, { "code": null, "e": 6847, "s": 6815, "text": "To extract features from XLM-R:" }, { "code": null, "e": 7214, "s": 6847, "text": "# Extract the last layer's featureslast_layer_features = xlmr.extract_features(zh_tokens)assert last_layer_features.size() == torch.Size([1, 6, 1024])# Extract all layer's features (layer 0 is the embedding layer)all_layers = xlmr.extract_features(zh_tokens, return_all_hiddens=True)assert len(all_layers) == 25assert torch.all(all_layers[-1] == last_layer_features)" }, { "code": null, "e": 7642, "s": 7214, "text": "With companies such as Hugging Face providing their pre-trained language models, it becomes easier for businesses to extract easily decodable information on how well their product is functioning instead of deciphering graphs and reports. At the core of NLP is having the technology to understand the very language or inputs the human world functions upon and democratizing it only makes the process more seamless and effective." } ]
Multi Class Text Classification with LSTM using TensorFlow 2.0 | by Susan Li | Towards Data Science
A lot of innovations on NLP have been how to add context into word vectors. One of the common ways of doing it is using Recurrent Neural Networks. The following are the concepts of Recurrent Neural Networks: They make use of sequential information. They have a memory that captures what have been calculated so far, i.e. what I spoke last will impact what I will speak next. RNNs are ideal for text and speech analysis. The most commonly used RNNs are LSTMs. The above is the architecture of Recurrent Neural Networks. “A” is one layer of feed-forward neural network. If we only look at the right side, it does recurrently to pass through the element of each sequence. If we unwrap the left, it will exactly look like the right. Assuming we are solving document classification problem for a news article data set. We input each word, words relate to each other in some ways. We make predictions at the end of the article when we see all the words in that article. RNNs, by passing input from last output, are able to retain information, and able to leverage all information at the end to make predictions. This works well for short sentences, when we deal with a long article, there will be a long term dependency problem. Therefore, we generally do not use vanilla RNNs, and we use Long Short Term Memory instead. LSTM is a type of RNNs that can solve this long term dependency problem. In our document classification for news article example, we have this many-to- one relationship. The input are sequences of words, output is one single class or label. Now we are going to solve a BBC news document classification problem with LSTM using TensorFlow 2.0 & Keras. The data set can be found here. First, we import the libraries and make sure our TensorFlow is the right version. Put the hyperparameters at the top like this to make it easier to change and edit. We will explain how each hyperparameter works when we get there. Define two lists containing articles and labels. In the meantime, we remove stopwords. There are 2,225 news articles in the data, we split them into training set and validation set, according to the parameter we set earlier, 80% for training, 20% for validation. Tokenizer does all the heavy lifting for us. In our articles that it was tokenizing, it will take 5,000 most common words. oov_token is to put a special value in when an unseen word is encountered. This means we want <OOV> to be used for words that are not in the word_index. fit_on_text will go through all the text and create dictionary like this: We can see that “<OOV>” is the most common token in our corpus, followed by “said”, followed by “mr” and so on. After tokenization, the next step is to turn those tokens into lists of sequence. The following is the 11th article in the training data that has been turned into sequences. train_sequences = tokenizer.texts_to_sequences(train_articles)print(train_sequences[10]) When we train neural networks for NLP, we need sequences to be in the same size, that’s why we use padding. If you look up, our max_length is 200, so we use pad_sequences to make all of our articles the same length which is 200. As a result, you will see that the 1st article was 426 in length, it becomes 200, the 2nd article was 192 in length, it becomes 200, and so on. train_padded = pad_sequences(train_sequences, maxlen=max_length, padding=padding_type, truncating=trunc_type)print(len(train_sequences[0]))print(len(train_padded[0]))print(len(train_sequences[1]))print(len(train_padded[1]))print(len(train_sequences[10]))print(len(train_padded[10])) In addition, there is padding_type and truncating_type, there are all post, means for example, for the 11th article, it was 186 in length, we padded to 200, and we padded at the end, that is adding 14 zeros. print(train_padded[10]) And for the 1st article, it was 426 in length, we truncated to 200, and we truncated at the end as well. Then we do the same for the validation sequences. Now we are going to look at the labels. Because our labels are text, so we will tokenize them, when training, labels are expected to be numpy arrays. So we will turn list of labels into numpy arrays like so: label_tokenizer = Tokenizer()label_tokenizer.fit_on_texts(labels)training_label_seq = np.array(label_tokenizer.texts_to_sequences(train_labels))validation_label_seq = np.array(label_tokenizer.texts_to_sequences(validation_labels))print(training_label_seq[0])print(training_label_seq[1])print(training_label_seq[2])print(training_label_seq.shape)print(validation_label_seq[0])print(validation_label_seq[1])print(validation_label_seq[2])print(validation_label_seq.shape) Before training deep neural network, we should explore what our original article and article after padding look like. Running the following code, we explore the 11th article, we can see that some words become “<OOV>”, because they did not make to the top 5,000. reverse_word_index = dict([(value, key) for (key, value) in word_index.items()])def decode_article(text): return ' '.join([reverse_word_index.get(i, '?') for i in text])print(decode_article(train_padded[10]))print('---')print(train_articles[10]) Now its the time to implement LSTM. We build a tf.keras.Sequential model and start with an embedding layer. An embedding layer stores one vector per word. When called, it converts the sequences of word indices into sequences of vectors. After training, words with similar meanings often have the similar vectors. The Bidirectional wrapper is used with a LSTM layer, this propagates the input forwards and backwards through the LSTM layer and then concatenates the outputs. This helps LSTM to learn long term dependencies. We then fit it to a dense neural network to do classification. We use relu in place of tahn function since they are very good alternatives of each other. We add a Dense layer with 6 units and softmax activation. When we have multiple outputs, softmax converts outputs layers into a probability distribution. In our model summary, we have our embeddings, our Bidirectional contains LSTM, followed by two dense layers. The output from Bidirectional is 128, because it doubled what we put in LSTM. We can also stack LSTM layer but I found the results worse. print(set(labels)) We have 5 labels in total, but because we did not one-hot encode labels, we have to use sparse_categorical_crossentropy as loss function, it seems to think 0 is a possible label as well, while the tokenizer object which tokenizes starting with integer 1, instead of integer 0. As a result, the last Dense layer needs outputs for labels 0, 1, 2, 3, 4, 5 although 0 has never been used. If you want the last Dense layer to be 5, you will need to subtract 1 from the training and validation labels. I decided to leave it as it is. I decided to train 10 epochs, and it is plenty of epochs as you will see. model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])num_epochs = 10history = model.fit(train_padded, training_label_seq, epochs=num_epochs, validation_data=(validation_padded, validation_label_seq), verbose=2) def plot_graphs(history, string): plt.plot(history.history[string]) plt.plot(history.history['val_'+string]) plt.xlabel("Epochs") plt.ylabel(string) plt.legend([string, 'val_'+string]) plt.show() plot_graphs(history, "accuracy")plot_graphs(history, "loss") We probably only need 3 or 4 epochs. At the end of the training, we can see that there is a little bit overfitting. In the future posts, we will work on improving the model. Jupyter notebook can be found on Github. Enjoy the rest of the weekend!
[ { "code": null, "e": 379, "s": 171, "text": "A lot of innovations on NLP have been how to add context into word vectors. One of the common ways of doing it is using Recurrent Neural Networks. The following are the concepts of Recurrent Neural Networks:" }, { "code": null, "e": 420, "s": 379, "text": "They make use of sequential information." }, { "code": null, "e": 546, "s": 420, "text": "They have a memory that captures what have been calculated so far, i.e. what I spoke last will impact what I will speak next." }, { "code": null, "e": 591, "s": 546, "text": "RNNs are ideal for text and speech analysis." }, { "code": null, "e": 630, "s": 591, "text": "The most commonly used RNNs are LSTMs." }, { "code": null, "e": 690, "s": 630, "text": "The above is the architecture of Recurrent Neural Networks." }, { "code": null, "e": 739, "s": 690, "text": "“A” is one layer of feed-forward neural network." }, { "code": null, "e": 840, "s": 739, "text": "If we only look at the right side, it does recurrently to pass through the element of each sequence." }, { "code": null, "e": 900, "s": 840, "text": "If we unwrap the left, it will exactly look like the right." }, { "code": null, "e": 985, "s": 900, "text": "Assuming we are solving document classification problem for a news article data set." }, { "code": null, "e": 1046, "s": 985, "text": "We input each word, words relate to each other in some ways." }, { "code": null, "e": 1135, "s": 1046, "text": "We make predictions at the end of the article when we see all the words in that article." }, { "code": null, "e": 1277, "s": 1135, "text": "RNNs, by passing input from last output, are able to retain information, and able to leverage all information at the end to make predictions." }, { "code": null, "e": 1394, "s": 1277, "text": "This works well for short sentences, when we deal with a long article, there will be a long term dependency problem." }, { "code": null, "e": 1559, "s": 1394, "text": "Therefore, we generally do not use vanilla RNNs, and we use Long Short Term Memory instead. LSTM is a type of RNNs that can solve this long term dependency problem." }, { "code": null, "e": 1727, "s": 1559, "text": "In our document classification for news article example, we have this many-to- one relationship. The input are sequences of words, output is one single class or label." }, { "code": null, "e": 1868, "s": 1727, "text": "Now we are going to solve a BBC news document classification problem with LSTM using TensorFlow 2.0 & Keras. The data set can be found here." }, { "code": null, "e": 1950, "s": 1868, "text": "First, we import the libraries and make sure our TensorFlow is the right version." }, { "code": null, "e": 2033, "s": 1950, "text": "Put the hyperparameters at the top like this to make it easier to change and edit." }, { "code": null, "e": 2098, "s": 2033, "text": "We will explain how each hyperparameter works when we get there." }, { "code": null, "e": 2185, "s": 2098, "text": "Define two lists containing articles and labels. In the meantime, we remove stopwords." }, { "code": null, "e": 2361, "s": 2185, "text": "There are 2,225 news articles in the data, we split them into training set and validation set, according to the parameter we set earlier, 80% for training, 20% for validation." }, { "code": null, "e": 2711, "s": 2361, "text": "Tokenizer does all the heavy lifting for us. In our articles that it was tokenizing, it will take 5,000 most common words. oov_token is to put a special value in when an unseen word is encountered. This means we want <OOV> to be used for words that are not in the word_index. fit_on_text will go through all the text and create dictionary like this:" }, { "code": null, "e": 2823, "s": 2711, "text": "We can see that “<OOV>” is the most common token in our corpus, followed by “said”, followed by “mr” and so on." }, { "code": null, "e": 2997, "s": 2823, "text": "After tokenization, the next step is to turn those tokens into lists of sequence. The following is the 11th article in the training data that has been turned into sequences." }, { "code": null, "e": 3086, "s": 2997, "text": "train_sequences = tokenizer.texts_to_sequences(train_articles)print(train_sequences[10])" }, { "code": null, "e": 3459, "s": 3086, "text": "When we train neural networks for NLP, we need sequences to be in the same size, that’s why we use padding. If you look up, our max_length is 200, so we use pad_sequences to make all of our articles the same length which is 200. As a result, you will see that the 1st article was 426 in length, it becomes 200, the 2nd article was 192 in length, it becomes 200, and so on." }, { "code": null, "e": 3742, "s": 3459, "text": "train_padded = pad_sequences(train_sequences, maxlen=max_length, padding=padding_type, truncating=trunc_type)print(len(train_sequences[0]))print(len(train_padded[0]))print(len(train_sequences[1]))print(len(train_padded[1]))print(len(train_sequences[10]))print(len(train_padded[10]))" }, { "code": null, "e": 3950, "s": 3742, "text": "In addition, there is padding_type and truncating_type, there are all post, means for example, for the 11th article, it was 186 in length, we padded to 200, and we padded at the end, that is adding 14 zeros." }, { "code": null, "e": 3974, "s": 3950, "text": "print(train_padded[10])" }, { "code": null, "e": 4079, "s": 3974, "text": "And for the 1st article, it was 426 in length, we truncated to 200, and we truncated at the end as well." }, { "code": null, "e": 4129, "s": 4079, "text": "Then we do the same for the validation sequences." }, { "code": null, "e": 4337, "s": 4129, "text": "Now we are going to look at the labels. Because our labels are text, so we will tokenize them, when training, labels are expected to be numpy arrays. So we will turn list of labels into numpy arrays like so:" }, { "code": null, "e": 4806, "s": 4337, "text": "label_tokenizer = Tokenizer()label_tokenizer.fit_on_texts(labels)training_label_seq = np.array(label_tokenizer.texts_to_sequences(train_labels))validation_label_seq = np.array(label_tokenizer.texts_to_sequences(validation_labels))print(training_label_seq[0])print(training_label_seq[1])print(training_label_seq[2])print(training_label_seq.shape)print(validation_label_seq[0])print(validation_label_seq[1])print(validation_label_seq[2])print(validation_label_seq.shape)" }, { "code": null, "e": 5068, "s": 4806, "text": "Before training deep neural network, we should explore what our original article and article after padding look like. Running the following code, we explore the 11th article, we can see that some words become “<OOV>”, because they did not make to the top 5,000." }, { "code": null, "e": 5317, "s": 5068, "text": "reverse_word_index = dict([(value, key) for (key, value) in word_index.items()])def decode_article(text): return ' '.join([reverse_word_index.get(i, '?') for i in text])print(decode_article(train_padded[10]))print('---')print(train_articles[10])" }, { "code": null, "e": 5353, "s": 5317, "text": "Now its the time to implement LSTM." }, { "code": null, "e": 5630, "s": 5353, "text": "We build a tf.keras.Sequential model and start with an embedding layer. An embedding layer stores one vector per word. When called, it converts the sequences of word indices into sequences of vectors. After training, words with similar meanings often have the similar vectors." }, { "code": null, "e": 5902, "s": 5630, "text": "The Bidirectional wrapper is used with a LSTM layer, this propagates the input forwards and backwards through the LSTM layer and then concatenates the outputs. This helps LSTM to learn long term dependencies. We then fit it to a dense neural network to do classification." }, { "code": null, "e": 5993, "s": 5902, "text": "We use relu in place of tahn function since they are very good alternatives of each other." }, { "code": null, "e": 6147, "s": 5993, "text": "We add a Dense layer with 6 units and softmax activation. When we have multiple outputs, softmax converts outputs layers into a probability distribution." }, { "code": null, "e": 6394, "s": 6147, "text": "In our model summary, we have our embeddings, our Bidirectional contains LSTM, followed by two dense layers. The output from Bidirectional is 128, because it doubled what we put in LSTM. We can also stack LSTM layer but I found the results worse." }, { "code": null, "e": 6413, "s": 6394, "text": "print(set(labels))" }, { "code": null, "e": 6798, "s": 6413, "text": "We have 5 labels in total, but because we did not one-hot encode labels, we have to use sparse_categorical_crossentropy as loss function, it seems to think 0 is a possible label as well, while the tokenizer object which tokenizes starting with integer 1, instead of integer 0. As a result, the last Dense layer needs outputs for labels 0, 1, 2, 3, 4, 5 although 0 has never been used." }, { "code": null, "e": 6941, "s": 6798, "text": "If you want the last Dense layer to be 5, you will need to subtract 1 from the training and validation labels. I decided to leave it as it is." }, { "code": null, "e": 7015, "s": 6941, "text": "I decided to train 10 epochs, and it is plenty of epochs as you will see." }, { "code": null, "e": 7266, "s": 7015, "text": "model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])num_epochs = 10history = model.fit(train_padded, training_label_seq, epochs=num_epochs, validation_data=(validation_padded, validation_label_seq), verbose=2)" }, { "code": null, "e": 7530, "s": 7266, "text": "def plot_graphs(history, string): plt.plot(history.history[string]) plt.plot(history.history['val_'+string]) plt.xlabel(\"Epochs\") plt.ylabel(string) plt.legend([string, 'val_'+string]) plt.show() plot_graphs(history, \"accuracy\")plot_graphs(history, \"loss\")" }, { "code": null, "e": 7646, "s": 7530, "text": "We probably only need 3 or 4 epochs. At the end of the training, we can see that there is a little bit overfitting." }, { "code": null, "e": 7704, "s": 7646, "text": "In the future posts, we will work on improving the model." } ]
Python Program for simple interest - GeeksforGeeks
18 Apr, 2020 Simple interest formula is given by:Simple Interest = (P x T x R)/100Where,P is the principle amountT is the time andR is the rate Examples: EXAMPLE1: Input : P = 10000 R = 5 T = 5 Output :2500 We need to find simple interest on Rs. 10,000 at the rate of 5% for 5 units of time. EXAMPLE2: Input : P = 3000 R = 7 T = 1 Output :210 Python3 # Python3 program to find simple interest# for given principal amount, time and# rate of interest. def simple_interest(p,t,r): print('The principal is', p) print('The time period is', t) print('The rate of interest is',r) si = (p * t * r)/100 print('The Simple Interest is', si) return si # Driver codesimple_interest(8, 6, 8) The principal is 8 The time period is 6 The rate of interest is 8 The Simple Interest is 3.84 #Please refer complete article on Program to find simple interest for more details! AnkanDatta Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Binary Search (Recursive and Iterative) Iterate over characters of a string in Python Python Program for Bubble Sort Python | Convert set into a list Add a key:value pair to dictionary in Python Appending to list in Python dictionary Python | Convert a list into a tuple
[ { "code": null, "e": 24619, "s": 24591, "text": "\n18 Apr, 2020" }, { "code": null, "e": 24750, "s": 24619, "text": "Simple interest formula is given by:Simple Interest = (P x T x R)/100Where,P is the principle amountT is the time andR is the rate" }, { "code": null, "e": 24760, "s": 24750, "text": "Examples:" }, { "code": null, "e": 24985, "s": 24760, "text": "EXAMPLE1:\nInput : P = 10000\n R = 5\n T = 5\nOutput :2500\nWe need to find simple interest on \nRs. 10,000 at the rate of 5% for 5 \nunits of time.\n\nEXAMPLE2:\nInput : P = 3000\n R = 7\n T = 1\nOutput :210\n" }, { "code": null, "e": 24993, "s": 24985, "text": "Python3" }, { "code": "# Python3 program to find simple interest# for given principal amount, time and# rate of interest. def simple_interest(p,t,r): print('The principal is', p) print('The time period is', t) print('The rate of interest is',r) si = (p * t * r)/100 print('The Simple Interest is', si) return si # Driver codesimple_interest(8, 6, 8)", "e": 25358, "s": 24993, "text": null }, { "code": null, "e": 25453, "s": 25358, "text": "The principal is 8\nThe time period is 6\nThe rate of interest is 8\nThe Simple Interest is 3.84\n" }, { "code": null, "e": 25537, "s": 25453, "text": "#Please refer complete article on Program to find simple interest for more details!" }, { "code": null, "e": 25548, "s": 25537, "text": "AnkanDatta" }, { "code": null, "e": 25564, "s": 25548, "text": "Python Programs" }, { "code": null, "e": 25662, "s": 25564, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25671, "s": 25662, "text": "Comments" }, { "code": null, "e": 25684, "s": 25671, "text": "Old Comments" }, { "code": null, "e": 25723, "s": 25684, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 25761, "s": 25723, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 25810, "s": 25761, "text": "Python | Convert string dictionary to dictionary" }, { "code": null, "e": 25869, "s": 25810, "text": "Python Program for Binary Search (Recursive and Iterative)" }, { "code": null, "e": 25915, "s": 25869, "text": "Iterate over characters of a string in Python" }, { "code": null, "e": 25946, "s": 25915, "text": "Python Program for Bubble Sort" }, { "code": null, "e": 25979, "s": 25946, "text": "Python | Convert set into a list" }, { "code": null, "e": 26024, "s": 25979, "text": "Add a key:value pair to dictionary in Python" }, { "code": null, "e": 26063, "s": 26024, "text": "Appending to list in Python dictionary" } ]
PyQt5 – How to hide the title bar of window ? - GeeksforGeeks
26 Mar, 2020 When we design the GUI (Graphical User Interface) application using PyQt5, there exist the window. A window is a (usually) rectangular portion of the display on a computer monitor that presents its contents (e.g., the contents of a directory, a text file or an image) seemingly independently of the rest of the screen. Windows are one of the elements that comprise a graphical user interface (GUI). In a window we can see there exist a title bar which comprises the icon and title on the left size and on the right side there exist control button. In this article we will see how we can hide title bar. In order to do so we will use setWindowFlag() method and pass which belongs to the QWidget class. Syntax : setWindowFlag(Qt.FramelessWindowHint) Argument : It takes Window type as argument. Action performed : It removes the title bar. Code : # importing the required libraries from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import Qtimport sys class Window(QMainWindow): def __init__(self): super().__init__() # this will hide the title bar self.setWindowFlag(Qt.FramelessWindowHint) # set the title self.setWindowTitle("no title") # setting the geometry of window self.setGeometry(100, 100, 400, 300) # creating a label widget # by default label will display at top left corner self.label_1 = QLabel('no title bar', self) # moving position self.label_1.move(100, 100) # setting up border and background color self.label_1.setStyleSheet("background-color: lightgreen; border: 3px solid green") # 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 : Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Enumerate() in Python Defaultdict in Python Different ways to create Pandas Dataframe sum() function in Python How to Install PIP on Windows ? Deque in Python Python String | replace() Convert integer to string in Python Stack in Python
[ { "code": null, "e": 24647, "s": 24619, "text": "\n26 Mar, 2020" }, { "code": null, "e": 25046, "s": 24647, "text": "When we design the GUI (Graphical User Interface) application using PyQt5, there exist the window. A window is a (usually) rectangular portion of the display on a computer monitor that presents its contents (e.g., the contents of a directory, a text file or an image) seemingly independently of the rest of the screen. Windows are one of the elements that comprise a graphical user interface (GUI)." }, { "code": null, "e": 25195, "s": 25046, "text": "In a window we can see there exist a title bar which comprises the icon and title on the left size and on the right side there exist control button." }, { "code": null, "e": 25348, "s": 25195, "text": "In this article we will see how we can hide title bar. In order to do so we will use setWindowFlag() method and pass which belongs to the QWidget class." }, { "code": null, "e": 25395, "s": 25348, "text": "Syntax : setWindowFlag(Qt.FramelessWindowHint)" }, { "code": null, "e": 25440, "s": 25395, "text": "Argument : It takes Window type as argument." }, { "code": null, "e": 25485, "s": 25440, "text": "Action performed : It removes the title bar." }, { "code": null, "e": 25492, "s": 25485, "text": "Code :" }, { "code": "# importing the required libraries from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import Qtimport sys class Window(QMainWindow): def __init__(self): super().__init__() # this will hide the title bar self.setWindowFlag(Qt.FramelessWindowHint) # set the title self.setWindowTitle(\"no title\") # setting the geometry of window self.setGeometry(100, 100, 400, 300) # creating a label widget # by default label will display at top left corner self.label_1 = QLabel('no title bar', self) # moving position self.label_1.move(100, 100) # setting up border and background color self.label_1.setStyleSheet(\"background-color: lightgreen; border: 3px solid green\") # 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": 26514, "s": 25492, "text": null }, { "code": null, "e": 26523, "s": 26514, "text": "Output :" }, { "code": null, "e": 26534, "s": 26523, "text": "Python-gui" }, { "code": null, "e": 26546, "s": 26534, "text": "Python-PyQt" }, { "code": null, "e": 26553, "s": 26546, "text": "Python" }, { "code": null, "e": 26651, "s": 26553, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26660, "s": 26651, "text": "Comments" }, { "code": null, "e": 26673, "s": 26660, "text": "Old Comments" }, { "code": null, "e": 26691, "s": 26673, "text": "Python Dictionary" }, { "code": null, "e": 26713, "s": 26691, "text": "Enumerate() in Python" }, { "code": null, "e": 26735, "s": 26713, "text": "Defaultdict in Python" }, { "code": null, "e": 26777, "s": 26735, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26802, "s": 26777, "text": "sum() function in Python" }, { "code": null, "e": 26834, "s": 26802, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26850, "s": 26834, "text": "Deque in Python" }, { "code": null, "e": 26876, "s": 26850, "text": "Python String | replace()" }, { "code": null, "e": 26912, "s": 26876, "text": "Convert integer to string in Python" } ]
Matplotlib.axes.Axes.set_xticklabels() in Python - GeeksforGeeks
21 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute. The Axes.set_xticklabels() function in axes module of matplotlib library is used to Set the x-tick labels with list of string labels. Syntax: Axes.set_xticklabels(self, labels, fontdict=None, minor=False, **kwargs) Parameters: This method accepts the following parameters. labels : This parameter is the list of of string labels. fontdict : This parameter is the dictionary controlling the appearance of the ticklabels. minor : This parameter is used whether set major ticks or to set minor ticks Return value: This method returns a list of Text instances. Below examples illustrate the matplotlib.axes.Axes.set_xticklabels() function in matplotlib.axes: Example 1: # Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as pltfrom matplotlib.patches import Polygon def func(x): return (x - 4) * (x - 6) * (x - 5) + 100 a, b = 2, 9 # integral limitsx = np.linspace(0, 10)y = func(x) fig, ax = plt.subplots()ax.plot(x, y, "k", linewidth = 2)ax.set_ylim(bottom = 0) # Make the shaded regionix = np.linspace(a, b)iy = func(ix)verts = [(a, 0), *zip(ix, iy), (b, 0)] poly = Polygon(verts, facecolor ='green', edgecolor ='0.5', alpha = 0.4)ax.add_patch(poly) ax.text(0.5 * (a + b), 30, r"$\int_a ^ b f(x)\mathrm{d}x$", horizontalalignment ='center', fontsize = 20) fig.text(0.9, 0.05, '$x$')fig.text(0.1, 0.9, '$y$') ax.spines['right'].set_visible(False)ax.spines['top'].set_visible(False) ax.set_xticks((a, b-a, b))ax.set_xticklabels(('$a$', '$valx$', '$b$')) fig.suptitle('matplotlib.axes.Axes.set_xticklabels() \function Example\n\n', fontweight ="bold")fig.canvas.draw()plt.show() Output: Example 2: # Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt # Fixing random state for reproducibilitynp.random.seed(19680801) x = np.linspace(0, 2 * np.pi, 100)y = np.sin(x)y2 = y + 0.2 * np.random.normal(size = x.shape) fig, ax = plt.subplots()ax.plot(x, y)ax.plot(x, y2) ax.set_xticks([0, np.pi, 2 * np.pi])ax.set_xticklabels(['0', r'$\pi$', r'2$\pi$']) ax.spines['left'].set_bounds(-1, 1)ax.spines['right'].set_visible(False)ax.spines['top'].set_visible(False) fig.suptitle('matplotlib.axes.Axes.set_xticklabels() \function Example\n\n', fontweight ="bold")fig.canvas.draw()plt.show() Output: Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Create a Pandas DataFrame from Lists Reading and Writing to text files in Python *args and **kwargs in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe sum() function in Python
[ { "code": null, "e": 24894, "s": 24866, "text": "\n21 Apr, 2020" }, { "code": null, "e": 25194, "s": 24894, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute." }, { "code": null, "e": 25328, "s": 25194, "text": "The Axes.set_xticklabels() function in axes module of matplotlib library is used to Set the x-tick labels with list of string labels." }, { "code": null, "e": 25409, "s": 25328, "text": "Syntax: Axes.set_xticklabels(self, labels, fontdict=None, minor=False, **kwargs)" }, { "code": null, "e": 25467, "s": 25409, "text": "Parameters: This method accepts the following parameters." }, { "code": null, "e": 25524, "s": 25467, "text": "labels : This parameter is the list of of string labels." }, { "code": null, "e": 25614, "s": 25524, "text": "fontdict : This parameter is the dictionary controlling the appearance of the ticklabels." }, { "code": null, "e": 25691, "s": 25614, "text": "minor : This parameter is used whether set major ticks or to set minor ticks" }, { "code": null, "e": 25751, "s": 25691, "text": "Return value: This method returns a list of Text instances." }, { "code": null, "e": 25849, "s": 25751, "text": "Below examples illustrate the matplotlib.axes.Axes.set_xticklabels() function in matplotlib.axes:" }, { "code": null, "e": 25860, "s": 25849, "text": "Example 1:" }, { "code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as pltfrom matplotlib.patches import Polygon def func(x): return (x - 4) * (x - 6) * (x - 5) + 100 a, b = 2, 9 # integral limitsx = np.linspace(0, 10)y = func(x) fig, ax = plt.subplots()ax.plot(x, y, \"k\", linewidth = 2)ax.set_ylim(bottom = 0) # Make the shaded regionix = np.linspace(a, b)iy = func(ix)verts = [(a, 0), *zip(ix, iy), (b, 0)] poly = Polygon(verts, facecolor ='green', edgecolor ='0.5', alpha = 0.4)ax.add_patch(poly) ax.text(0.5 * (a + b), 30, r\"$\\int_a ^ b f(x)\\mathrm{d}x$\", horizontalalignment ='center', fontsize = 20) fig.text(0.9, 0.05, '$x$')fig.text(0.1, 0.9, '$y$') ax.spines['right'].set_visible(False)ax.spines['top'].set_visible(False) ax.set_xticks((a, b-a, b))ax.set_xticklabels(('$a$', '$valx$', '$b$')) fig.suptitle('matplotlib.axes.Axes.set_xticklabels() \\function Example\\n\\n', fontweight =\"bold\")fig.canvas.draw()plt.show()", "e": 26875, "s": 25860, "text": null }, { "code": null, "e": 26883, "s": 26875, "text": "Output:" }, { "code": null, "e": 26894, "s": 26883, "text": "Example 2:" }, { "code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt # Fixing random state for reproducibilitynp.random.seed(19680801) x = np.linspace(0, 2 * np.pi, 100)y = np.sin(x)y2 = y + 0.2 * np.random.normal(size = x.shape) fig, ax = plt.subplots()ax.plot(x, y)ax.plot(x, y2) ax.set_xticks([0, np.pi, 2 * np.pi])ax.set_xticklabels(['0', r'$\\pi$', r'2$\\pi$']) ax.spines['left'].set_bounds(-1, 1)ax.spines['right'].set_visible(False)ax.spines['top'].set_visible(False) fig.suptitle('matplotlib.axes.Axes.set_xticklabels() \\function Example\\n\\n', fontweight =\"bold\")fig.canvas.draw()plt.show()", "e": 27528, "s": 26894, "text": null }, { "code": null, "e": 27536, "s": 27528, "text": "Output:" }, { "code": null, "e": 27554, "s": 27536, "text": "Python-matplotlib" }, { "code": null, "e": 27561, "s": 27554, "text": "Python" }, { "code": null, "e": 27659, "s": 27561, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27677, "s": 27659, "text": "Python Dictionary" }, { "code": null, "e": 27699, "s": 27677, "text": "Enumerate() in Python" }, { "code": null, "e": 27731, "s": 27699, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27773, "s": 27731, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27810, "s": 27773, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 27854, "s": 27810, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 27883, "s": 27854, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27925, "s": 27883, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27981, "s": 27925, "text": "How to drop one or multiple columns in Pandas Dataframe" } ]
Maximum XOR subarray | Practice | GeeksforGeeks
Given an array arr[] of size, N. Find the subarray with maximum XOR. A subarray is a contiguous part of the array. Example 1: Input: N = 4 arr[] = {1,2,3,4} Output: 7 Explanation: The subarray {3,4} has maximum xor value equal to 7. Your Task: You don't need to read input or print anything. Your task is to complete the function maxSubarrayXOR() which takes the array arr[], its size N as input parameters and returns the maximum xor of any subarray. Expected Time Complexity: O(N) Expected Auxiliary Space: O(N) Constraints: 1 <= N <= 105 1 <= arr[i] <= 105 0 apoorvmishra2 months ago struct node{ node* child[2]; int value; node(){ child[0]=NULL; child[1]=NULL; value=0; }};class trie{ public: node* root; trie(){ root= new node; } void insert(int num){ node* temp=root; for(int i=31;i>=0;i--){ bool bit=num&(1<<i); if(temp->child[bit]==NULL){ temp->child[bit]=new node; } temp=temp->child[bit]; } temp->value=num; } int query(int num){ node* temp=root; for(int i=31;i>=0;i--){ bool bit=num&(1<<i); if(temp->child[1-bit]!=NULL){ temp=temp->child[1-bit]; }else if(temp->child[bit]!=NULL){ temp=temp->child[bit]; } } return (temp->value)^num; }};class Solution{ public: int maxSubarrayXOR(int N, int arr[]){ trie t; t.insert(0); int res=0,prefixXor=0; for(int i=0;i<N;i++){ prefixXor=prefixXor^arr[i]; t.insert(prefixXor); res=max(res,t.query(prefixXor)); } return res; }}; 0 mayank20212 months ago @gfg please see.. backend code seems wrong in this case.for this testcase, it's showing 100001 as output. I tried manually but i can't get above 10000. what am I missing here ?3 100000 99999 99998 -1 aloksinghbais023 months ago C++ solution using kadane's algorithm having time complexity as O(N) and space complexity as O(1) is as follows :- Execution Time :- 0.1 / 1.2 sec int maxSubarrayXOR(int N, int arr[]){ if(N==1) return (arr[0]); int max_so_far = 0; int curr_max = 1; for(int i=0; i<N; i++){ curr_max = max(arr[i],arr[i] ^ curr_max); max_so_far = max(max_so_far,curr_max); } return (max_so_far); } -1 devshukla07 This comment was deleted. -9 amail4muni4 months ago for java solution class Solution{ static int maxSubarrayXOR(int N, int arr[]){ // code here int ans = 1; // Initialize result int curr_xor = 1; // Pick starting points of subarrays for (int i=0; i<N; i++) { curr_xor = Math.max(arr[i],curr_xor^arr[i]); ans = Math.max(ans, curr_xor); } return ans; }} -11 sreenathmopuri4 months ago class Solution{ public: int maxSubarrayXOR(int N, int arr[]){ //code here int max_so_far = 1, maxXor = 1; for (int i = 0; i < N; i++) { max_so_far = max(arr[i], max_so_far ^ arr[i]); maxXor = max(maxXor, max_so_far); } return maxXor; }}; 0 dmaddalena694 months ago This is the solution but I cannot decrease the execution time of the program. Anyone can help me? int maxSubarrayXOR(int N, int arr[]){ int max_xor = 0, ele_subarr = 1, re_xor = 0; while(ele_subarr <= N) { for(int i = 0; i < N-(ele_subarr-1); i++) { for(int j = i; j < ele_subarr+i; j++) re_xor ^= arr[j]; if(re_xor > max_xor) max_xor = re_xor; re_xor = 0; } ele_subarr++; } return max_xor; } 0 tanmaymm585 months ago Why isn't this solution working? I am gettig the output 2 and the XOR of 4 and 6 is 2 but it is saying the answer is 6. Can some explain me? class Solution: def maxSubarrayXOR (self, N, arr): # code here for i in range(N-1): arr[i] = arr[i] ^ arr[i+1] for j in range(len(arr)-1): if arr[j] > arr[j+1]: pass return arr[j] 0 sudarshans35 months ago ss -10 lapimpale7 months ago class Solution{ static int maxSubarrayXOR(int N, int arr[]){ int ans = 1; // Initialize result int curr_xor = 1; // Pick starting points of subarrays for (int i=0; i<N; i++) { curr_xor = Math.max(arr[i],curr_xor^arr[i]); ans = Math.max(ans, curr_xor); } return ans; } } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 353, "s": 238, "text": "Given an array arr[] of size, N. Find the subarray with maximum XOR. A subarray is a contiguous part of the array." }, { "code": null, "e": 365, "s": 353, "text": "\nExample 1:" }, { "code": null, "e": 476, "s": 365, "text": "Input:\nN = 4\narr[] = {1,2,3,4}\nOutput: 7\nExplanation: \nThe subarray {3,4} has maximum xor \nvalue equal to 7.\n\n" }, { "code": null, "e": 699, "s": 476, "text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function maxSubarrayXOR() which takes the array arr[], its size N as input parameters and returns the maximum xor of any subarray.\n " }, { "code": null, "e": 764, "s": 699, "text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)\n\n " }, { "code": null, "e": 810, "s": 764, "text": "Constraints:\n1 <= N <= 105\n1 <= arr[i] <= 105" }, { "code": null, "e": 812, "s": 810, "text": "0" }, { "code": null, "e": 837, "s": 812, "text": "apoorvmishra2 months ago" }, { "code": null, "e": 1919, "s": 837, "text": "struct node{ node* child[2]; int value; node(){ child[0]=NULL; child[1]=NULL; value=0; }};class trie{ public: node* root; trie(){ root= new node; } void insert(int num){ node* temp=root; for(int i=31;i>=0;i--){ bool bit=num&(1<<i); if(temp->child[bit]==NULL){ temp->child[bit]=new node; } temp=temp->child[bit]; } temp->value=num; } int query(int num){ node* temp=root; for(int i=31;i>=0;i--){ bool bit=num&(1<<i); if(temp->child[1-bit]!=NULL){ temp=temp->child[1-bit]; }else if(temp->child[bit]!=NULL){ temp=temp->child[bit]; } } return (temp->value)^num; }};class Solution{ public: int maxSubarrayXOR(int N, int arr[]){ trie t; t.insert(0); int res=0,prefixXor=0; for(int i=0;i<N;i++){ prefixXor=prefixXor^arr[i]; t.insert(prefixXor); res=max(res,t.query(prefixXor)); } return res; }};" }, { "code": null, "e": 1921, "s": 1919, "text": "0" }, { "code": null, "e": 1944, "s": 1921, "text": "mayank20212 months ago" }, { "code": null, "e": 2141, "s": 1944, "text": "@gfg please see.. backend code seems wrong in this case.for this testcase, it's showing 100001 as output. I tried manually but i can't get above 10000. what am I missing here ?3 100000 99999 99998" }, { "code": null, "e": 2144, "s": 2141, "text": "-1" }, { "code": null, "e": 2172, "s": 2144, "text": "aloksinghbais023 months ago" }, { "code": null, "e": 2287, "s": 2172, "text": "C++ solution using kadane's algorithm having time complexity as O(N) and space complexity as O(1) is as follows :-" }, { "code": null, "e": 2321, "s": 2289, "text": "Execution Time :- 0.1 / 1.2 sec" }, { "code": null, "e": 2617, "s": 2323, "text": "int maxSubarrayXOR(int N, int arr[]){ if(N==1) return (arr[0]); int max_so_far = 0; int curr_max = 1; for(int i=0; i<N; i++){ curr_max = max(arr[i],arr[i] ^ curr_max); max_so_far = max(max_so_far,curr_max); } return (max_so_far); }" }, { "code": null, "e": 2620, "s": 2617, "text": "-1" }, { "code": null, "e": 2632, "s": 2620, "text": "devshukla07" }, { "code": null, "e": 2658, "s": 2632, "text": "This comment was deleted." }, { "code": null, "e": 2661, "s": 2658, "text": "-9" }, { "code": null, "e": 2684, "s": 2661, "text": "amail4muni4 months ago" }, { "code": null, "e": 2702, "s": 2684, "text": "for java solution" }, { "code": null, "e": 2720, "s": 2704, "text": "class Solution{" }, { "code": null, "e": 3076, "s": 2720, "text": " static int maxSubarrayXOR(int N, int arr[]){ // code here int ans = 1; // Initialize result int curr_xor = 1; // Pick starting points of subarrays for (int i=0; i<N; i++) { curr_xor = Math.max(arr[i],curr_xor^arr[i]); ans = Math.max(ans, curr_xor); } return ans; }}" }, { "code": null, "e": 3080, "s": 3076, "text": "-11" }, { "code": null, "e": 3107, "s": 3080, "text": "sreenathmopuri4 months ago" }, { "code": null, "e": 3439, "s": 3107, "text": "class Solution{ public: int maxSubarrayXOR(int N, int arr[]){ //code here int max_so_far = 1, maxXor = 1; for (int i = 0; i < N; i++) { max_so_far = max(arr[i], max_so_far ^ arr[i]); maxXor = max(maxXor, max_so_far); } return maxXor; }};" }, { "code": null, "e": 3441, "s": 3439, "text": "0" }, { "code": null, "e": 3466, "s": 3441, "text": "dmaddalena694 months ago" }, { "code": null, "e": 3564, "s": 3466, "text": "This is the solution but I cannot decrease the execution time of the program. Anyone can help me?" }, { "code": null, "e": 4125, "s": 3564, "text": "int maxSubarrayXOR(int N, int arr[]){ \n \n int max_xor = 0, ele_subarr = 1, re_xor = 0;\n \n while(ele_subarr <= N)\n {\n for(int i = 0; i < N-(ele_subarr-1); i++)\n {\n for(int j = i; j < ele_subarr+i; j++)\n re_xor ^= arr[j];\n \n if(re_xor > max_xor)\n max_xor = re_xor;\n \n re_xor = 0;\n }\n \n ele_subarr++;\n }\n \n return max_xor;\n }" }, { "code": null, "e": 4127, "s": 4125, "text": "0" }, { "code": null, "e": 4150, "s": 4127, "text": "tanmaymm585 months ago" }, { "code": null, "e": 4539, "s": 4150, "text": "Why isn't this solution working? I am gettig the output 2 and the XOR of 4 and 6 is 2 but it is saying the answer is 6. Can some explain me? class Solution: def maxSubarrayXOR (self, N, arr): # code here for i in range(N-1): arr[i] = arr[i] ^ arr[i+1] for j in range(len(arr)-1): if arr[j] > arr[j+1]: pass return arr[j] " }, { "code": null, "e": 4541, "s": 4539, "text": "0" }, { "code": null, "e": 4565, "s": 4541, "text": "sudarshans35 months ago" }, { "code": null, "e": 4568, "s": 4565, "text": "ss" }, { "code": null, "e": 4572, "s": 4568, "text": "-10" }, { "code": null, "e": 4594, "s": 4572, "text": "lapimpale7 months ago" }, { "code": null, "e": 4968, "s": 4594, "text": "class Solution{\n\n static int maxSubarrayXOR(int N, int arr[]){\n int ans = 1; // Initialize result \n int curr_xor = 1; \n // Pick starting points of subarrays \n for (int i=0; i<N; i++) \n {\n curr_xor = Math.max(arr[i],curr_xor^arr[i]); \n ans = Math.max(ans, curr_xor); \n } \n return ans; \n }\n}" }, { "code": null, "e": 5114, "s": 4968, "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": 5150, "s": 5114, "text": " Login to access your submissions. " }, { "code": null, "e": 5160, "s": 5150, "text": "\nProblem\n" }, { "code": null, "e": 5170, "s": 5160, "text": "\nContest\n" }, { "code": null, "e": 5233, "s": 5170, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5381, "s": 5233, "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": 5589, "s": 5381, "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": 5695, "s": 5589, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
process.argv() Method in Node.js
The process.argv() method is used for returning all the command-line arguments that were passed when the Node.js process was being launched. The first element will always contains the same value as process.execPath. process.argv() Since it returns all the command line arguments passed before the node.js process. It does not need any inputs from the user. Create a file with name – argv.js and copy the below code snippet. After creating file, use the following command to run this code as shown in the example below − node argv.js argv.js Live Demo // Node.js program to demonstrate the use of process.argv // Importing the process module const process = require('process'); // Printing property value for process.argv console.log(process.argv); C:\home\node>> node argv.js [ '/usr/bin/node', '/home/node/test/process.js' ] Let's take a look at one more example. Live Demo // Node.js program to demonstrate the use of process.argv // Importing the process module const process = require('process'); // Printing process.argv property value var args = process.argv; console.log("Total number of arguments are: "+args.length); args.forEach((val, index) => { console.log(`${index}: ${val}`); }); C:\home\node>> node argv.js Total number of arguments are: 2 0: /usr/bin/node 1: /home/node/test/process.js
[ { "code": null, "e": 1278, "s": 1062, "text": "The process.argv() method is used for returning all the command-line arguments that were passed when the Node.js process was being launched. The first element will always contains the same value as process.execPath." }, { "code": null, "e": 1293, "s": 1278, "text": "process.argv()" }, { "code": null, "e": 1419, "s": 1293, "text": "Since it returns all the command line arguments passed before the node.js process. It does not need any inputs from the user." }, { "code": null, "e": 1582, "s": 1419, "text": "Create a file with name – argv.js and copy the below code snippet. After creating file, use the following command to run this code as shown in the example below −" }, { "code": null, "e": 1595, "s": 1582, "text": "node argv.js" }, { "code": null, "e": 1603, "s": 1595, "text": "argv.js" }, { "code": null, "e": 1614, "s": 1603, "text": " Live Demo" }, { "code": null, "e": 1813, "s": 1614, "text": "// Node.js program to demonstrate the use of process.argv\n\n// Importing the process module\nconst process = require('process');\n\n// Printing property value for process.argv\nconsole.log(process.argv);" }, { "code": null, "e": 1891, "s": 1813, "text": "C:\\home\\node>> node argv.js\n[ '/usr/bin/node',\n'/home/node/test/process.js' ]" }, { "code": null, "e": 1930, "s": 1891, "text": "Let's take a look at one more example." }, { "code": null, "e": 1941, "s": 1930, "text": " Live Demo" }, { "code": null, "e": 2266, "s": 1941, "text": "// Node.js program to demonstrate the use of process.argv\n\n// Importing the process module\nconst process = require('process');\n\n// Printing process.argv property value\nvar args = process.argv;\n\nconsole.log(\"Total number of arguments are: \"+args.length);\nargs.forEach((val, index) => {\n console.log(`${index}: ${val}`);\n});" }, { "code": null, "e": 2374, "s": 2266, "text": "C:\\home\\node>> node argv.js\nTotal number of arguments are: 2\n0: /usr/bin/node\n1: /home/node/test/process.js" } ]
Alternatively Merge two Strings in Java - GeeksforGeeks
15 Dec, 2020 Given 2 strings, merge them in an alternate way, i.e. the final string’s first character is the first character of the first string, the second character of the final string is the first character of the second string and so on. And if once you reach end of one string while if another string is still remaining then append the remaining of that string to final string Examples: Input : string 1 :"geeks" string 2 :"forgeeks" Output: "gfeoerkgseeks" Explanation : The answer contains characters from alternate strings, and once the first string ends the remaining of the second string is added to the final string Input :string 1 :"hello" string 2 :"geeks" Output : hgeelelkos The idea is simple, we create a result string. We one by one append characters of both given strings in alternate style. C++ Java Python3 C# // C++ code to alternatively merge two strings#include <bits/stdc++.h>using namespace std; // Function for alternatively merging two stringsstring merge(string s1, string s2){ // To store the final string string result = ""; // For every index in the strings for (int i = 0; i < s1.length() || i < s2.length(); i++) { // First choose the ith character of the // first string if it exists if (i < s1.length()) result += s1[i]; // Then choose the ith character of the // second string if it exists if (i < s2.length()) result += s2[i]; } return result;} // Driver codeint main(){ string s1 = "geeks"; string s2 = "forgeeks"; cout << merge(s1, s2); return 0;} // This code is contributed by gp6 // Java code to alternatively merge two stringspublic class mergeString { // Function for alternatively merging two strings public static String merge(String s1, String s2) { // To store the final string StringBuilder result = new StringBuilder(); // For every index in the strings for (int i = 0; i < s1.length() || i < s2.length(); i++) { // First choose the ith character of the // first string if it exists if (i < s1.length()) result.append(s1.charAt(i)); // Then choose the ith character of the // second string if it exists if (i < s2.length()) result.append(s2.charAt(i)); } return result.toString(); } // Driver code public static void main(String[] args) { String s1 = "geeks"; String s2 = "forgeeks"; System.out.println(merge(s1, s2)); }} # Python3 code to alternatively merge two strings # Function for alternatively merging two stringsdef merge(s1, s2): # To store the final string result = "" # For every index in the strings i = 0 while (i < len(s1)) or (i < len(s2)): # First choose the ith character of the # first string if it exists if (i < len(s1)): result += s1[i] # Then choose the ith character of the # second string if it exists if (i < len(s2)): result += s2[i] i += 1 return result # Driver Codes1 = "geeks"s2 = "forgeeks" print(merge(s1, s2)) # This code is contributed by divyesh072019 // C# code to alternatively merge two stringsusing System;class GFG { // Function for alternatively merging two strings static string merge(string s1, string s2) { // To store the final string string result = ""; // For every index in the strings for (int i = 0; i < s1.Length || i < s2.Length; i++) { // First choose the ith character of the // first string if it exists if (i < s1.Length) result += s1[i]; // Then choose the ith character of the // second string if it exists if (i < s2.Length) result += s2[i]; } return result; } static void Main() { string s1 = "geeks"; string s2 = "forgeeks"; Console.WriteLine(merge(s1, s2)); }} // This code is contributed by divyeshrabadiya07 gfeoerkgseeks shivamgupta356331 divyaramadoss1 gp6 divyesh072019 divyeshrabadiya07 Airtel array-merge Strings Airtel Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python program to check if a string is palindrome or not Array of Strings in C++ (5 Different Ways to Create) 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 How to split a string in C/C++, Python and Java? Reverse words in a given string
[ { "code": null, "e": 26715, "s": 26687, "text": "\n15 Dec, 2020" }, { "code": null, "e": 27085, "s": 26715, "text": "Given 2 strings, merge them in an alternate way, i.e. the final string’s first character is the first character of the first string, the second character of the final string is the first character of the second string and so on. And if once you reach end of one string while if another string is still remaining then append the remaining of that string to final string " }, { "code": null, "e": 27096, "s": 27085, "text": "Examples: " }, { "code": null, "e": 27412, "s": 27096, "text": "Input : string 1 :\"geeks\"\n string 2 :\"forgeeks\"\nOutput: \"gfeoerkgseeks\"\nExplanation : The answer contains characters from alternate strings, and once \nthe first string ends the remaining of the second string is added to the final string\n\nInput :string 1 :\"hello\"\n string 2 :\"geeks\"\nOutput : hgeelelkos" }, { "code": null, "e": 27533, "s": 27412, "text": "The idea is simple, we create a result string. We one by one append characters of both given strings in alternate style." }, { "code": null, "e": 27537, "s": 27533, "text": "C++" }, { "code": null, "e": 27542, "s": 27537, "text": "Java" }, { "code": null, "e": 27550, "s": 27542, "text": "Python3" }, { "code": null, "e": 27553, "s": 27550, "text": "C#" }, { "code": "// C++ code to alternatively merge two strings#include <bits/stdc++.h>using namespace std; // Function for alternatively merging two stringsstring merge(string s1, string s2){ // To store the final string string result = \"\"; // For every index in the strings for (int i = 0; i < s1.length() || i < s2.length(); i++) { // First choose the ith character of the // first string if it exists if (i < s1.length()) result += s1[i]; // Then choose the ith character of the // second string if it exists if (i < s2.length()) result += s2[i]; } return result;} // Driver codeint main(){ string s1 = \"geeks\"; string s2 = \"forgeeks\"; cout << merge(s1, s2); return 0;} // This code is contributed by gp6", "e": 28365, "s": 27553, "text": null }, { "code": "// Java code to alternatively merge two stringspublic class mergeString { // Function for alternatively merging two strings public static String merge(String s1, String s2) { // To store the final string StringBuilder result = new StringBuilder(); // For every index in the strings for (int i = 0; i < s1.length() || i < s2.length(); i++) { // First choose the ith character of the // first string if it exists if (i < s1.length()) result.append(s1.charAt(i)); // Then choose the ith character of the // second string if it exists if (i < s2.length()) result.append(s2.charAt(i)); } return result.toString(); } // Driver code public static void main(String[] args) { String s1 = \"geeks\"; String s2 = \"forgeeks\"; System.out.println(merge(s1, s2)); }}", "e": 29304, "s": 28365, "text": null }, { "code": "# Python3 code to alternatively merge two strings # Function for alternatively merging two stringsdef merge(s1, s2): # To store the final string result = \"\" # For every index in the strings i = 0 while (i < len(s1)) or (i < len(s2)): # First choose the ith character of the # first string if it exists if (i < len(s1)): result += s1[i] # Then choose the ith character of the # second string if it exists if (i < len(s2)): result += s2[i] i += 1 return result # Driver Codes1 = \"geeks\"s2 = \"forgeeks\" print(merge(s1, s2)) # This code is contributed by divyesh072019", "e": 29996, "s": 29304, "text": null }, { "code": "// C# code to alternatively merge two stringsusing System;class GFG { // Function for alternatively merging two strings static string merge(string s1, string s2) { // To store the final string string result = \"\"; // For every index in the strings for (int i = 0; i < s1.Length || i < s2.Length; i++) { // First choose the ith character of the // first string if it exists if (i < s1.Length) result += s1[i]; // Then choose the ith character of the // second string if it exists if (i < s2.Length) result += s2[i]; } return result; } static void Main() { string s1 = \"geeks\"; string s2 = \"forgeeks\"; Console.WriteLine(merge(s1, s2)); }} // This code is contributed by divyeshrabadiya07", "e": 30890, "s": 29996, "text": null }, { "code": null, "e": 30904, "s": 30890, "text": "gfeoerkgseeks" }, { "code": null, "e": 30924, "s": 30906, "text": "shivamgupta356331" }, { "code": null, "e": 30939, "s": 30924, "text": "divyaramadoss1" }, { "code": null, "e": 30943, "s": 30939, "text": "gp6" }, { "code": null, "e": 30957, "s": 30943, "text": "divyesh072019" }, { "code": null, "e": 30975, "s": 30957, "text": "divyeshrabadiya07" }, { "code": null, "e": 30982, "s": 30975, "text": "Airtel" }, { "code": null, "e": 30994, "s": 30982, "text": "array-merge" }, { "code": null, "e": 31002, "s": 30994, "text": "Strings" }, { "code": null, "e": 31009, "s": 31002, "text": "Airtel" }, { "code": null, "e": 31017, "s": 31009, "text": "Strings" }, { "code": null, "e": 31115, "s": 31017, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31172, "s": 31115, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 31225, "s": 31172, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 31261, "s": 31225, "text": "Convert string to char array in C++" }, { "code": null, "e": 31299, "s": 31261, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 31329, "s": 31299, "text": "Caesar Cipher in Cryptography" }, { "code": null, "e": 31381, "s": 31329, "text": "Check whether two strings are anagram of each other" }, { "code": null, "e": 31426, "s": 31381, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 31487, "s": 31426, "text": "Length of the longest substring without repeating characters" }, { "code": null, "e": 31536, "s": 31487, "text": "How to split a string in C/C++, Python and Java?" } ]
Machine Learning: Target Feature Label Imbalance Problems and Solutions | by Joseph Cohen | Towards Data Science
IntroductionWhat is train data?Why do we need to balance train data?What does “balancing data” actually look like in practice?Do we also need to balance test data?Evaluation metrics for imbalanced test data Introduction What is train data? Why do we need to balance train data? What does “balancing data” actually look like in practice? Do we also need to balance test data? Evaluation metrics for imbalanced test data SetupInitial feature engineeringModel purpose transformationAddressing categorical featuresTrain test splitData balancingModelsWhat if we balance the test data?ConclusionResources Setup Initial feature engineering Model purpose transformation Addressing categorical features Train test split Data balancing Models What if we balance the test data? Conclusion Resources The goal of this post is to teach python programmers why they must have balanced data for model training and how to balance those data sets. Often times, in machine learning classification problems, models will not work as well and be incomplete without performing data balancing on train data. This post will serve as an end-to-end guide for solving this problem. Table of contents Before running a model, you need to fit the model on a set of data that is distinct from the data you test it on. In other words, if you create a model based on one pool of data and run that same pool of data back through the model, and the model performs well, you likely haven’t built anything exciting or proven anything. Therefore, a common way to generate extra data is to cut off a random segment of the total data, and use the remaining data for model training and go back to the cut off (and smaller) set of data for model validation purposes. Table of contents I am a strong believer in using extreme examples to prove points. In this case, I’d like to provide the following example to demonstrate why data balance matters in classification algorithms: say you are trying to predict whether a certain disease is likely to occur for a given person. Let’s focus on the output here, meaning the y-value we are trying to predict via our numerous features. Make up all the features you want to use as they won’t matter in a second. If we had 500 data points and 499 showed healthy people while 1 showed a diseased person and our model had 100% accuracy... well it doesn’t prove a whole lot. In fact, it proves just as much as a 99.99% accurate model where the one error was in the diseased person predicted as healthy. Having a 499-to-1 distribution of data points just doesn’t cut it as we don’t have the required level of data to develop an understanding of what may lead to disease. Balancing data gives us the same amount of information to help predict each class and therefore gives a better idea of how to respond to test data. Table of contents There are a couple ways to think through balancing data. I will talk about three in particular. I’ll start by discussing the ideas here and later share the coding process. Example data: 10 rows of data with label A. 12 rows of data with label B. 14 rows of data with label C. Method 1: Under-sampling; Delete some data from rows of data from the majority classes. In this case, delete 2 rows resulting in label B and 4 rows resulting in label C. Limitation: This is hard to use when you don’t have a substantial (and relatively equal) amount of data from each target class. Method 2: Copy rows of data resulting minority labels. In this case, copy 4 rows with label A and 2 rows with label B to add a total of 6 new rows to the data set. Limitation: I think the limitation here is pretty clear. All you are really doing is copying current data and you don’t really present anything new. You will get better models, though. Method 3: (SMOTE - Synthetic Minority Oversampling Technique) Synthetically generate new data based on implications of old data. Basically, instead of deleting or copying data, you use the current inputs to generate new input rows that are unique but will have a label based on what the original data implies. In the case above, one simple way to think of this idea would be to add 4 rows with label A to the data where the inputs represent total or partial similarities in values to current input features. Repeat this process for 2 rows of label B as well. Limitation: If two different class labels have common neighboring examples, it may be hard to generate accurate data representing what each unique label may look like from the input side and therefore SMOTE struggles with higher dimensionality data (Lusa, L and Blagus, R, 2013). Table of contents Usually, this is something we don’t do. You can sometimes upsample test data anyway just to see if your model works well on minority classes as well. What’s most important to keep in mind is that you don’t want to upsample data and only then do a data split into train and test set. This will likely result in having elements of train data copied perfectly into test data and artificially boost your model scores. The only time you would ever upsample test data is after a data split, just like you only perform data balancing on train data. Table of contents If we have a strong imbalance in test data, we still have ways of understanding how well our model performs outside of the accuracy metric. Accuracy, our intuitive and classic metric, is actually only a measure of wrong-or-right for every single observation. It does not take into account how many of each label are included in the data and works best with relatively balanced data (or in cases where correct predictions are more important regardless of the distribution of the various outcomes in the target feature). Having alternative metrics is less of a reason as to why you shouldn’t balance test data, but more of a reason why you might not need to balance test data. Let’s look at three metrics that are effective in the context of binary classification algorithm (they are also relevant for non-binary problems, but binary problems provide the easiest method of illustration). Precision Precision is a measure that tells you how meaningful a positive (target class = 1) is. This is accomplished by dividing the number of correct positive predictions over total number of positive predictions (true positive divided by sum of false positives and true positives). Say you are predicting disease and have 400 healthy people and 100 diseased people. If you predict all 500 cases to be diseased, you have correctly identified every case of disease, but your model is rather meaningless as you always have the same outcome and you misidentified 80% of the inputs. Recall Recall is very similar to precision. The denominator in recall, however, is composed of true positives and false negatives, while the numerator remains true positives. This shifts our focus from how much a positive score actually matters, to an understanding of how effective our model is at identifying any positive case that is present (because a false negative is actually a positive). As the number of false negatives grow, there is no increase to the numerator of true positives, and the recall gets lower and lower. Let’s use the precision example again. If you predict 500 patients to be diseased when only 100 are actually diseased, you will have high recall as there are no false negatives. However, if you go to the other extreme and say everyone is healthy, then all the sudden you have 80% accuracy and no false positives but you failed to identify 100% of the diseased people. You may notice that in the case where everyone is predicted to be sick that precision is low while recall is high. There is in fact a moderate tradeoff between optimizing precision and recall. F1-Score The F1-Score is the perfect way in which we can get a better sense of model performance when we have imbalanced data since accuracy alone isn’t a good metric. F1-Score is a harmonic average (max value is the arithmetic mean) of the precision and recall score. Having a blend of precision and recall gives us a strong idea of how well the model actually works. Table of contents The data I will be using for demonstration can be found at kaggle.com at this link and deals with diamond price prediction The code below will take you through the entire process; from beginning imports and data preparation to modeling Install libraries !pip install -U scikit-learn!pip install -U imbalanced-learn!pip install xgboost Import necessary libraries # remove warningsimport warningswarnings.filterwarnings('ignore')# standard imports and setupimport pandas as pdimport numpy as npimport matplotlib.pyplot as plt%matplotlib inlineimport seaborn as snsfrom scipy import stats# model evaluationfrom sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV, ShuffleSplitfrom sklearn.metrics import *# pipelinesfrom sklearn.compose import make_column_transformerfrom sklearn.pipeline import Pipeline, make_pipeline# data preparationfrom sklearn.preprocessing import *from sklearn.decomposition import PCAfrom sklearn.feature_selection import RFE, RFECVfrom sklearn.utils import resamplefrom imblearn.datasets import make_imbalancefrom imblearn.over_sampling import SMOTE# machine learningfrom sklearn.linear_model import *from sklearn.neighbors import KNeighborsClassifierfrom sklearn.svm import SVC, LinearSVCfrom sklearn.naive_bayes import GaussianNBfrom sklearn.ensemble import RandomForestClassifier, RandomForestRegressorfrom sklearn.tree import DecisionTreeClassifierfrom xgboost import XGBClassifier, XGBRegressor Read and preview data df=pd.read_csv('diamonds.csv')print(df.shape)df.head() Drop “Unnamed: 0” as it is useless and look for null values While looking for null values, get a feel for the data types df.drop('Unnamed: 0', axis=1, inplace=True)df.info() There appear to be no null values Table of contents Next, we will quickly do some feature modifications You may notice that the product of x, y, and z (according to the kaggle link) correspond to volume. We can add a feature called volume to equal this product and remove x, y, and z. I’d like to credit Chinmay Rane for this idea as I saw it in his kaggle notebook which can be found at this link (Rane, 2018) df['volume'] = df.x*df.y*df.zdf.drop(['x','z','y'],axis=1,inplace=True) What does new data look like? Table of contents You may notice that the data above present our target feature of price as a continuous variable, but we can establish sets of intervals in the target feature to morph it into a classification problem The plan is as follows: we will split the target feature into various intervals of values, and I like picking four unique intervals for this problem Those intervals are as follows (along with value counts) Pandas has a built in function to break things down into bins and you can even have a 1:1 ratio from each bin size to the next using pd.qcut We still have a problem as it is a bit of a pain to look at intervals Thankfully, Pandas let’s users create default labels as I will show below df['price_bin']=pd.cut(df.price,bins=4,labels=[0,1,2,3]) Now, look at data below from the first couple rows You may notice that the most common label above is 0 and that is reflected below For more information on the built-in functions used above, you can view documentation for pandas.cut here and documentation for pandas.qcut here Table of contents We now are looking at a classification problem, but there is still the problem of the features cut, color, and clarity which do not have numeric values To solve this problem we will use label encoding which is a method of assigning a numeric label for unique value of a categorical variable I actually prefer target encoding, but don’t believe target encoding is the most “fair” approximation with very few input features present After encoding labels, we will do a double check to ensure our data is of type float le = LabelEncoder()for col in df.select_dtypes(include='O').columns: df[col]=le.fit_transform(df[col])for col in df.columns: df[col]=df[col].astype(float) For more information on label encoding using python, you can view the documentation Table of contents Now that our data is prepared, we will have to split the data into two sets for reasons described above To accomplish this, we will first assign the X values to everything but the output feature (aka all the inputs) Next, we assign y values to the price_bin feature; our modification of the price feature Finally, we assign X_train and y_train together as a “matching dataset” and do the same for X_test and y_test We will then fit a model using X_train and its outputs y_train and validate the model by comparing predictions based on X_test to actual output of y_test X = df.drop(['price','price_bin'],axis=1)y = df.price_binX_train, X_test, y_train, y_test = train_test_split(X,y) For more information on train_test_split, you can view the documentation Table of contents Ok, take a breath; we’ve finally made it to the data balancing We see below the distribution of the target class in our data in both train and initial sets What we see here is that the lowest we can go for each class to be equal is around 2000 I’m going to go with 1500 though Using make_imbalance from imblearn, we can easily just delete rows to balance the classes (more information on this process can be found at the documentation) I will store these new values into X_train_1 and y_train_1 so we can see which method works best at the end when we run all the models Having balanced our data, let’s see the outcome by running the following code y_train_1.value_counts().plot(kind='bar')plt.title('label balance')plt.xlabel('label values')plt.ylabel('amount per label')plt.show() For method two, we will copy existing rows of minority classes using resample from sklearn.utils I wrote the function below to help you easily accomplish this task (but the key part of the function is the resample import and information on this function can be found at the documentation) There is, however, a prerequisite that you need to combine X_train with y_train and only then upsample classes Creating upsample_classes function Input is data and what the target feature from that data is Output is a balanced dataset First, we make a list of unique labels in data Next, we split up the rows of data by their labels into different sets of data Next, we search for the majority class label Next, we get the classes back together using pandas.concat (more on this function can be found at the documentation) and separate off the majority class based on it’s newly found label Next, we remove the majority class and upsample the other classes to match the length of the majority class Finally, we combine the majority class with the other classes, which are now of equal length This function is very simple due to the fact that there are only two inputs Let’s see how to turn this into new sets of X_train and y_train train = pd.concat([X_train,y_train],axis=1)train_balanced = (upsample_classes(train,'price_bin'))X_train_2 = train_balanced.drop(['price_bin'],axis=1)y_train_2 = train_balanced.price_bin Outcome Visual y_train_2.value_counts().plot(kind='bar')plt.title('label balance')plt.xlabel('label values')plt.ylabel('amount per label')plt.show() While the actual calculations and backend for SMOTE are beyond the scope of this post (but is discussed elsewhere on the internet), we will use python and its libraries to leverage the SMOTE technique with only a couple lines of code (Doken, S) Recall that SMOTE can be thought of a way of synthetically generating new data based on what other rows of data may imply All you need for SMOTE is two lines of code and you can learn more about the specifics of SMOTE in python at the documentation smote = SMOTE(random_state = 14)X_train_3, y_train_3 = smote.fit_sample(X_train, y_train) Now you have balance in the target class, as we will see below y_train_3.value_counts().plot(kind='bar')plt.title('label balance')plt.xlabel('label values')plt.ylabel('amount per label')plt.show() That wasn’t too bad! Table of contents We need to start this section with a disclaimer: the dataset here is a fairly simple dataset and contains few features. Just because some models paired with different data balancing methods may work here in certain ways here, they may look different in different datasets and different scenarios We start by instantiating our modeling technique (my lucky number is 14) We will also only use XGBoost for uniformity purposes (and it works very well, anyway) To learn more about XGBoost classifiers in python, you can view the documentation xgbc=XGBClassifier(random_state=14) To make life easy and to avoid writing everything over and over again, I will also create the following function Creating classification function Input train data, test data, and a model type Start by fitting model on train data Assign prediction variables for train and test set Due to class imbalance in test data, display f1 score for train and test predictions using scikit-learn’s built in metrics library (more information on F1 score can be found at the documentation) Display a confusion matrix for performance of test data (more information on confusion matrices in python can be found at the documentation) Let’s run through the results It looks like we consistently improved our models as we progressed to more advanced methods of data balancing Table of contents I mainly ask this question as it will help reinforce what we saw above and instill confidence that our models are very strong Below, we start by balancing the test data test = pd.concat([X_test,y_test],axis=1)test_balanced = (upsample_classes(test,'price_bin'))X_test_b = test_balanced.drop('price_bin',axis=1)y_test_b = test_balanced.price_bin Below are the new outcomes following data balancing Interestingly, method 2 slightly overtook SMOTE but SMOTE still managed to beat the most simple of the three options What we see here essentially confirms our observations above You may wonder what will happen as we introduce new data from each of the 4 diamond classes Above, we see what that would look like Table of contents Balancing data is often a key part of the data science process in classification algorithms. Conveniently, there are very simple, efficient, and effective ways to perform this crucial task. We saw the various types of ways and discussed the benefits and drawbacks of each style. We also explored the coding process we would use in python. I hope this post will help readers in their statistical inquiries to generate meaningful insights. Table of contents Rane, C (2018). Diamonds In-Depth Analysis. Retrieved from https://www.kaggle.com/fuzzywizard/diamonds-in-depth-analysis Testing Classification on Oversampled Imbalance Data.Retrieved from https://stats.stackexchange.com/questions/60180/testing-classification-on-oversampled-imbalance-data Brwonlee, J (2020, January 17). SMOTE for Imbalanced Classification with Python. Retrieved from https://machinelearningmastery.com/smote-oversampling-for-imbalanced-classification/ Paul, S (2018, October 04). Diving Deep with Imbalanced Data. Retrieved from https://www.datacamp.com/community/tutorials/diving-deep-imbalanced-data Murali, A (2018, May 31). Embed Code in Medium. Retrieved from: https://medium.com/@aryamurali/embed-code-in-medium-e95b839cfdda Mahendru, K (2019, June 24). How to Deal with Imbalanced Data using SMOTE. Retrieved from https://medium.com/analytics-vidhya/balance-your-data-using-smote-98e4d79fcddb Allien, M (2019, January 10). Creating Table of Contents for Medium Articles. Retrieved from https://medium.com/@AllienWorks/creating-table-of-contents-for-medium-articles-5f9087377b82#dc26 Doken, S (2017, November 06). SMOTE explained for noobs — Synthetic Minority Over-sampling Technique line by line. Retrieved from https://rikunert.com/SMOTE_explained Lusa, L and Blagus, R (2013, March 22). Retrieved from: https://www.datacamp.com/community/tutorials/diving-deep-imbalanced-data Table of contents
[ { "code": null, "e": 379, "s": 172, "text": "IntroductionWhat is train data?Why do we need to balance train data?What does “balancing data” actually look like in practice?Do we also need to balance test data?Evaluation metrics for imbalanced test data" }, { "code": null, "e": 392, "s": 379, "text": "Introduction" }, { "code": null, "e": 412, "s": 392, "text": "What is train data?" }, { "code": null, "e": 450, "s": 412, "text": "Why do we need to balance train data?" }, { "code": null, "e": 509, "s": 450, "text": "What does “balancing data” actually look like in practice?" }, { "code": null, "e": 547, "s": 509, "text": "Do we also need to balance test data?" }, { "code": null, "e": 591, "s": 547, "text": "Evaluation metrics for imbalanced test data" }, { "code": null, "e": 771, "s": 591, "text": "SetupInitial feature engineeringModel purpose transformationAddressing categorical featuresTrain test splitData balancingModelsWhat if we balance the test data?ConclusionResources" }, { "code": null, "e": 777, "s": 771, "text": "Setup" }, { "code": null, "e": 805, "s": 777, "text": "Initial feature engineering" }, { "code": null, "e": 834, "s": 805, "text": "Model purpose transformation" }, { "code": null, "e": 866, "s": 834, "text": "Addressing categorical features" }, { "code": null, "e": 883, "s": 866, "text": "Train test split" }, { "code": null, "e": 898, "s": 883, "text": "Data balancing" }, { "code": null, "e": 905, "s": 898, "text": "Models" }, { "code": null, "e": 939, "s": 905, "text": "What if we balance the test data?" }, { "code": null, "e": 950, "s": 939, "text": "Conclusion" }, { "code": null, "e": 960, "s": 950, "text": "Resources" }, { "code": null, "e": 1325, "s": 960, "text": "The goal of this post is to teach python programmers why they must have balanced data for model training and how to balance those data sets. Often times, in machine learning classification problems, models will not work as well and be incomplete without performing data balancing on train data. This post will serve as an end-to-end guide for solving this problem." }, { "code": null, "e": 1343, "s": 1325, "text": "Table of contents" }, { "code": null, "e": 1895, "s": 1343, "text": "Before running a model, you need to fit the model on a set of data that is distinct from the data you test it on. In other words, if you create a model based on one pool of data and run that same pool of data back through the model, and the model performs well, you likely haven’t built anything exciting or proven anything. Therefore, a common way to generate extra data is to cut off a random segment of the total data, and use the remaining data for model training and go back to the cut off (and smaller) set of data for model validation purposes." }, { "code": null, "e": 1913, "s": 1895, "text": "Table of contents" }, { "code": null, "e": 2981, "s": 1913, "text": "I am a strong believer in using extreme examples to prove points. In this case, I’d like to provide the following example to demonstrate why data balance matters in classification algorithms: say you are trying to predict whether a certain disease is likely to occur for a given person. Let’s focus on the output here, meaning the y-value we are trying to predict via our numerous features. Make up all the features you want to use as they won’t matter in a second. If we had 500 data points and 499 showed healthy people while 1 showed a diseased person and our model had 100% accuracy... well it doesn’t prove a whole lot. In fact, it proves just as much as a 99.99% accurate model where the one error was in the diseased person predicted as healthy. Having a 499-to-1 distribution of data points just doesn’t cut it as we don’t have the required level of data to develop an understanding of what may lead to disease. Balancing data gives us the same amount of information to help predict each class and therefore gives a better idea of how to respond to test data." }, { "code": null, "e": 2999, "s": 2981, "text": "Table of contents" }, { "code": null, "e": 3171, "s": 2999, "text": "There are a couple ways to think through balancing data. I will talk about three in particular. I’ll start by discussing the ideas here and later share the coding process." }, { "code": null, "e": 3185, "s": 3171, "text": "Example data:" }, { "code": null, "e": 3215, "s": 3185, "text": "10 rows of data with label A." }, { "code": null, "e": 3245, "s": 3215, "text": "12 rows of data with label B." }, { "code": null, "e": 3275, "s": 3245, "text": "14 rows of data with label C." }, { "code": null, "e": 3445, "s": 3275, "text": "Method 1: Under-sampling; Delete some data from rows of data from the majority classes. In this case, delete 2 rows resulting in label B and 4 rows resulting in label C." }, { "code": null, "e": 3573, "s": 3445, "text": "Limitation: This is hard to use when you don’t have a substantial (and relatively equal) amount of data from each target class." }, { "code": null, "e": 3737, "s": 3573, "text": "Method 2: Copy rows of data resulting minority labels. In this case, copy 4 rows with label A and 2 rows with label B to add a total of 6 new rows to the data set." }, { "code": null, "e": 3922, "s": 3737, "text": "Limitation: I think the limitation here is pretty clear. All you are really doing is copying current data and you don’t really present anything new. You will get better models, though." }, { "code": null, "e": 4481, "s": 3922, "text": "Method 3: (SMOTE - Synthetic Minority Oversampling Technique) Synthetically generate new data based on implications of old data. Basically, instead of deleting or copying data, you use the current inputs to generate new input rows that are unique but will have a label based on what the original data implies. In the case above, one simple way to think of this idea would be to add 4 rows with label A to the data where the inputs represent total or partial similarities in values to current input features. Repeat this process for 2 rows of label B as well." }, { "code": null, "e": 4761, "s": 4481, "text": "Limitation: If two different class labels have common neighboring examples, it may be hard to generate accurate data representing what each unique label may look like from the input side and therefore SMOTE struggles with higher dimensionality data (Lusa, L and Blagus, R, 2013)." }, { "code": null, "e": 4779, "s": 4761, "text": "Table of contents" }, { "code": null, "e": 5321, "s": 4779, "text": "Usually, this is something we don’t do. You can sometimes upsample test data anyway just to see if your model works well on minority classes as well. What’s most important to keep in mind is that you don’t want to upsample data and only then do a data split into train and test set. This will likely result in having elements of train data copied perfectly into test data and artificially boost your model scores. The only time you would ever upsample test data is after a data split, just like you only perform data balancing on train data." }, { "code": null, "e": 5339, "s": 5321, "text": "Table of contents" }, { "code": null, "e": 6225, "s": 5339, "text": "If we have a strong imbalance in test data, we still have ways of understanding how well our model performs outside of the accuracy metric. Accuracy, our intuitive and classic metric, is actually only a measure of wrong-or-right for every single observation. It does not take into account how many of each label are included in the data and works best with relatively balanced data (or in cases where correct predictions are more important regardless of the distribution of the various outcomes in the target feature). Having alternative metrics is less of a reason as to why you shouldn’t balance test data, but more of a reason why you might not need to balance test data. Let’s look at three metrics that are effective in the context of binary classification algorithm (they are also relevant for non-binary problems, but binary problems provide the easiest method of illustration)." }, { "code": null, "e": 6235, "s": 6225, "text": "Precision" }, { "code": null, "e": 6806, "s": 6235, "text": "Precision is a measure that tells you how meaningful a positive (target class = 1) is. This is accomplished by dividing the number of correct positive predictions over total number of positive predictions (true positive divided by sum of false positives and true positives). Say you are predicting disease and have 400 healthy people and 100 diseased people. If you predict all 500 cases to be diseased, you have correctly identified every case of disease, but your model is rather meaningless as you always have the same outcome and you misidentified 80% of the inputs." }, { "code": null, "e": 6813, "s": 6806, "text": "Recall" }, { "code": null, "e": 7896, "s": 6813, "text": "Recall is very similar to precision. The denominator in recall, however, is composed of true positives and false negatives, while the numerator remains true positives. This shifts our focus from how much a positive score actually matters, to an understanding of how effective our model is at identifying any positive case that is present (because a false negative is actually a positive). As the number of false negatives grow, there is no increase to the numerator of true positives, and the recall gets lower and lower. Let’s use the precision example again. If you predict 500 patients to be diseased when only 100 are actually diseased, you will have high recall as there are no false negatives. However, if you go to the other extreme and say everyone is healthy, then all the sudden you have 80% accuracy and no false positives but you failed to identify 100% of the diseased people. You may notice that in the case where everyone is predicted to be sick that precision is low while recall is high. There is in fact a moderate tradeoff between optimizing precision and recall." }, { "code": null, "e": 7905, "s": 7896, "text": "F1-Score" }, { "code": null, "e": 8265, "s": 7905, "text": "The F1-Score is the perfect way in which we can get a better sense of model performance when we have imbalanced data since accuracy alone isn’t a good metric. F1-Score is a harmonic average (max value is the arithmetic mean) of the precision and recall score. Having a blend of precision and recall gives us a strong idea of how well the model actually works." }, { "code": null, "e": 8283, "s": 8265, "text": "Table of contents" }, { "code": null, "e": 8406, "s": 8283, "text": "The data I will be using for demonstration can be found at kaggle.com at this link and deals with diamond price prediction" }, { "code": null, "e": 8519, "s": 8406, "text": "The code below will take you through the entire process; from beginning imports and data preparation to modeling" }, { "code": null, "e": 8537, "s": 8519, "text": "Install libraries" }, { "code": null, "e": 8618, "s": 8537, "text": "!pip install -U scikit-learn!pip install -U imbalanced-learn!pip install xgboost" }, { "code": null, "e": 8645, "s": 8618, "text": "Import necessary libraries" }, { "code": null, "e": 9733, "s": 8645, "text": "# remove warningsimport warningswarnings.filterwarnings('ignore')# standard imports and setupimport pandas as pdimport numpy as npimport matplotlib.pyplot as plt%matplotlib inlineimport seaborn as snsfrom scipy import stats# model evaluationfrom sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV, ShuffleSplitfrom sklearn.metrics import *# pipelinesfrom sklearn.compose import make_column_transformerfrom sklearn.pipeline import Pipeline, make_pipeline# data preparationfrom sklearn.preprocessing import *from sklearn.decomposition import PCAfrom sklearn.feature_selection import RFE, RFECVfrom sklearn.utils import resamplefrom imblearn.datasets import make_imbalancefrom imblearn.over_sampling import SMOTE# machine learningfrom sklearn.linear_model import *from sklearn.neighbors import KNeighborsClassifierfrom sklearn.svm import SVC, LinearSVCfrom sklearn.naive_bayes import GaussianNBfrom sklearn.ensemble import RandomForestClassifier, RandomForestRegressorfrom sklearn.tree import DecisionTreeClassifierfrom xgboost import XGBClassifier, XGBRegressor" }, { "code": null, "e": 9755, "s": 9733, "text": "Read and preview data" }, { "code": null, "e": 9810, "s": 9755, "text": "df=pd.read_csv('diamonds.csv')print(df.shape)df.head()" }, { "code": null, "e": 9870, "s": 9810, "text": "Drop “Unnamed: 0” as it is useless and look for null values" }, { "code": null, "e": 9931, "s": 9870, "text": "While looking for null values, get a feel for the data types" }, { "code": null, "e": 9984, "s": 9931, "text": "df.drop('Unnamed: 0', axis=1, inplace=True)df.info()" }, { "code": null, "e": 10018, "s": 9984, "text": "There appear to be no null values" }, { "code": null, "e": 10036, "s": 10018, "text": "Table of contents" }, { "code": null, "e": 10088, "s": 10036, "text": "Next, we will quickly do some feature modifications" }, { "code": null, "e": 10395, "s": 10088, "text": "You may notice that the product of x, y, and z (according to the kaggle link) correspond to volume. We can add a feature called volume to equal this product and remove x, y, and z. I’d like to credit Chinmay Rane for this idea as I saw it in his kaggle notebook which can be found at this link (Rane, 2018)" }, { "code": null, "e": 10467, "s": 10395, "text": "df['volume'] = df.x*df.y*df.zdf.drop(['x','z','y'],axis=1,inplace=True)" }, { "code": null, "e": 10497, "s": 10467, "text": "What does new data look like?" }, { "code": null, "e": 10515, "s": 10497, "text": "Table of contents" }, { "code": null, "e": 10715, "s": 10515, "text": "You may notice that the data above present our target feature of price as a continuous variable, but we can establish sets of intervals in the target feature to morph it into a classification problem" }, { "code": null, "e": 10864, "s": 10715, "text": "The plan is as follows: we will split the target feature into various intervals of values, and I like picking four unique intervals for this problem" }, { "code": null, "e": 10921, "s": 10864, "text": "Those intervals are as follows (along with value counts)" }, { "code": null, "e": 11062, "s": 10921, "text": "Pandas has a built in function to break things down into bins and you can even have a 1:1 ratio from each bin size to the next using pd.qcut" }, { "code": null, "e": 11132, "s": 11062, "text": "We still have a problem as it is a bit of a pain to look at intervals" }, { "code": null, "e": 11206, "s": 11132, "text": "Thankfully, Pandas let’s users create default labels as I will show below" }, { "code": null, "e": 11263, "s": 11206, "text": "df['price_bin']=pd.cut(df.price,bins=4,labels=[0,1,2,3])" }, { "code": null, "e": 11314, "s": 11263, "text": "Now, look at data below from the first couple rows" }, { "code": null, "e": 11395, "s": 11314, "text": "You may notice that the most common label above is 0 and that is reflected below" }, { "code": null, "e": 11540, "s": 11395, "text": "For more information on the built-in functions used above, you can view documentation for pandas.cut here and documentation for pandas.qcut here" }, { "code": null, "e": 11558, "s": 11540, "text": "Table of contents" }, { "code": null, "e": 11710, "s": 11558, "text": "We now are looking at a classification problem, but there is still the problem of the features cut, color, and clarity which do not have numeric values" }, { "code": null, "e": 11849, "s": 11710, "text": "To solve this problem we will use label encoding which is a method of assigning a numeric label for unique value of a categorical variable" }, { "code": null, "e": 11988, "s": 11849, "text": "I actually prefer target encoding, but don’t believe target encoding is the most “fair” approximation with very few input features present" }, { "code": null, "e": 12073, "s": 11988, "text": "After encoding labels, we will do a double check to ensure our data is of type float" }, { "code": null, "e": 12234, "s": 12073, "text": "le = LabelEncoder()for col in df.select_dtypes(include='O').columns: df[col]=le.fit_transform(df[col])for col in df.columns: df[col]=df[col].astype(float)" }, { "code": null, "e": 12318, "s": 12234, "text": "For more information on label encoding using python, you can view the documentation" }, { "code": null, "e": 12336, "s": 12318, "text": "Table of contents" }, { "code": null, "e": 12440, "s": 12336, "text": "Now that our data is prepared, we will have to split the data into two sets for reasons described above" }, { "code": null, "e": 12552, "s": 12440, "text": "To accomplish this, we will first assign the X values to everything but the output feature (aka all the inputs)" }, { "code": null, "e": 12641, "s": 12552, "text": "Next, we assign y values to the price_bin feature; our modification of the price feature" }, { "code": null, "e": 12751, "s": 12641, "text": "Finally, we assign X_train and y_train together as a “matching dataset” and do the same for X_test and y_test" }, { "code": null, "e": 12905, "s": 12751, "text": "We will then fit a model using X_train and its outputs y_train and validate the model by comparing predictions based on X_test to actual output of y_test" }, { "code": null, "e": 13019, "s": 12905, "text": "X = df.drop(['price','price_bin'],axis=1)y = df.price_binX_train, X_test, y_train, y_test = train_test_split(X,y)" }, { "code": null, "e": 13092, "s": 13019, "text": "For more information on train_test_split, you can view the documentation" }, { "code": null, "e": 13110, "s": 13092, "text": "Table of contents" }, { "code": null, "e": 13173, "s": 13110, "text": "Ok, take a breath; we’ve finally made it to the data balancing" }, { "code": null, "e": 13266, "s": 13173, "text": "We see below the distribution of the target class in our data in both train and initial sets" }, { "code": null, "e": 13354, "s": 13266, "text": "What we see here is that the lowest we can go for each class to be equal is around 2000" }, { "code": null, "e": 13387, "s": 13354, "text": "I’m going to go with 1500 though" }, { "code": null, "e": 13546, "s": 13387, "text": "Using make_imbalance from imblearn, we can easily just delete rows to balance the classes (more information on this process can be found at the documentation)" }, { "code": null, "e": 13681, "s": 13546, "text": "I will store these new values into X_train_1 and y_train_1 so we can see which method works best at the end when we run all the models" }, { "code": null, "e": 13759, "s": 13681, "text": "Having balanced our data, let’s see the outcome by running the following code" }, { "code": null, "e": 13893, "s": 13759, "text": "y_train_1.value_counts().plot(kind='bar')plt.title('label balance')plt.xlabel('label values')plt.ylabel('amount per label')plt.show()" }, { "code": null, "e": 13990, "s": 13893, "text": "For method two, we will copy existing rows of minority classes using resample from sklearn.utils" }, { "code": null, "e": 14182, "s": 13990, "text": "I wrote the function below to help you easily accomplish this task (but the key part of the function is the resample import and information on this function can be found at the documentation)" }, { "code": null, "e": 14293, "s": 14182, "text": "There is, however, a prerequisite that you need to combine X_train with y_train and only then upsample classes" }, { "code": null, "e": 14328, "s": 14293, "text": "Creating upsample_classes function" }, { "code": null, "e": 14388, "s": 14328, "text": "Input is data and what the target feature from that data is" }, { "code": null, "e": 14417, "s": 14388, "text": "Output is a balanced dataset" }, { "code": null, "e": 14464, "s": 14417, "text": "First, we make a list of unique labels in data" }, { "code": null, "e": 14543, "s": 14464, "text": "Next, we split up the rows of data by their labels into different sets of data" }, { "code": null, "e": 14588, "s": 14543, "text": "Next, we search for the majority class label" }, { "code": null, "e": 14773, "s": 14588, "text": "Next, we get the classes back together using pandas.concat (more on this function can be found at the documentation) and separate off the majority class based on it’s newly found label" }, { "code": null, "e": 14881, "s": 14773, "text": "Next, we remove the majority class and upsample the other classes to match the length of the majority class" }, { "code": null, "e": 14974, "s": 14881, "text": "Finally, we combine the majority class with the other classes, which are now of equal length" }, { "code": null, "e": 15050, "s": 14974, "text": "This function is very simple due to the fact that there are only two inputs" }, { "code": null, "e": 15114, "s": 15050, "text": "Let’s see how to turn this into new sets of X_train and y_train" }, { "code": null, "e": 15301, "s": 15114, "text": "train = pd.concat([X_train,y_train],axis=1)train_balanced = (upsample_classes(train,'price_bin'))X_train_2 = train_balanced.drop(['price_bin'],axis=1)y_train_2 = train_balanced.price_bin" }, { "code": null, "e": 15309, "s": 15301, "text": "Outcome" }, { "code": null, "e": 15316, "s": 15309, "text": "Visual" }, { "code": null, "e": 15450, "s": 15316, "text": "y_train_2.value_counts().plot(kind='bar')plt.title('label balance')plt.xlabel('label values')plt.ylabel('amount per label')plt.show()" }, { "code": null, "e": 15695, "s": 15450, "text": "While the actual calculations and backend for SMOTE are beyond the scope of this post (but is discussed elsewhere on the internet), we will use python and its libraries to leverage the SMOTE technique with only a couple lines of code (Doken, S)" }, { "code": null, "e": 15817, "s": 15695, "text": "Recall that SMOTE can be thought of a way of synthetically generating new data based on what other rows of data may imply" }, { "code": null, "e": 15944, "s": 15817, "text": "All you need for SMOTE is two lines of code and you can learn more about the specifics of SMOTE in python at the documentation" }, { "code": null, "e": 16034, "s": 15944, "text": "smote = SMOTE(random_state = 14)X_train_3, y_train_3 = smote.fit_sample(X_train, y_train)" }, { "code": null, "e": 16097, "s": 16034, "text": "Now you have balance in the target class, as we will see below" }, { "code": null, "e": 16231, "s": 16097, "text": "y_train_3.value_counts().plot(kind='bar')plt.title('label balance')plt.xlabel('label values')plt.ylabel('amount per label')plt.show()" }, { "code": null, "e": 16252, "s": 16231, "text": "That wasn’t too bad!" }, { "code": null, "e": 16270, "s": 16252, "text": "Table of contents" }, { "code": null, "e": 16566, "s": 16270, "text": "We need to start this section with a disclaimer: the dataset here is a fairly simple dataset and contains few features. Just because some models paired with different data balancing methods may work here in certain ways here, they may look different in different datasets and different scenarios" }, { "code": null, "e": 16639, "s": 16566, "text": "We start by instantiating our modeling technique (my lucky number is 14)" }, { "code": null, "e": 16726, "s": 16639, "text": "We will also only use XGBoost for uniformity purposes (and it works very well, anyway)" }, { "code": null, "e": 16808, "s": 16726, "text": "To learn more about XGBoost classifiers in python, you can view the documentation" }, { "code": null, "e": 16844, "s": 16808, "text": "xgbc=XGBClassifier(random_state=14)" }, { "code": null, "e": 16957, "s": 16844, "text": "To make life easy and to avoid writing everything over and over again, I will also create the following function" }, { "code": null, "e": 16990, "s": 16957, "text": "Creating classification function" }, { "code": null, "e": 17036, "s": 16990, "text": "Input train data, test data, and a model type" }, { "code": null, "e": 17073, "s": 17036, "text": "Start by fitting model on train data" }, { "code": null, "e": 17124, "s": 17073, "text": "Assign prediction variables for train and test set" }, { "code": null, "e": 17320, "s": 17124, "text": "Due to class imbalance in test data, display f1 score for train and test predictions using scikit-learn’s built in metrics library (more information on F1 score can be found at the documentation)" }, { "code": null, "e": 17461, "s": 17320, "text": "Display a confusion matrix for performance of test data (more information on confusion matrices in python can be found at the documentation)" }, { "code": null, "e": 17491, "s": 17461, "text": "Let’s run through the results" }, { "code": null, "e": 17601, "s": 17491, "text": "It looks like we consistently improved our models as we progressed to more advanced methods of data balancing" }, { "code": null, "e": 17619, "s": 17601, "text": "Table of contents" }, { "code": null, "e": 17745, "s": 17619, "text": "I mainly ask this question as it will help reinforce what we saw above and instill confidence that our models are very strong" }, { "code": null, "e": 17788, "s": 17745, "text": "Below, we start by balancing the test data" }, { "code": null, "e": 17964, "s": 17788, "text": "test = pd.concat([X_test,y_test],axis=1)test_balanced = (upsample_classes(test,'price_bin'))X_test_b = test_balanced.drop('price_bin',axis=1)y_test_b = test_balanced.price_bin" }, { "code": null, "e": 18016, "s": 17964, "text": "Below are the new outcomes following data balancing" }, { "code": null, "e": 18133, "s": 18016, "text": "Interestingly, method 2 slightly overtook SMOTE but SMOTE still managed to beat the most simple of the three options" }, { "code": null, "e": 18194, "s": 18133, "text": "What we see here essentially confirms our observations above" }, { "code": null, "e": 18286, "s": 18194, "text": "You may wonder what will happen as we introduce new data from each of the 4 diamond classes" }, { "code": null, "e": 18326, "s": 18286, "text": "Above, we see what that would look like" }, { "code": null, "e": 18344, "s": 18326, "text": "Table of contents" }, { "code": null, "e": 18782, "s": 18344, "text": "Balancing data is often a key part of the data science process in classification algorithms. Conveniently, there are very simple, efficient, and effective ways to perform this crucial task. We saw the various types of ways and discussed the benefits and drawbacks of each style. We also explored the coding process we would use in python. I hope this post will help readers in their statistical inquiries to generate meaningful insights." }, { "code": null, "e": 18800, "s": 18782, "text": "Table of contents" }, { "code": null, "e": 18921, "s": 18800, "text": "Rane, C (2018). Diamonds In-Depth Analysis. Retrieved from https://www.kaggle.com/fuzzywizard/diamonds-in-depth-analysis" }, { "code": null, "e": 19090, "s": 18921, "text": "Testing Classification on Oversampled Imbalance Data.Retrieved from https://stats.stackexchange.com/questions/60180/testing-classification-on-oversampled-imbalance-data" }, { "code": null, "e": 19271, "s": 19090, "text": "Brwonlee, J (2020, January 17). SMOTE for Imbalanced Classification with Python. Retrieved from https://machinelearningmastery.com/smote-oversampling-for-imbalanced-classification/" }, { "code": null, "e": 19421, "s": 19271, "text": "Paul, S (2018, October 04). Diving Deep with Imbalanced Data. Retrieved from https://www.datacamp.com/community/tutorials/diving-deep-imbalanced-data" }, { "code": null, "e": 19550, "s": 19421, "text": "Murali, A (2018, May 31). Embed Code in Medium. Retrieved from: https://medium.com/@aryamurali/embed-code-in-medium-e95b839cfdda" }, { "code": null, "e": 19719, "s": 19550, "text": "Mahendru, K (2019, June 24). How to Deal with Imbalanced Data using SMOTE. Retrieved from https://medium.com/analytics-vidhya/balance-your-data-using-smote-98e4d79fcddb" }, { "code": null, "e": 19909, "s": 19719, "text": "Allien, M (2019, January 10). Creating Table of Contents for Medium Articles. Retrieved from https://medium.com/@AllienWorks/creating-table-of-contents-for-medium-articles-5f9087377b82#dc26" }, { "code": null, "e": 20076, "s": 19909, "text": "Doken, S (2017, November 06). SMOTE explained for noobs — Synthetic Minority Over-sampling Technique line by line. Retrieved from https://rikunert.com/SMOTE_explained" }, { "code": null, "e": 20205, "s": 20076, "text": "Lusa, L and Blagus, R (2013, March 22). Retrieved from: https://www.datacamp.com/community/tutorials/diving-deep-imbalanced-data" } ]
jQuery UI Sortable sort Event
13 Dec, 2021 jQuery UI consists of GUI widgets, visual effects, and themes implemented using Query JavaScript Library. jQuery UI is great for building UI interfaces for the webpages. It can be used to build highly interactive web applications or can be used to add widgets easily. The jQuery UI Sortable sort event is used to trigger during the list items sorting. Syntax: Initialize the sortable widget with the sort callback function:$(".selector").selectable({ sort: function( event, ui ) {} }); Initialize the sortable widget with the sort callback function: $(".selector").selectable({ sort: function( event, ui ) {} }); Bind an event listener to the sort event:$( ".selector" ).on( "sort", function( event, ui ) {} ); Bind an event listener to the sort event: $( ".selector" ).on( "sort", function( event, ui ) {} ); Parameters: event: This event is triggered when the user stopped the sorting with a position change of DOM. ui: This is of type object with below-given options.helper: The jQuery object representing the sorted helper.item: The jQuery object representing the current dragged item.offset: The current absolute position of the helper object which is represented as { top, left }.position: The current position of the helper object which is represented as { top, left }.originalPosition: The original position of the helper object which is represented as { top, left }. helper: The jQuery object representing the sorted helper. item: The jQuery object representing the current dragged item. offset: The current absolute position of the helper object which is represented as { top, left }. position: The current position of the helper object which is represented as { top, left }. originalPosition: The original position of the helper object which is represented as { top, left }. CDN Link: First, add jQuery UI scripts needed for your project. <link rel=”stylesheet” href=”//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css”><script src=”//code.jquery.com/jquery-1.12.4.js”></script><script src=”//code.jquery.com/ui/1.12.1/jquery-ui.js”></script> Example: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="https//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"> </script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"> </script> <style> #sortable { list-style-type: none; width: 50%; } #sortable li { margin: 10px 0; padding: 0.5em; font-size: 25px; height: 20px; } </style> <script> $(function () { $("#sortable").sortable({ sort: function( event, ui ) { alert("Sort Event Triggered!") } }); }); </script></head> <body> <center> <h1 style="color: green;"> GeeksforGeeks </h1> <h4>jQuery UI Sortable sort Event</h4> <ul id="sortable"> <li class="ui-state-default">BCD</li> <li class="ui-state-default">CAB</li> <li class="ui-state-default">BAC</li> <li class="ui-state-default">BCA</li> <li class="ui-state-default">ABC</li> </ul> </center></body> </html> Output: Reference: https://api.jqueryui.com/sortable/#event-sort jQuery-UI Picked JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Dec, 2021" }, { "code": null, "e": 296, "s": 28, "text": "jQuery UI consists of GUI widgets, visual effects, and themes implemented using Query JavaScript Library. jQuery UI is great for building UI interfaces for the webpages. It can be used to build highly interactive web applications or can be used to add widgets easily." }, { "code": null, "e": 380, "s": 296, "text": "The jQuery UI Sortable sort event is used to trigger during the list items sorting." }, { "code": null, "e": 388, "s": 380, "text": "Syntax:" }, { "code": null, "e": 518, "s": 388, "text": "Initialize the sortable widget with the sort callback function:$(\".selector\").selectable({\n sort: function( event, ui ) {}\n});" }, { "code": null, "e": 582, "s": 518, "text": "Initialize the sortable widget with the sort callback function:" }, { "code": null, "e": 649, "s": 582, "text": "$(\".selector\").selectable({\n sort: function( event, ui ) {}\n});" }, { "code": null, "e": 749, "s": 651, "text": "Bind an event listener to the sort event:$( \".selector\" ).on( \"sort\", function( event, ui ) {} );" }, { "code": null, "e": 791, "s": 749, "text": "Bind an event listener to the sort event:" }, { "code": null, "e": 848, "s": 791, "text": "$( \".selector\" ).on( \"sort\", function( event, ui ) {} );" }, { "code": null, "e": 860, "s": 848, "text": "Parameters:" }, { "code": null, "e": 956, "s": 860, "text": "event: This event is triggered when the user stopped the sorting with a position change of DOM." }, { "code": null, "e": 1414, "s": 956, "text": "ui: This is of type object with below-given options.helper: The jQuery object representing the sorted helper.item: The jQuery object representing the current dragged item.offset: The current absolute position of the helper object which is represented as { top, left }.position: The current position of the helper object which is represented as { top, left }.originalPosition: The original position of the helper object which is represented as { top, left }." }, { "code": null, "e": 1472, "s": 1414, "text": "helper: The jQuery object representing the sorted helper." }, { "code": null, "e": 1535, "s": 1472, "text": "item: The jQuery object representing the current dragged item." }, { "code": null, "e": 1633, "s": 1535, "text": "offset: The current absolute position of the helper object which is represented as { top, left }." }, { "code": null, "e": 1724, "s": 1633, "text": "position: The current position of the helper object which is represented as { top, left }." }, { "code": null, "e": 1824, "s": 1724, "text": "originalPosition: The original position of the helper object which is represented as { top, left }." }, { "code": null, "e": 1888, "s": 1824, "text": "CDN Link: First, add jQuery UI scripts needed for your project." }, { "code": null, "e": 2101, "s": 1888, "text": "<link rel=”stylesheet” href=”//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css”><script src=”//code.jquery.com/jquery-1.12.4.js”></script><script src=”//code.jquery.com/ui/1.12.1/jquery-ui.js”></script>" }, { "code": null, "e": 2110, "s": 2101, "text": "Example:" }, { "code": null, "e": 2115, "s": 2110, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <link rel=\"stylesheet\" href=\"https//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\"> <script src=\"https://code.jquery.com/jquery-1.12.4.js\"> </script> <script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"> </script> <style> #sortable { list-style-type: none; width: 50%; } #sortable li { margin: 10px 0; padding: 0.5em; font-size: 25px; height: 20px; } </style> <script> $(function () { $(\"#sortable\").sortable({ sort: function( event, ui ) { alert(\"Sort Event Triggered!\") } }); }); </script></head> <body> <center> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <h4>jQuery UI Sortable sort Event</h4> <ul id=\"sortable\"> <li class=\"ui-state-default\">BCD</li> <li class=\"ui-state-default\">CAB</li> <li class=\"ui-state-default\">BAC</li> <li class=\"ui-state-default\">BCA</li> <li class=\"ui-state-default\">ABC</li> </ul> </center></body> </html>", "e": 3361, "s": 2115, "text": null }, { "code": null, "e": 3369, "s": 3361, "text": "Output:" }, { "code": null, "e": 3426, "s": 3369, "text": "Reference: https://api.jqueryui.com/sortable/#event-sort" }, { "code": null, "e": 3436, "s": 3426, "text": "jQuery-UI" }, { "code": null, "e": 3443, "s": 3436, "text": "Picked" }, { "code": null, "e": 3450, "s": 3443, "text": "JQuery" }, { "code": null, "e": 3467, "s": 3450, "text": "Web Technologies" } ]
Implement multiple LIKE operators in a single MySQL query
To implement multiple LIKE clauses, the syntax is as follows − select * from yourTableName where yourColumnName1 LIKE ('%yourValue1%' or yourColumnName2 LIKE '%yourValue2%') or (yourColumnName3 LIKE '%yourValue3'); Let us first create a table − mysql> create table DemoTable1534 -> ( -> ClientId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> ClientName varchar(20), -> ClientAge int, -> ClientCountryName varchar(20) -> ); Query OK, 0 rows affected (0.78 sec) Insert some records in the table using insert command − mysql> insert into DemoTable1534(ClientName,ClientAge,ClientCountryName) values('Chris Brown',29,'AUS'); Query OK, 1 row affected (0.21 sec) mysql> insert into DemoTable1534(ClientName,ClientAge,ClientCountryName) values('David Miller',49,'UK'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable1534(ClientName,ClientAge,ClientCountryName) values('John Doe',43,'US'); Query OK, 1 row affected (0.22 sec) mysql> insert into DemoTable1534(ClientName,ClientAge,ClientCountryName) values('Adam Smith',38,'US'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable1534(ClientName,ClientAge,ClientCountryName) values('Carol Taylor',36,'UK'); Query OK, 1 row affected (0.16 sec) Display all records from the table using select statement − mysql> select * from DemoTable1534; This will produce the following output − +----------+--------------+-----------+-------------------+ | ClientId | ClientName | ClientAge | ClientCountryName | +----------+--------------+-----------+-------------------+ | 1 | Chris Brown | 29 | AUS | | 2 | David Miller | 49 | UK | | 3 | John Doe | 43 | US | | 4 | Adam Smith | 38 | US | | 5 | Carol Taylor | 36 | UK | +----------+--------------+-----------+-------------------+ 5 rows in set (0.00 sec) Following is the query for multiple LIKE operator usage in a single query − mysql> select * from DemoTable1534 -> where ClientName LIKE ('%Doe%' or ClientAge LIKE '%38%') or (ClientCountryName LIKE '%S'); This will produce the following output − +----------+-------------+-----------+-------------------+ | ClientId | ClientName | ClientAge | ClientCountryName | +----------+-------------+-----------+-------------------+ | 1 | Chris Brown | 29 | AUS | | 3 | John Doe | 43 | US | | 4 | Adam Smith | 38 | US | +----------+-------------+-----------+-------------------+ 3 rows in set, 5 warnings (0.00 sec)
[ { "code": null, "e": 1250, "s": 1187, "text": "To implement multiple LIKE clauses, the syntax is as follows −" }, { "code": null, "e": 1403, "s": 1250, "text": "select * from yourTableName\n where yourColumnName1 LIKE ('%yourValue1%' or yourColumnName2 LIKE '%yourValue2%') or (yourColumnName3 LIKE '%yourValue3');" }, { "code": null, "e": 1433, "s": 1403, "text": "Let us first create a table −" }, { "code": null, "e": 1664, "s": 1433, "text": "mysql> create table DemoTable1534\n -> (\n -> ClientId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> ClientName varchar(20),\n -> ClientAge int,\n -> ClientCountryName varchar(20)\n -> );\nQuery OK, 0 rows affected (0.78 sec)" }, { "code": null, "e": 1720, "s": 1664, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 2419, "s": 1720, "text": "mysql> insert into DemoTable1534(ClientName,ClientAge,ClientCountryName) values('Chris Brown',29,'AUS');\nQuery OK, 1 row affected (0.21 sec)\nmysql> insert into DemoTable1534(ClientName,ClientAge,ClientCountryName) values('David Miller',49,'UK');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable1534(ClientName,ClientAge,ClientCountryName) values('John Doe',43,'US');\nQuery OK, 1 row affected (0.22 sec)\nmysql> insert into DemoTable1534(ClientName,ClientAge,ClientCountryName) values('Adam Smith',38,'US');\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into DemoTable1534(ClientName,ClientAge,ClientCountryName) values('Carol Taylor',36,'UK');\nQuery OK, 1 row affected (0.16 sec)" }, { "code": null, "e": 2479, "s": 2419, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 2515, "s": 2479, "text": "mysql> select * from DemoTable1534;" }, { "code": null, "e": 2556, "s": 2515, "text": "This will produce the following output −" }, { "code": null, "e": 3121, "s": 2556, "text": "+----------+--------------+-----------+-------------------+\n| ClientId | ClientName | ClientAge | ClientCountryName |\n+----------+--------------+-----------+-------------------+\n| 1 | Chris Brown | 29 | AUS |\n| 2 | David Miller | 49 | UK |\n| 3 | John Doe | 43 | US |\n| 4 | Adam Smith | 38 | US |\n| 5 | Carol Taylor | 36 | UK |\n+----------+--------------+-----------+-------------------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 3197, "s": 3121, "text": "Following is the query for multiple LIKE operator usage in a single query −" }, { "code": null, "e": 3329, "s": 3197, "text": "mysql> select * from DemoTable1534\n -> where ClientName LIKE ('%Doe%' or ClientAge LIKE '%38%') or (ClientCountryName LIKE '%S');" }, { "code": null, "e": 3370, "s": 3329, "text": "This will produce the following output −" }, { "code": null, "e": 3820, "s": 3370, "text": "+----------+-------------+-----------+-------------------+\n| ClientId | ClientName | ClientAge | ClientCountryName |\n+----------+-------------+-----------+-------------------+\n| 1 | Chris Brown | 29 | AUS |\n| 3 | John Doe | 43 | US |\n| 4 | Adam Smith | 38 | US |\n+----------+-------------+-----------+-------------------+\n3 rows in set, 5 warnings (0.00 sec)" } ]
Python Tkinter – Menubutton Widget
26 Mar, 2020 Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter is the fastest and easiest way to create the GUI applications. Creating a GUI using tkinter is an easy task. Note: For more information, refer to Python GUI – tkinter The Menubutton widget can be defined as the drop-down menu that is shown to the user all the time. The Menubutton is used to implement various types of menus in the python application. Syntax: w = Menubutton ( master, options ) Parameters: master: This parameter is used to represents the parent window. options:There are many options which are available and they can be used as key-value pairs separated by commas. Options:Following are commonly used Option can be used with this widget :- activebackground: This option used to represent the background color when the Menubutton is under the cursor. activeforeground: This option used to represent the foreground color when the Menubutton is under the cursor. bg: This option used to represent the normal background color displayed behind the label and indicator. bitmap: This option used to display a monochrome image on a button. bd: This option used to represent the size of the border around the indicator and the default value is 2 pixels. anchor: This option specifies the exact position of the widget content when the widget is assigned more space than needed. cursor: By using this option, the mouse cursor will change to that pattern when it is over the Menubutton. disabledforeground: The foreground color used to render the text of a disabled Menubutton. The default is a stippled version of the default foreground color. direction: It direction can be specified so that menu can be displayed to the specified direction of the button. fg: This option used to represent the color used to render the text. height: This option used to represent the number of lines of text on the Menubutton and it’s default value is 1. highlightcolor: This option used to represent the color of the focus highlight when the Menubutton has the focus. image: This option used to display a graphic image on the button. justify: This option used to control how the text is justified: CENTER, LEFT, or RIGHT. menu: It represents the menu specified with the Menubutton. padx: This option used to represent how much space to leave to the left and right of the Menubutton and text. It’s default value is 1 pixel. pady: This option used to represent how much space to leave above and below the Menubutton and text. It’s default value is 1 pixel. relief: The type of the border of the Menubutton. It’s default value is set to FLAT. state: It represents the state of the Menubutton. By default, it is set to normal. We can change it to DISABLED to make the Menubutton unresponsive. The state of the Menubutton is ACTIVE when it is under focus. text: This option used use newlines (“\n”) to display multiple lines of text. underline: This option used to represent the index of the character in the text which is to be underlined. The indexing starts with zero in the text. textvariable: This option used to represents the associated variable that tracks the state of the Menubutton. width: This option used to represents the width of the Menubutton. and also represented in the number of characters that are represented in the form of texts. wraplength: This option will be broken text into the number of pieces. Example: from tkinter import * root = Tk()root.geometry("300x200") w = Label(root, text ='GeeksForGeeks', font = "50") w.pack() menubutton = Menubutton(root, text = "Menu") menubutton.menu = Menu(menubutton) menubutton["menu"]= menubutton.menu var1 = IntVar()var2 = IntVar()var3 = IntVar() menubutton.menu.add_checkbutton(label = "Courses", variable = var1) menubutton.menu.add_checkbutton(label = "Students", variable = var2)menubutton.menu.add_checkbutton(label = "Careers", variable = var3) menubutton.pack() root.mainloop() Output: Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Mar, 2020" }, { "code": null, "e": 382, "s": 28, "text": "Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter is the fastest and easiest way to create the GUI applications. Creating a GUI using tkinter is an easy task." }, { "code": null, "e": 440, "s": 382, "text": "Note: For more information, refer to Python GUI – tkinter" }, { "code": null, "e": 625, "s": 440, "text": "The Menubutton widget can be defined as the drop-down menu that is shown to the user all the time. The Menubutton is used to implement various types of menus in the python application." }, { "code": null, "e": 633, "s": 625, "text": "Syntax:" }, { "code": null, "e": 668, "s": 633, "text": "w = Menubutton ( master, options )" }, { "code": null, "e": 680, "s": 668, "text": "Parameters:" }, { "code": null, "e": 744, "s": 680, "text": "master: This parameter is used to represents the parent window." }, { "code": null, "e": 856, "s": 744, "text": "options:There are many options which are available and they can be used as key-value pairs separated by commas." }, { "code": null, "e": 931, "s": 856, "text": "Options:Following are commonly used Option can be used with this widget :-" }, { "code": null, "e": 1041, "s": 931, "text": "activebackground: This option used to represent the background color when the Menubutton is under the cursor." }, { "code": null, "e": 1151, "s": 1041, "text": "activeforeground: This option used to represent the foreground color when the Menubutton is under the cursor." }, { "code": null, "e": 1255, "s": 1151, "text": "bg: This option used to represent the normal background color displayed behind the label and indicator." }, { "code": null, "e": 1323, "s": 1255, "text": "bitmap: This option used to display a monochrome image on a button." }, { "code": null, "e": 1436, "s": 1323, "text": "bd: This option used to represent the size of the border around the indicator and the default value is 2 pixels." }, { "code": null, "e": 1559, "s": 1436, "text": "anchor: This option specifies the exact position of the widget content when the widget is assigned more space than needed." }, { "code": null, "e": 1666, "s": 1559, "text": "cursor: By using this option, the mouse cursor will change to that pattern when it is over the Menubutton." }, { "code": null, "e": 1824, "s": 1666, "text": "disabledforeground: The foreground color used to render the text of a disabled Menubutton. The default is a stippled version of the default foreground color." }, { "code": null, "e": 1937, "s": 1824, "text": "direction: It direction can be specified so that menu can be displayed to the specified direction of the button." }, { "code": null, "e": 2006, "s": 1937, "text": "fg: This option used to represent the color used to render the text." }, { "code": null, "e": 2119, "s": 2006, "text": "height: This option used to represent the number of lines of text on the Menubutton and it’s default value is 1." }, { "code": null, "e": 2233, "s": 2119, "text": "highlightcolor: This option used to represent the color of the focus highlight when the Menubutton has the focus." }, { "code": null, "e": 2299, "s": 2233, "text": "image: This option used to display a graphic image on the button." }, { "code": null, "e": 2387, "s": 2299, "text": "justify: This option used to control how the text is justified: CENTER, LEFT, or RIGHT." }, { "code": null, "e": 2447, "s": 2387, "text": "menu: It represents the menu specified with the Menubutton." }, { "code": null, "e": 2588, "s": 2447, "text": "padx: This option used to represent how much space to leave to the left and right of the Menubutton and text. It’s default value is 1 pixel." }, { "code": null, "e": 2720, "s": 2588, "text": "pady: This option used to represent how much space to leave above and below the Menubutton and text. It’s default value is 1 pixel." }, { "code": null, "e": 2805, "s": 2720, "text": "relief: The type of the border of the Menubutton. It’s default value is set to FLAT." }, { "code": null, "e": 3016, "s": 2805, "text": "state: It represents the state of the Menubutton. By default, it is set to normal. We can change it to DISABLED to make the Menubutton unresponsive. The state of the Menubutton is ACTIVE when it is under focus." }, { "code": null, "e": 3094, "s": 3016, "text": "text: This option used use newlines (“\\n”) to display multiple lines of text." }, { "code": null, "e": 3244, "s": 3094, "text": "underline: This option used to represent the index of the character in the text which is to be underlined. The indexing starts with zero in the text." }, { "code": null, "e": 3354, "s": 3244, "text": "textvariable: This option used to represents the associated variable that tracks the state of the Menubutton." }, { "code": null, "e": 3513, "s": 3354, "text": "width: This option used to represents the width of the Menubutton. and also represented in the number of characters that are represented in the form of texts." }, { "code": null, "e": 3584, "s": 3513, "text": "wraplength: This option will be broken text into the number of pieces." }, { "code": null, "e": 3593, "s": 3584, "text": "Example:" }, { "code": "from tkinter import * root = Tk()root.geometry(\"300x200\") w = Label(root, text ='GeeksForGeeks', font = \"50\") w.pack() menubutton = Menubutton(root, text = \"Menu\") menubutton.menu = Menu(menubutton) menubutton[\"menu\"]= menubutton.menu var1 = IntVar()var2 = IntVar()var3 = IntVar() menubutton.menu.add_checkbutton(label = \"Courses\", variable = var1) menubutton.menu.add_checkbutton(label = \"Students\", variable = var2)menubutton.menu.add_checkbutton(label = \"Careers\", variable = var3) menubutton.pack() root.mainloop()", "e": 4224, "s": 3593, "text": null }, { "code": null, "e": 4232, "s": 4224, "text": "Output:" }, { "code": null, "e": 4247, "s": 4232, "text": "Python-tkinter" }, { "code": null, "e": 4254, "s": 4247, "text": "Python" } ]
Node.js - Event Loop
Node.js is a single-threaded application, but it can support concurrency via the concept of event and callbacks. Every API of Node.js is asynchronous and being single-threaded, they use async function calls to maintain concurrency. Node uses observer pattern. Node thread keeps an event loop and whenever a task gets completed, it fires the corresponding event which signals the event-listener function to execute. Node.js uses events heavily and it is also one of the reasons why Node.js is pretty fast compared to other similar technologies. As soon as Node starts its server, it simply initiates its variables, declares functions and then simply waits for the event to occur. In an event-driven application, there is generally a main loop that listens for events, and then triggers a callback function when one of those events is detected. Although events look quite similar to callbacks, the difference lies in the fact that callback functions are called when an asynchronous function returns its result, whereas event handling works on the observer pattern. The functions that listen to events act as Observers. Whenever an event gets fired, its listener function starts executing. Node.js has multiple in-built events available through events module and EventEmitter class which are used to bind events and event-listeners as follows − // Import events module var events = require('events'); // Create an eventEmitter object var eventEmitter = new events.EventEmitter(); Following is the syntax to bind an event handler with an event − // Bind event and event handler as follows eventEmitter.on('eventName', eventHandler); We can fire an event programmatically as follows − // Fire an event eventEmitter.emit('eventName'); Create a js file named main.js with the following code − // Import events module var events = require('events'); // Create an eventEmitter object var eventEmitter = new events.EventEmitter(); // Create an event handler as follows var connectHandler = function connected() { console.log('connection succesful.'); // Fire the data_received event eventEmitter.emit('data_received'); } // Bind the connection event with the handler eventEmitter.on('connection', connectHandler); // Bind the data_received event with the anonymous function eventEmitter.on('data_received', function() { console.log('data received succesfully.'); }); // Fire the connection event eventEmitter.emit('connection'); console.log("Program Ended."); Now let's try to run the above program and check its output − $ node main.js IT should produce the following result − connection successful. data received successfully. Program Ended. In Node Application, any async function accepts a callback as the last parameter and a callback function accepts an error as the first parameter. Let's revisit the previous example again. Create a text file named input.txt with the following content. Tutorials Point is giving self learning content to teach the world in simple and easy way!!!!! Create a js file named main.js having the following code − var fs = require("fs"); fs.readFile('input.txt', function (err, data) { if (err) { console.log(err.stack); return; } console.log(data.toString()); }); console.log("Program Ended"); Here fs.readFile() is a async function whose purpose is to read a file. If an error occurs during the read operation, then the err object will contain the corresponding error, else data will contain the contents of the file. readFile passes err and data to the callback function after the read operation is complete, which finally prints the content. Program Ended Tutorials Point is giving self learning content to teach the world in simple and easy way!!!!!
[ { "code": null, "e": 2567, "s": 2152, "text": "Node.js is a single-threaded application, but it can support concurrency via the concept of event and callbacks. Every API of Node.js is asynchronous and being single-threaded, they use async function calls to maintain concurrency. Node uses observer pattern. Node thread keeps an event loop and whenever a task gets completed, it fires the corresponding event which signals the event-listener function to execute." }, { "code": null, "e": 2832, "s": 2567, "text": "Node.js uses events heavily and it is also one of the reasons why Node.js is pretty fast compared to other similar technologies. As soon as Node starts its server, it simply initiates its variables, declares functions and then simply waits for the event to occur. " }, { "code": null, "e": 2996, "s": 2832, "text": "In an event-driven application, there is generally a main loop that listens for events, and then triggers a callback function when one of those events is detected." }, { "code": null, "e": 3495, "s": 2996, "text": "Although events look quite similar to callbacks, the difference lies in the fact that callback functions are called when an asynchronous function returns its result, whereas event handling works on the observer pattern. The functions that listen to events act as Observers. Whenever an event gets fired, its listener function starts executing. Node.js has multiple in-built events available through events module and EventEmitter class which are used to bind events and event-listeners as follows −" }, { "code": null, "e": 3632, "s": 3495, "text": "// Import events module\nvar events = require('events');\n\n// Create an eventEmitter object\nvar eventEmitter = new events.EventEmitter();\n" }, { "code": null, "e": 3697, "s": 3632, "text": "Following is the syntax to bind an event handler with an event −" }, { "code": null, "e": 3786, "s": 3697, "text": "// Bind event and event handler as follows\neventEmitter.on('eventName', eventHandler);\n" }, { "code": null, "e": 3837, "s": 3786, "text": "We can fire an event programmatically as follows −" }, { "code": null, "e": 3888, "s": 3837, "text": "// Fire an event \neventEmitter.emit('eventName');\n" }, { "code": null, "e": 3945, "s": 3888, "text": "Create a js file named main.js with the following code −" }, { "code": null, "e": 4633, "s": 3945, "text": "// Import events module\nvar events = require('events');\n\n// Create an eventEmitter object\nvar eventEmitter = new events.EventEmitter();\n\n// Create an event handler as follows\nvar connectHandler = function connected() {\n console.log('connection succesful.');\n \n // Fire the data_received event \n eventEmitter.emit('data_received');\n}\n\n// Bind the connection event with the handler\neventEmitter.on('connection', connectHandler);\n \n// Bind the data_received event with the anonymous function\neventEmitter.on('data_received', function() {\n console.log('data received succesfully.');\n});\n\n// Fire the connection event \neventEmitter.emit('connection');\n\nconsole.log(\"Program Ended.\");" }, { "code": null, "e": 4695, "s": 4633, "text": "Now let's try to run the above program and check its output −" }, { "code": null, "e": 4711, "s": 4695, "text": "$ node main.js\n" }, { "code": null, "e": 4752, "s": 4711, "text": "IT should produce the following result −" }, { "code": null, "e": 4819, "s": 4752, "text": "connection successful.\ndata received successfully.\nProgram Ended.\n" }, { "code": null, "e": 5070, "s": 4819, "text": "In Node Application, any async function accepts a callback as the last parameter and a callback function accepts an error as the first parameter. Let's revisit the previous example again. Create a text file named input.txt with the following content." }, { "code": null, "e": 5165, "s": 5070, "text": "Tutorials Point is giving self learning content\nto teach the world in simple and easy way!!!!!" }, { "code": null, "e": 5224, "s": 5165, "text": "Create a js file named main.js having the following code −" }, { "code": null, "e": 5427, "s": 5224, "text": "var fs = require(\"fs\");\n\nfs.readFile('input.txt', function (err, data) {\n if (err) {\n console.log(err.stack);\n return;\n }\n console.log(data.toString());\n});\nconsole.log(\"Program Ended\");" }, { "code": null, "e": 5778, "s": 5427, "text": "Here fs.readFile() is a async function whose purpose is to read a file. If an error occurs during the read operation, then the err object will contain the corresponding error, else data will contain the contents of the file. readFile passes err and data to the callback function after the read operation is complete, which finally prints the content." } ]
Python Number acos() Method
Python number method acos() returns the arc cosine of x, in radians. Following is the syntax for acos() method − acos(x) Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object. x − This must be a numeric value in the range -1 to 1. If x is greater than 1 then it will generate an error. x − This must be a numeric value in the range -1 to 1. If x is greater than 1 then it will generate an error. This method returns arc cosine of x, in radians. The following example shows the usage of acos() method. #!/usr/bin/python import math print "acos(0.64) : ", math.acos(0.64) print "acos(0) : ", math.acos(0) print "acos(-1) : ", math.acos(-1) print "acos(1) : ", math.acos(1) When we run above program, it produces following result − acos(0.64) : 0.876298061168 acos(0) : 1.57079632679 acos(-1) : 3.14159265359 acos(1) : 0.0
[ { "code": null, "e": 2448, "s": 2378, "text": "Python number method acos() returns the arc cosine of x, in radians." }, { "code": null, "e": 2492, "s": 2448, "text": "Following is the syntax for acos() method −" }, { "code": null, "e": 2501, "s": 2492, "text": "acos(x)\n" }, { "code": null, "e": 2648, "s": 2501, "text": "Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object." }, { "code": null, "e": 2758, "s": 2648, "text": "x − This must be a numeric value in the range -1 to 1. If x is greater than 1 then it will generate an error." }, { "code": null, "e": 2868, "s": 2758, "text": "x − This must be a numeric value in the range -1 to 1. If x is greater than 1 then it will generate an error." }, { "code": null, "e": 2917, "s": 2868, "text": "This method returns arc cosine of x, in radians." }, { "code": null, "e": 2973, "s": 2917, "text": "The following example shows the usage of acos() method." }, { "code": null, "e": 3148, "s": 2973, "text": "#!/usr/bin/python\nimport math\n\nprint \"acos(0.64) : \", math.acos(0.64)\nprint \"acos(0) : \", math.acos(0)\nprint \"acos(-1) : \", math.acos(-1)\nprint \"acos(1) : \", math.acos(1)" }, { "code": null, "e": 3206, "s": 3148, "text": "When we run above program, it produces following result −" } ]
Python | Numpy np.assert_equal() method
23 Jan, 2020 With the help of np.assert_equal() method, we can get the assertion error when two objects are not equal by using np.assert_equal() method. Syntax : np.assert_equal(actual, desired)Return : Return assertion error if two object are unequal. Example #1 :In this example we can see that by using np.assert_equal() method, we are able to get the assertion error when two objects are not equal by using this method. # import numpy and assert_equalimport numpy as npimport numpy.testing as npt # using np.assert_equal() methodgfg = npt.assert_equal([1, 2], [1, 2]) print(gfg) Output : None Example #2 : # import numpy and assert_equalimport numpy as npimport numpy.testing as npt # using np.assert_equal() methodgfg = npt.assert_equal([1, 2], [5, 2]) print(gfg) Output : AssertionError:Items are not equal:item=0 ACTUAL: 1DESIRED: 5 Python numpy-Testing Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Jan, 2020" }, { "code": null, "e": 168, "s": 28, "text": "With the help of np.assert_equal() method, we can get the assertion error when two objects are not equal by using np.assert_equal() method." }, { "code": null, "e": 268, "s": 168, "text": "Syntax : np.assert_equal(actual, desired)Return : Return assertion error if two object are unequal." }, { "code": null, "e": 439, "s": 268, "text": "Example #1 :In this example we can see that by using np.assert_equal() method, we are able to get the assertion error when two objects are not equal by using this method." }, { "code": "# import numpy and assert_equalimport numpy as npimport numpy.testing as npt # using np.assert_equal() methodgfg = npt.assert_equal([1, 2], [1, 2]) print(gfg)", "e": 600, "s": 439, "text": null }, { "code": null, "e": 609, "s": 600, "text": "Output :" }, { "code": null, "e": 614, "s": 609, "text": "None" }, { "code": null, "e": 627, "s": 614, "text": "Example #2 :" }, { "code": "# import numpy and assert_equalimport numpy as npimport numpy.testing as npt # using np.assert_equal() methodgfg = npt.assert_equal([1, 2], [5, 2]) print(gfg)", "e": 788, "s": 627, "text": null }, { "code": null, "e": 797, "s": 788, "text": "Output :" }, { "code": null, "e": 839, "s": 797, "text": "AssertionError:Items are not equal:item=0" }, { "code": null, "e": 859, "s": 839, "text": "ACTUAL: 1DESIRED: 5" }, { "code": null, "e": 880, "s": 859, "text": "Python numpy-Testing" }, { "code": null, "e": 893, "s": 880, "text": "Python-numpy" }, { "code": null, "e": 900, "s": 893, "text": "Python" }, { "code": null, "e": 998, "s": 900, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1030, "s": 998, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1057, "s": 1030, "text": "Python Classes and Objects" }, { "code": null, "e": 1078, "s": 1057, "text": "Python OOPs Concepts" }, { "code": null, "e": 1101, "s": 1078, "text": "Introduction To PYTHON" }, { "code": null, "e": 1157, "s": 1101, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1188, "s": 1157, "text": "Python | os.path.join() method" }, { "code": null, "e": 1230, "s": 1188, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1272, "s": 1230, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1311, "s": 1272, "text": "Python | Get unique values from a list" } ]
HTML & CSS | Tabindex attribute & Navigation bars
04 Dec, 2018 The tabindex attribute specifies the tab order of an element. “tab” button is used for navigation. The tabindex content attribute allows users to control whether an element is supposed to be focusable, whether it is supposed to be reachable using sequential focus navigation, and what is to be the relative order of the element for the purposes of sequential focus navigation.Syntax : element tabindex = "number" Attribute : number: This specify the “tab” order when tab key is used to navigate. Example : <div tabindex = "0"><p>GFG Article 1</P></div><div tabindex = "1"><p>GFG Article 2</P></div><div tabindex = "2"><p>GFG Article 3</P></div> In the above example, when tab button is used to navigating elements Article 1 will focused first followed by Article 2 and Article 3. Note: If tabindex value is -1 then it will not be focusable. For example the below link will not be focused while using tab keys to traverse.Example : <a href="#" tabindex="-1">Tab key cannot reach here!</a> Navigation bars :Navigation bars are important to any websites. They are the blocks associated with links to the different pages of the websites. There are two types of navigation menu: Vertical Nav bars Horizontal Nav bars Vertical Nav bars: Vertical bar menu displays one above another.Examples :Code : <style> ul { list-style-type: none; margin: 0; padding: 0; width: 20%; background-color: white; position: fixed; height: 25%; overflow: hidden; } li a { display: block; color: #000; padding: 8px 16px; text-decoration: none; } .hme { background-color: #4CB96B; }</style> <body> <ul> <li><a class="hme" href="#" tabindex="2">Home</a></li> <li><a href="#" tabindex="1">Blog</a></li> <li><a class="hme" href="#" tabindex="4">About Us</a></li> <li><a href="#a" tabindex="3">Contact Us</a></li> </ul></body> Horizontal Nav bars:Horizontal Nav bars menu displays one followed by other or side by side.Examples :Code : <style> ul { list-style-type: none; margin: 0; padding: 0; background-color: white; height: 25%; overflow: hidden; } li { float: left; } li a { display: block; color: #000; padding: 8px 16px; text-decoration: none; } .hme { background-color: #4CB96B }</style> <body> <ul> <li><a class="hme" href="#" tabindex="1">Home</a></li> <li><a href="#" tabindex="2">Blog</a></li> <li><a class="hme" href="#" tabindex="3">About Us</a></li> <li><a href="#" tabindex="4">Contact Us</a></li> </ul></body> CSS-Advanced HTML-Attributes Web technologies 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": "\n04 Dec, 2018" }, { "code": null, "e": 438, "s": 53, "text": "The tabindex attribute specifies the tab order of an element. “tab” button is used for navigation. The tabindex content attribute allows users to control whether an element is supposed to be focusable, whether it is supposed to be reachable using sequential focus navigation, and what is to be the relative order of the element for the purposes of sequential focus navigation.Syntax :" }, { "code": null, "e": 467, "s": 438, "text": "element tabindex = \"number\" " }, { "code": null, "e": 479, "s": 467, "text": "Attribute :" }, { "code": null, "e": 550, "s": 479, "text": "number: This specify the “tab” order when tab key is used to navigate." }, { "code": null, "e": 560, "s": 550, "text": "Example :" }, { "code": "<div tabindex = \"0\"><p>GFG Article 1</P></div><div tabindex = \"1\"><p>GFG Article 2</P></div><div tabindex = \"2\"><p>GFG Article 3</P></div>", "e": 699, "s": 560, "text": null }, { "code": null, "e": 834, "s": 699, "text": "In the above example, when tab button is used to navigating elements Article 1 will focused first followed by Article 2 and Article 3." }, { "code": null, "e": 985, "s": 834, "text": "Note: If tabindex value is -1 then it will not be focusable. For example the below link will not be focused while using tab keys to traverse.Example :" }, { "code": "<a href=\"#\" tabindex=\"-1\">Tab key cannot reach here!</a>", "e": 1042, "s": 985, "text": null }, { "code": null, "e": 1188, "s": 1042, "text": "Navigation bars :Navigation bars are important to any websites. They are the blocks associated with links to the different pages of the websites." }, { "code": null, "e": 1228, "s": 1188, "text": "There are two types of navigation menu:" }, { "code": null, "e": 1246, "s": 1228, "text": "Vertical Nav bars" }, { "code": null, "e": 1266, "s": 1246, "text": "Horizontal Nav bars" }, { "code": null, "e": 1347, "s": 1266, "text": "Vertical Nav bars: Vertical bar menu displays one above another.Examples :Code :" }, { "code": "<style> ul { list-style-type: none; margin: 0; padding: 0; width: 20%; background-color: white; position: fixed; height: 25%; overflow: hidden; } li a { display: block; color: #000; padding: 8px 16px; text-decoration: none; } .hme { background-color: #4CB96B; }</style> <body> <ul> <li><a class=\"hme\" href=\"#\" tabindex=\"2\">Home</a></li> <li><a href=\"#\" tabindex=\"1\">Blog</a></li> <li><a class=\"hme\" href=\"#\" tabindex=\"4\">About Us</a></li> <li><a href=\"#a\" tabindex=\"3\">Contact Us</a></li> </ul></body>", "e": 2005, "s": 1347, "text": null }, { "code": null, "e": 2114, "s": 2005, "text": "Horizontal Nav bars:Horizontal Nav bars menu displays one followed by other or side by side.Examples :Code :" }, { "code": "<style> ul { list-style-type: none; margin: 0; padding: 0; background-color: white; height: 25%; overflow: hidden; } li { float: left; } li a { display: block; color: #000; padding: 8px 16px; text-decoration: none; } .hme { background-color: #4CB96B }</style> <body> <ul> <li><a class=\"hme\" href=\"#\" tabindex=\"1\">Home</a></li> <li><a href=\"#\" tabindex=\"2\">Blog</a></li> <li><a class=\"hme\" href=\"#\" tabindex=\"3\">About Us</a></li> <li><a href=\"#\" tabindex=\"4\">Contact Us</a></li> </ul></body>", "e": 2766, "s": 2114, "text": null }, { "code": null, "e": 2779, "s": 2766, "text": "CSS-Advanced" }, { "code": null, "e": 2795, "s": 2779, "text": "HTML-Attributes" }, { "code": null, "e": 2812, "s": 2795, "text": "Web technologies" }, { "code": null, "e": 2816, "s": 2812, "text": "CSS" }, { "code": null, "e": 2821, "s": 2816, "text": "HTML" }, { "code": null, "e": 2838, "s": 2821, "text": "Web Technologies" }, { "code": null, "e": 2843, "s": 2838, "text": "HTML" } ]
Sherlock – Hunt Username on Social Media Kali Linux Tool
20 Apr, 2021 Sherlock is a free and open-source tool available on GitHub. This tool is free you can download it from Github and can use it for free of cost. Sherlock is used to finding usernames on social media on 300 sites. As you know many users register themselves on social media platforms using their own name. Suppose we need to find someone on any social media website such as Facebook, Instagram etc. To do so we need to go on different websites along and have to search for individually again and again. Sherlock makes it easy for us to find someone’s online presence on social media. Sherlock searches for usernames between 300 websites of social media and provides the related link of that social media platform. Sherlock is written in python language. Features of Sherlock: Sherlock is a free and open-source tool. Sherlock is written in python language. Sherlock is used to hunt usernames. Sherlock searches on 300 social media websites. Sherlock uses python script to search for usernames among 300 websites. Sherlock asks for username and then search online presence of it on other social media. Step 1. Open your Kali Linux and move to Desktop using the following command. cd Desktop Step 2. You are on Desktop to create a new directory here called sherlock using the following command. mkdir sherlock Step 3. Move to the directory that you have created using the following command. cd sherlock Step 4. Now you are in sherlock directory here you have to install the tool using the following command. In this directory, you have to clone the tool from GitHub using the following command. git clone https://github.com/sherlock-project/sherlock.git Step 5. The tool has been downloaded to the directory. Now to list out the contents in it use the following command. ls Step 6. As you can see here is a new directory of the tool. Use the following command to move to this directory. cd sherlock Step 7. To list out the contents of the tool use the following command. ls Step 8. Now you have to install the requirements using the following command. If you don’t install the requirements the tool will not run. python3 -m pip install -r requirements.txt Step 9. All the requirements have been downloaded now it’s time to run and test the tool. To test the tool use the following command. This command will open the help index of the tool. python3 sherlock --help The tool has been downloaded and running successfully. You can now search for usernames by seeing the following examples. Example. Run the tool and find usernames on the different social media platforms. In the above example, the tool is searching for usernames on all 300 social media platforms. You can use your username or your target username in the place of username for example if you want to search a username called harry your command should be python3 sherlock harry. This command will work surely and will search all usernames on 300 websites. This was all about sherlock tool. Cyber-security Kali-Linux Linux-Tools Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ZIP command in Linux with examples tar command in Linux with examples SORT command in Linux/Unix with examples Conditional Statements | Shell Script TCP Server-Client implementation in C curl command in Linux with Examples Tail command in Linux with examples scp command in Linux with Examples Docker - COPY Instruction echo command in Linux with Examples
[ { "code": null, "e": 53, "s": 25, "text": "\n20 Apr, 2021" }, { "code": null, "e": 804, "s": 53, "text": "Sherlock is a free and open-source tool available on GitHub. This tool is free you can download it from Github and can use it for free of cost. Sherlock is used to finding usernames on social media on 300 sites. As you know many users register themselves on social media platforms using their own name. Suppose we need to find someone on any social media website such as Facebook, Instagram etc. To do so we need to go on different websites along and have to search for individually again and again. Sherlock makes it easy for us to find someone’s online presence on social media. Sherlock searches for usernames between 300 websites of social media and provides the related link of that social media platform. Sherlock is written in python language." }, { "code": null, "e": 826, "s": 804, "text": "Features of Sherlock:" }, { "code": null, "e": 867, "s": 826, "text": "Sherlock is a free and open-source tool." }, { "code": null, "e": 907, "s": 867, "text": "Sherlock is written in python language." }, { "code": null, "e": 943, "s": 907, "text": "Sherlock is used to hunt usernames." }, { "code": null, "e": 991, "s": 943, "text": "Sherlock searches on 300 social media websites." }, { "code": null, "e": 1063, "s": 991, "text": "Sherlock uses python script to search for usernames among 300 websites." }, { "code": null, "e": 1151, "s": 1063, "text": "Sherlock asks for username and then search online presence of it on other social media." }, { "code": null, "e": 1229, "s": 1151, "text": "Step 1. Open your Kali Linux and move to Desktop using the following command." }, { "code": null, "e": 1240, "s": 1229, "text": "cd Desktop" }, { "code": null, "e": 1343, "s": 1240, "text": "Step 2. You are on Desktop to create a new directory here called sherlock using the following command." }, { "code": null, "e": 1358, "s": 1343, "text": "mkdir sherlock" }, { "code": null, "e": 1439, "s": 1358, "text": "Step 3. Move to the directory that you have created using the following command." }, { "code": null, "e": 1451, "s": 1439, "text": "cd sherlock" }, { "code": null, "e": 1643, "s": 1451, "text": "Step 4. Now you are in sherlock directory here you have to install the tool using the following command. In this directory, you have to clone the tool from GitHub using the following command." }, { "code": null, "e": 1702, "s": 1643, "text": "git clone https://github.com/sherlock-project/sherlock.git" }, { "code": null, "e": 1819, "s": 1702, "text": "Step 5. The tool has been downloaded to the directory. Now to list out the contents in it use the following command." }, { "code": null, "e": 1822, "s": 1819, "text": "ls" }, { "code": null, "e": 1935, "s": 1822, "text": "Step 6. As you can see here is a new directory of the tool. Use the following command to move to this directory." }, { "code": null, "e": 1947, "s": 1935, "text": "cd sherlock" }, { "code": null, "e": 2019, "s": 1947, "text": "Step 7. To list out the contents of the tool use the following command." }, { "code": null, "e": 2022, "s": 2019, "text": "ls" }, { "code": null, "e": 2161, "s": 2022, "text": "Step 8. Now you have to install the requirements using the following command. If you don’t install the requirements the tool will not run." }, { "code": null, "e": 2204, "s": 2161, "text": "python3 -m pip install -r requirements.txt" }, { "code": null, "e": 2389, "s": 2204, "text": "Step 9. All the requirements have been downloaded now it’s time to run and test the tool. To test the tool use the following command. This command will open the help index of the tool." }, { "code": null, "e": 2413, "s": 2389, "text": "python3 sherlock --help" }, { "code": null, "e": 2535, "s": 2413, "text": "The tool has been downloaded and running successfully. You can now search for usernames by seeing the following examples." }, { "code": null, "e": 2617, "s": 2535, "text": "Example. Run the tool and find usernames on the different social media platforms." }, { "code": null, "e": 3001, "s": 2617, "text": "In the above example, the tool is searching for usernames on all 300 social media platforms. You can use your username or your target username in the place of username for example if you want to search a username called harry your command should be python3 sherlock harry. This command will work surely and will search all usernames on 300 websites. This was all about sherlock tool." }, { "code": null, "e": 3016, "s": 3001, "text": "Cyber-security" }, { "code": null, "e": 3027, "s": 3016, "text": "Kali-Linux" }, { "code": null, "e": 3039, "s": 3027, "text": "Linux-Tools" }, { "code": null, "e": 3050, "s": 3039, "text": "Linux-Unix" }, { "code": null, "e": 3148, "s": 3050, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3183, "s": 3148, "text": "ZIP command in Linux with examples" }, { "code": null, "e": 3218, "s": 3183, "text": "tar command in Linux with examples" }, { "code": null, "e": 3259, "s": 3218, "text": "SORT command in Linux/Unix with examples" }, { "code": null, "e": 3297, "s": 3259, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 3335, "s": 3297, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 3371, "s": 3335, "text": "curl command in Linux with Examples" }, { "code": null, "e": 3407, "s": 3371, "text": "Tail command in Linux with examples" }, { "code": null, "e": 3442, "s": 3407, "text": "scp command in Linux with Examples" }, { "code": null, "e": 3468, "s": 3442, "text": "Docker - COPY Instruction" } ]
Java Program To Recursively Linearly Search An Element In An Array
25 Jan, 2022 Given an array arr[] of n elements, write a function to recursively search a given element x in arr[]. Illustration: Input : arr[] = {25, 60, 18, 3, 10} Output : Element to be searched : 3 Input : arr[] = {10,20,30,24,15,40} Output : -1 For x = 35 Element x is not present in arr[] Procedure: The idea is to search the element from both the sides of array recursively. If the element that needs to searched matches with the leftmost element of the left boundary, or it matches with the rightmost element of the right boundary, directly return the position of the element, else recur for the remaining array to search for the element with the value same as x. Example Java // Java Program to Search an element in an Array Recursively // Main classpublic class GFG { // Method 1 // Recursive method to search for an element and // its index in the array static int recursiveSearch(int arr[], int l, int r, int x) { // if r<l,it means that element is not present in // the array if (r < l) return -1; if (arr[l] == x) return l; if (arr[r] == x) return r; // Since element has not found on both left most and // rightmost boundary,ie at l and r, now recursive the // array to find position of x. return recursiveSearch(arr, l + 1, r - 1, x); } // Method 2 // Main driver method public static void main(String[] args) { // Element to be searched for // Custom input number int x = 3; // Declaring and initializing the integer array int arr[] = new int[] { 25, 60, 18, 3, 10 }; // Calling the above recursive method method to // search for the element in the array // Recursive function is called over array to // get the index of the element present in an array int index = recursiveSearch(arr, 0, arr.length - 1, x); // If index is found means element exists if (index != -1) // Print the element and its index System.out.println("Element " + x + " is present at index " + index); // If we hit else case means // element is not present in the array else // Simply display the corresponding element // is not present System.out.println("Element " + x + " is not present"); }} Element 3 is present at index 3 surinderdawra388 sagartomar9927 java-basics Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array
[ { "code": null, "e": 54, "s": 26, "text": "\n25 Jan, 2022" }, { "code": null, "e": 157, "s": 54, "text": "Given an array arr[] of n elements, write a function to recursively search a given element x in arr[]." }, { "code": null, "e": 171, "s": 157, "text": "Illustration:" }, { "code": null, "e": 340, "s": 171, "text": "Input : arr[] = {25, 60, 18, 3, 10}\nOutput : Element to be searched : 3\n\n\nInput : arr[] = {10,20,30,24,15,40}\nOutput : -1\nFor x = 35\nElement x is not present in arr[]" }, { "code": null, "e": 351, "s": 340, "text": "Procedure:" }, { "code": null, "e": 717, "s": 351, "text": "The idea is to search the element from both the sides of array recursively. If the element that needs to searched matches with the leftmost element of the left boundary, or it matches with the rightmost element of the right boundary, directly return the position of the element, else recur for the remaining array to search for the element with the value same as x." }, { "code": null, "e": 725, "s": 717, "text": "Example" }, { "code": null, "e": 730, "s": 725, "text": "Java" }, { "code": "// Java Program to Search an element in an Array Recursively // Main classpublic class GFG { // Method 1 // Recursive method to search for an element and // its index in the array static int recursiveSearch(int arr[], int l, int r, int x) { // if r<l,it means that element is not present in // the array if (r < l) return -1; if (arr[l] == x) return l; if (arr[r] == x) return r; // Since element has not found on both left most and // rightmost boundary,ie at l and r, now recursive the // array to find position of x. return recursiveSearch(arr, l + 1, r - 1, x); } // Method 2 // Main driver method public static void main(String[] args) { // Element to be searched for // Custom input number int x = 3; // Declaring and initializing the integer array int arr[] = new int[] { 25, 60, 18, 3, 10 }; // Calling the above recursive method method to // search for the element in the array // Recursive function is called over array to // get the index of the element present in an array int index = recursiveSearch(arr, 0, arr.length - 1, x); // If index is found means element exists if (index != -1) // Print the element and its index System.out.println(\"Element \" + x + \" is present at index \" + index); // If we hit else case means // element is not present in the array else // Simply display the corresponding element // is not present System.out.println(\"Element \" + x + \" is not present\"); }}", "e": 2562, "s": 730, "text": null }, { "code": null, "e": 2597, "s": 2565, "text": "Element 3 is present at index 3" }, { "code": null, "e": 2616, "s": 2599, "text": "surinderdawra388" }, { "code": null, "e": 2631, "s": 2616, "text": "sagartomar9927" }, { "code": null, "e": 2643, "s": 2631, "text": "java-basics" }, { "code": null, "e": 2648, "s": 2643, "text": "Java" }, { "code": null, "e": 2662, "s": 2648, "text": "Java Programs" }, { "code": null, "e": 2667, "s": 2662, "text": "Java" }, { "code": null, "e": 2765, "s": 2667, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2780, "s": 2765, "text": "Stream In Java" }, { "code": null, "e": 2801, "s": 2780, "text": "Introduction to Java" }, { "code": null, "e": 2822, "s": 2801, "text": "Constructors in Java" }, { "code": null, "e": 2841, "s": 2822, "text": "Exceptions in Java" }, { "code": null, "e": 2858, "s": 2841, "text": "Generics in Java" }, { "code": null, "e": 2884, "s": 2858, "text": "Java Programming Examples" }, { "code": null, "e": 2918, "s": 2884, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 2965, "s": 2918, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 3003, "s": 2965, "text": "Factory method design pattern in Java" } ]
Collections.nCopies() in Java
28 Feb, 2018 The role of Collections.nCopies() is to return an immutable list which contains n copies of given object. This function helps if we want to create a list with n copies of given object. The newly allocated data object is tiny i.e, it contains a single reference to the data object. Syntax : public static <T> List<T> nCopies(int number, T object) where, number is the number of copies of object and object represents the element which will appear number times in the returned list. T represents generic type. Exception : The function throws IllegalArgumentException if value of number is less than 0. Example : Java // Java code to show implementation// of Collections.nCopies()import java.util.*; class GFG { // Driver code public static void main(String[] args) { // creating a list where first argument // represents the number of copies and // the second argument represents the // element to be copied for 'number' times // This will create 4 copies of the objects. List list = Collections.nCopies(4, "GeeksforGeeks"); // Displaying the list returned System.out.println("The list returned is :"); Iterator itr = list.iterator(); while (itr.hasNext()) { System.out.print(itr.next() + " "); } System.out.println("\n"); List list1 = Collections.nCopies(3, "GeeksQuiz"); // Displaying the list returned System.out.println("The list returned is :"); Iterator itr1 = list1.iterator(); while (itr1.hasNext()) { System.out.print(itr1.next() + " "); } System.out.print("\n"); }} The list returned is : GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks The list returned is : GeeksQuiz GeeksQuiz GeeksQuiz Java-Collections Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Functional Interfaces in Java Java Programming Examples Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Feb, 2018" }, { "code": null, "e": 335, "s": 54, "text": "The role of Collections.nCopies() is to return an immutable list which contains n copies of given object. This function helps if we want to create a list with n copies of given object. The newly allocated data object is tiny i.e, it contains a single reference to the data object." }, { "code": null, "e": 344, "s": 335, "text": "Syntax :" }, { "code": null, "e": 566, "s": 344, "text": "public static <T> List<T> nCopies(int number, T object)\n\nwhere, number is the number of copies\nof object and object represents the \nelement which will appear number times\nin the returned list. T represents generic type. \n" }, { "code": null, "e": 658, "s": 566, "text": "Exception : The function throws IllegalArgumentException if value of number is less than 0." }, { "code": null, "e": 668, "s": 658, "text": "Example :" }, { "code": null, "e": 673, "s": 668, "text": "Java" }, { "code": "// Java code to show implementation// of Collections.nCopies()import java.util.*; class GFG { // Driver code public static void main(String[] args) { // creating a list where first argument // represents the number of copies and // the second argument represents the // element to be copied for 'number' times // This will create 4 copies of the objects. List list = Collections.nCopies(4, \"GeeksforGeeks\"); // Displaying the list returned System.out.println(\"The list returned is :\"); Iterator itr = list.iterator(); while (itr.hasNext()) { System.out.print(itr.next() + \" \"); } System.out.println(\"\\n\"); List list1 = Collections.nCopies(3, \"GeeksQuiz\"); // Displaying the list returned System.out.println(\"The list returned is :\"); Iterator itr1 = list1.iterator(); while (itr1.hasNext()) { System.out.print(itr1.next() + \" \"); } System.out.print(\"\\n\"); }}", "e": 1716, "s": 673, "text": null }, { "code": null, "e": 1853, "s": 1716, "text": "The list returned is :\nGeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks \n\nThe list returned is :\nGeeksQuiz GeeksQuiz GeeksQuiz \n" }, { "code": null, "e": 1870, "s": 1853, "text": "Java-Collections" }, { "code": null, "e": 1875, "s": 1870, "text": "Java" }, { "code": null, "e": 1880, "s": 1875, "text": "Java" }, { "code": null, "e": 1897, "s": 1880, "text": "Java-Collections" }, { "code": null, "e": 1995, "s": 1897, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2010, "s": 1995, "text": "Stream In Java" }, { "code": null, "e": 2031, "s": 2010, "text": "Introduction to Java" }, { "code": null, "e": 2052, "s": 2031, "text": "Constructors in Java" }, { "code": null, "e": 2071, "s": 2052, "text": "Exceptions in Java" }, { "code": null, "e": 2088, "s": 2071, "text": "Generics in Java" }, { "code": null, "e": 2118, "s": 2088, "text": "Functional Interfaces in Java" }, { "code": null, "e": 2144, "s": 2118, "text": "Java Programming Examples" }, { "code": null, "e": 2160, "s": 2144, "text": "Strings in Java" }, { "code": null, "e": 2197, "s": 2160, "text": "Differences between JDK, JRE and JVM" } ]
Python Program to Sort Words in Alphabetical Order
23 Aug, 2021 Given an input string, our task is to write a Python program to sort the words present in the string in alphabetical order. Examples: Input : “geeks for Geeks” Output : “for geeks geeks” Input : “the Quick brown fox jumPs over the lazY Dog” Output : “brown dog fox jumps lazy over quick the the” sorted() is a predefined function in Python which returns the sorted list of any particular sequence. Python3 # Python3 program to sort the words of a string in# alphabetical order# Function to sort the words in alphabetical orderdef Func(S):W = S.split(” “)for i in range(len(W)):# convert all the words into lowercaseW[i]=W[i].lower()S = sorted(W)print(‘ ‘.join(S))# Driver codeS = “the Quick brown fox jumPs over the lazY Dog”# function callFunc(S) # Function to sort the words in alphabetical orderdef Func(S):W = S.split(” “)for i in range(len(W)): # convert all the words into lowercaseW[i]=W[i].lower()S = sorted(W)print(‘ ‘.join(S)) # Driver codeS = “the Quick brown fox jumPs over the lazY Dog” # function callFunc(S) Output: brown dog fox jumps lazy over quick the the Python list sort() function can be used to sort a list in ascending, descending, or user-defined order. Python3 # Python3 program to sort the words of a# string in alphabetical order# Function to sort the words in alphabetical# orderdef F(S):W = S.split(” “)for i in range(len(W)):W[i] = W[i].lower()W.sort()# return the sorted wordsreturn ‘ ‘.join(W)# Driver codeS = “GeekS for geEks”print(F(S)) # Function to sort the words in alphabetical# orderdef F(S):W = S.split(” “)for i in range(len(W)):W[i] = W[i].lower()W.sort() # return the sorted wordsreturn ‘ ‘.join(W) # Driver codeS = “GeekS for geEks”print(F(S)) Output: for geeks geeks Picked Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n23 Aug, 2021" }, { "code": null, "e": 177, "s": 53, "text": "Given an input string, our task is to write a Python program to sort the words present in the string in alphabetical order." }, { "code": null, "e": 187, "s": 177, "text": "Examples:" }, { "code": null, "e": 213, "s": 187, "text": "Input : “geeks for Geeks”" }, { "code": null, "e": 242, "s": 213, "text": "Output : “for geeks geeks” " }, { "code": null, "e": 296, "s": 242, "text": "Input : “the Quick brown fox jumPs over the lazY Dog”" }, { "code": null, "e": 351, "s": 296, "text": "Output : “brown dog fox jumps lazy over quick the the”" }, { "code": null, "e": 453, "s": 351, "text": "sorted() is a predefined function in Python which returns the sorted list of any particular sequence." }, { "code": null, "e": 461, "s": 453, "text": "Python3" }, { "code": "# Python3 program to sort the words of a string in# alphabetical order# Function to sort the words in alphabetical orderdef Func(S):W = S.split(” “)for i in range(len(W)):# convert all the words into lowercaseW[i]=W[i].lower()S = sorted(W)print(‘ ‘.join(S))# Driver codeS = “the Quick brown fox jumPs over the lazY Dog”# function callFunc(S)", "e": 803, "s": 461, "text": null }, { "code": null, "e": 905, "s": 803, "text": "# Function to sort the words in alphabetical orderdef Func(S):W = S.split(” “)for i in range(len(W)):" }, { "code": null, "e": 992, "s": 905, "text": "# convert all the words into lowercaseW[i]=W[i].lower()S = sorted(W)print(‘ ‘.join(S))" }, { "code": null, "e": 1055, "s": 992, "text": "# Driver codeS = “the Quick brown fox jumPs over the lazY Dog”" }, { "code": null, "e": 1078, "s": 1055, "text": "# function callFunc(S)" }, { "code": null, "e": 1086, "s": 1078, "text": "Output:" }, { "code": null, "e": 1130, "s": 1086, "text": "brown dog fox jumps lazy over quick the the" }, { "code": null, "e": 1235, "s": 1130, "text": "Python list sort() function can be used to sort a list in ascending, descending, or user-defined order. " }, { "code": null, "e": 1243, "s": 1235, "text": "Python3" }, { "code": "# Python3 program to sort the words of a# string in alphabetical order# Function to sort the words in alphabetical# orderdef F(S):W = S.split(” “)for i in range(len(W)):W[i] = W[i].lower()W.sort()# return the sorted wordsreturn ‘ ‘.join(W)# Driver codeS = “GeekS for geEks”print(F(S))", "e": 1528, "s": 1243, "text": null }, { "code": null, "e": 1655, "s": 1528, "text": "# Function to sort the words in alphabetical# orderdef F(S):W = S.split(” “)for i in range(len(W)):W[i] = W[i].lower()W.sort()" }, { "code": null, "e": 1699, "s": 1655, "text": "# return the sorted wordsreturn ‘ ‘.join(W)" }, { "code": null, "e": 1745, "s": 1699, "text": "# Driver codeS = “GeekS for geEks”print(F(S))" }, { "code": null, "e": 1753, "s": 1745, "text": "Output:" }, { "code": null, "e": 1769, "s": 1753, "text": "for geeks geeks" }, { "code": null, "e": 1776, "s": 1769, "text": "Picked" }, { "code": null, "e": 1799, "s": 1776, "text": "Python string-programs" }, { "code": null, "e": 1806, "s": 1799, "text": "Python" }, { "code": null, "e": 1822, "s": 1806, "text": "Python Programs" } ]
Method Class | hashCode() Method in Java
24 Dec, 2021 The java.lang.reflect.Method.hashCode() method returns the hash code for the Method class object. The hashcode returned is computed by exclusive-or operation on the hashcodes for the method’s declaring class name and the method’s name. The hashcode is always the same if the object doesn’t change. Hashcode is a unique code generated by the JVM at time of object creation. It can be used to perform some operation on hashing related algorithms like hashtable, hashmap etc. An object can also be searched with this unique code. Syntax: public int hashCode() Returns: It returns an integer value which represents hashCode value for this Method. Example: Method: public void getvalue(){} HashCode: 1553975225 Explanation: Hashcode is a unique code generated by the JVM at time of creation of the object of Method getValue.when we going to apply hashCode function on method object of getValue it will return 1553975225 as hashCode. Method:public void paint(){} HashCode: 1643975341 Below program illustrates hashcode() method of Method class: Program 1: Get the hash code of a specific method object created by calling getDeclaredMethod() of Class object. Java /** Program Demonstrate hashcode() method of Method Class.*/import java.lang.reflect.Method; public class GFG { // create a Method name getSampleMethod public void getSampleMethod() {} // create main method public static void main(String args[]) { try { // create class object for class name GFG Class c = GFG.class; // get Method object of method name getSampleMethod Method method = c.getDeclaredMethod("getSampleMethod", null); // get hashcode of method object using hashCode() method int hashCode = method.hashCode(); // Print hashCode with method name System.out.println("hashCode of method " + method.getName() + " is " + hashCode); } catch (Exception e) { // print if any exception occurs e.printStackTrace(); } }} Output: hashCode of method getSampleMethod is 1553813225 Program 2: In this program, after getting a list of Method objects of a class object by calling getMethods() method of class object, hashCode() method of Method object is called for each method object of the list. At last, the hashcode is printed along with the method name. Java /** Program Demonstrate hashcode() method of Method Class.*/import java.lang.reflect.Method; public class GFG { // create a Method name getSampleMethod public void getSampleMethod() {} // create a Method name setSampleMethod public String setSampleMethod() { String str = "hello India"; return str; } // create main method public static void main(String args[]) { try { // create class object for class name GFG Class c = GFG.class; // get list of Method objects // of class object of gfg class Method[] methods = c.getMethods(); // loop through methods list // and get hashcode of every method // and print those hashcode along with Method Name for (Method m : methods) { // get hashcode of current method of loop int hashCode = m.hashCode(); // Print hashCode along with method name System.out.println("hashCode of method " + m.getName() + " is " + hashCode); } } catch (Exception e) { // print Exception if any Exception occurs. e.printStackTrace(); } }} Output: hashCode of method main is 3282673 hashCode of method getSampleMethod is 1553813225 hashCode of method setSampleMethod is -1830532123 hashCode of method wait is 1063184614 hashCode of method wait is 1063184614 hashCode of method wait is 1063184614 hashCode of method equals is -1918826964 hashCode of method toString is -1451283457 hashCode of method hashCode is 933549448 hashCode of method getClass is 1261057617 hashCode of method notify is -43061542 hashCode of method notifyAll is 1312178187 Explanation: Output of this program also showing results for method objects other than methods defined in class object like wait, equals, toString, hashCode, getClass, notify, and notifyAll, which are inherited from superclass Object of java.lang package by class Object. Reference: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Method.html#hashCode– arorakashish0911 Hash Java-Functions Java-lang package java-lang-reflect-package Java-Method Class Java Hash Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java HashMap in Java with Examples ArrayList in Java Collections in Java Stream In Java Multidimensional Arrays in Java Singleton Class in Java Set in Java Stack Class in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Dec, 2021" }, { "code": null, "e": 555, "s": 28, "text": "The java.lang.reflect.Method.hashCode() method returns the hash code for the Method class object. The hashcode returned is computed by exclusive-or operation on the hashcodes for the method’s declaring class name and the method’s name. The hashcode is always the same if the object doesn’t change. Hashcode is a unique code generated by the JVM at time of object creation. It can be used to perform some operation on hashing related algorithms like hashtable, hashmap etc. An object can also be searched with this unique code." }, { "code": null, "e": 564, "s": 555, "text": "Syntax: " }, { "code": null, "e": 586, "s": 564, "text": "public int hashCode()" }, { "code": null, "e": 672, "s": 586, "text": "Returns: It returns an integer value which represents hashCode value for this Method." }, { "code": null, "e": 681, "s": 672, "text": "Example:" }, { "code": null, "e": 1009, "s": 681, "text": "Method: public void getvalue(){}\nHashCode: 1553975225\nExplanation: Hashcode is a unique code generated by the JVM at time of creation of the object\nof Method getValue.when we going to apply hashCode function on method object of \ngetValue it will return 1553975225 as hashCode.\n\nMethod:public void paint(){}\nHashCode: 1643975341" }, { "code": null, "e": 1071, "s": 1009, "text": "Below program illustrates hashcode() method of Method class: " }, { "code": null, "e": 1184, "s": 1071, "text": "Program 1: Get the hash code of a specific method object created by calling getDeclaredMethod() of Class object." }, { "code": null, "e": 1189, "s": 1184, "text": "Java" }, { "code": "/** Program Demonstrate hashcode() method of Method Class.*/import java.lang.reflect.Method; public class GFG { // create a Method name getSampleMethod public void getSampleMethod() {} // create main method public static void main(String args[]) { try { // create class object for class name GFG Class c = GFG.class; // get Method object of method name getSampleMethod Method method = c.getDeclaredMethod(\"getSampleMethod\", null); // get hashcode of method object using hashCode() method int hashCode = method.hashCode(); // Print hashCode with method name System.out.println(\"hashCode of method \" + method.getName() + \" is \" + hashCode); } catch (Exception e) { // print if any exception occurs e.printStackTrace(); } }}", "e": 2104, "s": 1189, "text": null }, { "code": null, "e": 2113, "s": 2104, "text": "Output: " }, { "code": null, "e": 2162, "s": 2113, "text": "hashCode of method getSampleMethod is 1553813225" }, { "code": null, "e": 2437, "s": 2162, "text": "Program 2: In this program, after getting a list of Method objects of a class object by calling getMethods() method of class object, hashCode() method of Method object is called for each method object of the list. At last, the hashcode is printed along with the method name." }, { "code": null, "e": 2442, "s": 2437, "text": "Java" }, { "code": "/** Program Demonstrate hashcode() method of Method Class.*/import java.lang.reflect.Method; public class GFG { // create a Method name getSampleMethod public void getSampleMethod() {} // create a Method name setSampleMethod public String setSampleMethod() { String str = \"hello India\"; return str; } // create main method public static void main(String args[]) { try { // create class object for class name GFG Class c = GFG.class; // get list of Method objects // of class object of gfg class Method[] methods = c.getMethods(); // loop through methods list // and get hashcode of every method // and print those hashcode along with Method Name for (Method m : methods) { // get hashcode of current method of loop int hashCode = m.hashCode(); // Print hashCode along with method name System.out.println(\"hashCode of method \" + m.getName() + \" is \" + hashCode); } } catch (Exception e) { // print Exception if any Exception occurs. e.printStackTrace(); } }}", "e": 3742, "s": 2442, "text": null }, { "code": null, "e": 3751, "s": 3742, "text": "Output: " }, { "code": null, "e": 4248, "s": 3751, "text": "hashCode of method main is 3282673\nhashCode of method getSampleMethod is 1553813225\nhashCode of method setSampleMethod is -1830532123\nhashCode of method wait is 1063184614\nhashCode of method wait is 1063184614\nhashCode of method wait is 1063184614\nhashCode of method equals is -1918826964\nhashCode of method toString is -1451283457\nhashCode of method hashCode is 933549448\nhashCode of method getClass is 1261057617\nhashCode of method notify is -43061542\nhashCode of method notifyAll is 1312178187" }, { "code": null, "e": 4520, "s": 4248, "text": "Explanation: Output of this program also showing results for method objects other than methods defined in class object like wait, equals, toString, hashCode, getClass, notify, and notifyAll, which are inherited from superclass Object of java.lang package by class Object." }, { "code": null, "e": 4613, "s": 4520, "text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Method.html#hashCode–" }, { "code": null, "e": 4630, "s": 4613, "text": "arorakashish0911" }, { "code": null, "e": 4635, "s": 4630, "text": "Hash" }, { "code": null, "e": 4650, "s": 4635, "text": "Java-Functions" }, { "code": null, "e": 4668, "s": 4650, "text": "Java-lang package" }, { "code": null, "e": 4694, "s": 4668, "text": "java-lang-reflect-package" }, { "code": null, "e": 4712, "s": 4694, "text": "Java-Method Class" }, { "code": null, "e": 4717, "s": 4712, "text": "Java" }, { "code": null, "e": 4722, "s": 4717, "text": "Hash" }, { "code": null, "e": 4727, "s": 4722, "text": "Java" }, { "code": null, "e": 4825, "s": 4727, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4876, "s": 4825, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 4907, "s": 4876, "text": "How to iterate any Map in Java" }, { "code": null, "e": 4937, "s": 4907, "text": "HashMap in Java with Examples" }, { "code": null, "e": 4955, "s": 4937, "text": "ArrayList in Java" }, { "code": null, "e": 4975, "s": 4955, "text": "Collections in Java" }, { "code": null, "e": 4990, "s": 4975, "text": "Stream In Java" }, { "code": null, "e": 5022, "s": 4990, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 5046, "s": 5022, "text": "Singleton Class in Java" }, { "code": null, "e": 5058, "s": 5046, "text": "Set in Java" } ]
JavaScript Narcissistic number
A narcissistic number in a given number base b is a number that is the sum of its own digits each raised to the power of the number of digits. For example − 153 = 1^3 + 5^3 + 3^3 = 1+125+27 = 153 Similarly, 1 = 1^1 = 1 We will first count the number of digits using a while loop. Then with another while loop, we pick last digit of the number and add its (count) th power to a variable sum. After the loop we return a boolean checking whether the sum is equal to the number or not. The code for this approach will be − const isNarcissistic = (num) => { let m = 1, count = 0; while(num / m > 1){ m *= 10; count++; }; let sum = 0, temp = num; while(temp){ sum += Math.pow(temp % 10, count); temp = Math.floor(temp / 10); }; return sum === num; }; console.log(isNarcissistic(153)); console.log(isNarcissistic(1634)); console.log(isNarcissistic(1433)); console.log(isNarcissistic(342)); The output in the console will be − true true false false
[ { "code": null, "e": 1330, "s": 1187, "text": "A narcissistic number in a given number base b is a number that is the sum of its own digits each raised to the power of the number of digits." }, { "code": null, "e": 1344, "s": 1330, "text": "For example −" }, { "code": null, "e": 1383, "s": 1344, "text": "153 = 1^3 + 5^3 + 3^3 = 1+125+27 = 153" }, { "code": null, "e": 1394, "s": 1383, "text": "Similarly," }, { "code": null, "e": 1406, "s": 1394, "text": "1 = 1^1 = 1" }, { "code": null, "e": 1669, "s": 1406, "text": "We will first count the number of digits using a while loop. Then with another while loop, we pick\nlast digit of the number and add its (count) th power to a variable sum. After the loop we return a\nboolean checking whether the sum is equal to the number or not." }, { "code": null, "e": 1706, "s": 1669, "text": "The code for this approach will be −" }, { "code": null, "e": 2115, "s": 1706, "text": "const isNarcissistic = (num) => {\n let m = 1, count = 0;\n while(num / m > 1){\n m *= 10;\n count++;\n };\n let sum = 0, temp = num;\n while(temp){\n sum += Math.pow(temp % 10, count);\n temp = Math.floor(temp / 10);\n };\n return sum === num;\n};\nconsole.log(isNarcissistic(153));\nconsole.log(isNarcissistic(1634));\nconsole.log(isNarcissistic(1433));\nconsole.log(isNarcissistic(342));" }, { "code": null, "e": 2151, "s": 2115, "text": "The output in the console will be −" }, { "code": null, "e": 2173, "s": 2151, "text": "true\ntrue\nfalse\nfalse" } ]
Java.util.Collections.frequency() in Java with Examples
07 Dec, 2018 java.util.Collections.frequency() method is present in java.util.Collections class. It is used to get the frequency of a element present in the specified list of Collection. More formally, it returns the number of elements e in the collection. Syntax public static int frequency(Collection<?> c, Object o) Parameters : c - the collection in which to determine the frequency of o o - the object whose frequency is to be determined Returns : Returns the number of elements in the specified collection equal to the specified object. Throws: NullPointerException - if c is null // Java program to demonstrate working of // java.utils.Collections.frequency() import java.util.*; public class FrequencyDemo{ public static void main(String[] args) { // Let us create a list of strings List<String> mylist = new ArrayList<String>(); mylist.add("practice"); mylist.add("code"); mylist.add("code"); mylist.add("quiz"); mylist.add("geeksforgeeks"); // Here we are using frequency() method // to get frequency of element "code" int freq = Collections.frequency(mylist, "code"); System.out.println(freq); }} Output: 2 How to Quickly get frequency of an element in an array in Java ? Arrays class in Java doesn’t have frequency method. But we can use Collections.frequency() to get frequency of an element in an array also. // Java program to get frequency of an element // with java.utils.Collections.frequency() import java.util.*; public class FrequencyDemo{ public static void main(String[] args) { // Let us create an array of integers Integer arr[] = {10, 20, 20, 30, 20, 40, 50}; // Please refer below post for details of asList() // https://www.geeksforgeeks.org/array-class-in-java/ int freq = Collections.frequency(Arrays.asList(arr), 20); System.out.println(freq); }} Output: 3 This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Java - util package Java-Collections Java-Collections-Class Java-Functions Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Dec, 2018" }, { "code": null, "e": 296, "s": 52, "text": "java.util.Collections.frequency() method is present in java.util.Collections class. It is used to get the frequency of a element present in the specified list of Collection. More formally, it returns the number of elements e in the collection." }, { "code": null, "e": 303, "s": 296, "text": "Syntax" }, { "code": null, "e": 629, "s": 303, "text": "public static int frequency(Collection<?> c, Object o)\nParameters : \nc - the collection in which to determine the frequency of o\no - the object whose frequency is to be determined\nReturns :\nReturns the number of elements in the specified collection \nequal to the specified object.\nThrows:\nNullPointerException - if c is null\n" }, { "code": "// Java program to demonstrate working of // java.utils.Collections.frequency() import java.util.*; public class FrequencyDemo{ public static void main(String[] args) { // Let us create a list of strings List<String> mylist = new ArrayList<String>(); mylist.add(\"practice\"); mylist.add(\"code\"); mylist.add(\"code\"); mylist.add(\"quiz\"); mylist.add(\"geeksforgeeks\"); // Here we are using frequency() method // to get frequency of element \"code\" int freq = Collections.frequency(mylist, \"code\"); System.out.println(freq); }}", "e": 1247, "s": 629, "text": null }, { "code": null, "e": 1255, "s": 1247, "text": "Output:" }, { "code": null, "e": 1258, "s": 1255, "text": "2\n" }, { "code": null, "e": 1323, "s": 1258, "text": "How to Quickly get frequency of an element in an array in Java ?" }, { "code": null, "e": 1463, "s": 1323, "text": "Arrays class in Java doesn’t have frequency method. But we can use Collections.frequency() to get frequency of an element in an array also." }, { "code": "// Java program to get frequency of an element // with java.utils.Collections.frequency() import java.util.*; public class FrequencyDemo{ public static void main(String[] args) { // Let us create an array of integers Integer arr[] = {10, 20, 20, 30, 20, 40, 50}; // Please refer below post for details of asList() // https://www.geeksforgeeks.org/array-class-in-java/ int freq = Collections.frequency(Arrays.asList(arr), 20); System.out.println(freq); }}", "e": 1979, "s": 1463, "text": null }, { "code": null, "e": 1987, "s": 1979, "text": "Output:" }, { "code": null, "e": 1990, "s": 1987, "text": "3\n" }, { "code": null, "e": 2292, "s": 1990, "text": "This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 2417, "s": 2292, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 2437, "s": 2417, "text": "Java - util package" }, { "code": null, "e": 2454, "s": 2437, "text": "Java-Collections" }, { "code": null, "e": 2477, "s": 2454, "text": "Java-Collections-Class" }, { "code": null, "e": 2492, "s": 2477, "text": "Java-Functions" }, { "code": null, "e": 2497, "s": 2492, "text": "Java" }, { "code": null, "e": 2502, "s": 2497, "text": "Java" }, { "code": null, "e": 2519, "s": 2502, "text": "Java-Collections" } ]
Select row with maximum and minimum value in Pandas dataframe
06 Jan, 2019 Let’s see how can we select row with maximum and minimum value in Pandas dataframe with help of different examples. Consider this dataset. # importing pandas and numpyimport pandas as pdimport numpy as np # data of 2018 drivers world championshipdict1 ={'Driver':['Hamilton', 'Vettel', 'Raikkonen', 'Verstappen', 'Bottas', 'Ricciardo', 'Hulkenberg', 'Perez', 'Magnussen', 'Sainz', 'Alonso', 'Ocon', 'Leclerc', 'Grosjean', 'Gasly', 'Vandoorne', 'Ericsson', 'Stroll', 'Hartley', 'Sirotkin'], 'Points':[408, 320, 251, 249, 247, 170, 69, 62, 56, 53, 50, 49, 39, 37, 29, 12, 9, 6, 4, 1], 'Age':[33, 31, 39, 21, 29, 29, 31, 28, 26, 24, 37, 22, 21, 32, 22, 26, 28, 20, 29, 23]} # creating dataframe using DataFrame constructordf = pd.DataFrame(dict1)print(df.head(10)) Output: Code #1: Shows max on Driver, Points, Age columns. # importing pandas and numpyimport pandas as pdimport numpy as np # data of 2018 drivers world championshipdict1 ={'Driver':['Hamilton', 'Vettel', 'Raikkonen', 'Verstappen', 'Bottas', 'Ricciardo', 'Hulkenberg', 'Perez', 'Magnussen', 'Sainz', 'Alonso', 'Ocon', 'Leclerc', 'Grosjean', 'Gasly', 'Vandoorne', 'Ericsson', 'Stroll', 'Hartley', 'Sirotkin'], 'Points':[408, 320, 251, 249, 247, 170, 69, 62, 56, 53, 50, 49, 39, 37, 29, 12, 9, 6, 4, 1], 'Age':[33, 31, 39, 21, 29, 29, 31, 28, 26, 24, 37, 22, 21, 32, 22, 26, 28, 20, 29, 23]} # creating dataframe using DataFrame constructordf = pd.DataFrame(dict1) # the result shows max on# Driver, Points, Age columns.print(df.max()) Output: Code #2: Who scored max points # importing pandas and numpyimport pandas as pdimport numpy as np # data of 2018 drivers world championshipdict1 ={'Driver':['Hamilton', 'Vettel', 'Raikkonen', 'Verstappen', 'Bottas', 'Ricciardo', 'Hulkenberg', 'Perez', 'Magnussen', 'Sainz', 'Alonso', 'Ocon', 'Leclerc', 'Grosjean', 'Gasly', 'Vandoorne', 'Ericsson', 'Stroll', 'Hartley', 'Sirotkin'], 'Points':[408, 320, 251, 249, 247, 170, 69, 62, 56, 53, 50, 49, 39, 37, 29, 12, 9, 6, 4, 1], 'Age':[33, 31, 39, 21, 29, 29, 31, 28, 26, 24, 37, 22, 21, 32, 22, 26, 28, 20, 29, 23]} # creating dataframe using DataFrame constructordf = pd.DataFrame(dict1) # Who scored more points ?print(df[df.Points == df.Points.max()]) Output: Code #3: What is the maximum age # importing pandas and numpyimport pandas as pdimport numpy as np # data of 2018 drivers world championshipdict1 ={'Driver':['Hamilton', 'Vettel', 'Raikkonen', 'Verstappen', 'Bottas', 'Ricciardo', 'Hulkenberg', 'Perez', 'Magnussen', 'Sainz', 'Alonso', 'Ocon', 'Leclerc', 'Grosjean', 'Gasly', 'Vandoorne', 'Ericsson', 'Stroll', 'Hartley', 'Sirotkin'], 'Points':[408, 320, 251, 249, 247, 170, 69, 62, 56, 53, 50, 49, 39, 37, 29, 12, 9, 6, 4, 1], 'Age':[33, 31, 39, 21, 29, 29, 31, 28, 26, 24, 37, 22, 21, 32, 22, 26, 28, 20, 29, 23]} # creating dataframe using DataFrame constructordf = pd.DataFrame(dict1) # what is the maximum age ?print(df.Age.max()) Output: Code #4: Which row has maximum age in the dataframe | who is the oldest driver ? # importing pandas and numpyimport pandas as pdimport numpy as np # data of 2018 drivers world championshipdict1 ={'Driver':['Hamilton', 'Vettel', 'Raikkonen', 'Verstappen', 'Bottas', 'Ricciardo', 'Hulkenberg', 'Perez', 'Magnussen', 'Sainz', 'Alonso', 'Ocon', 'Leclerc', 'Grosjean', 'Gasly', 'Vandoorne', 'Ericsson', 'Stroll', 'Hartley', 'Sirotkin'], 'Points':[408, 320, 251, 249, 247, 170, 69, 62, 56, 53, 50, 49, 39, 37, 29, 12, 9, 6, 4, 1], 'Age':[33, 31, 39, 21, 29, 29, 31, 28, 26, 24, 37, 22, 21, 32, 22, 26, 28, 20, 29, 23]} # creating dataframe using DataFrame constructordf = pd.DataFrame(dict1) # Which row has maximum age |# who is the oldest driver ?print(df[df.Age == df.Age.max()]) Output: Code #1: Shows min on Driver, Points, Age columns. # importing pandas and numpyimport pandas as pdimport numpy as np # data of 2018 drivers world championshipdict1 ={'Driver':['Hamilton', 'Vettel', 'Raikkonen', 'Verstappen', 'Bottas', 'Ricciardo', 'Hulkenberg', 'Perez', 'Magnussen', 'Sainz', 'Alonso', 'Ocon', 'Leclerc', 'Grosjean', 'Gasly', 'Vandoorne', 'Ericsson', 'Stroll', 'Hartley', 'Sirotkin'], 'Points':[408, 320, 251, 249, 247, 170, 69, 62, 56, 53, 50, 49, 39, 37, 29, 12, 9, 6, 4, 1], 'Age':[33, 31, 39, 21, 29, 29, 31, 28, 26, 24, 37, 22, 21, 32, 22, 26, 28, 20, 29, 23]} # creating dataframe using DataFrame constructordf = pd.DataFrame(dict1) # the result shows min on # Driver, Points, Age columns.print(df.min()) Output: Code #2: Who scored less points # importing pandas and numpyimport pandas as pdimport numpy as np # data of 2018 drivers world championshipdict1 ={'Driver':['Hamilton', 'Vettel', 'Raikkonen', 'Verstappen', 'Bottas', 'Ricciardo', 'Hulkenberg', 'Perez', 'Magnussen', 'Sainz', 'Alonso', 'Ocon', 'Leclerc', 'Grosjean', 'Gasly', 'Vandoorne', 'Ericsson', 'Stroll', 'Hartley', 'Sirotkin'], 'Points':[408, 320, 251, 249, 247, 170, 69, 62, 56, 53, 50, 49, 39, 37, 29, 12, 9, 6, 4, 1], 'Age':[33, 31, 39, 21, 29, 29, 31, 28, 26, 24, 37, 22, 21, 32, 22, 26, 28, 20, 29, 23]} # creating dataframe using DataFrame constructordf = pd.DataFrame(dict1) # Who scored less points ?print(df[df.Points == df.Points.min()]) Output: Code #3: Which row has minimum age in the dataframe | who is the youngest driver # importing pandas and numpyimport pandas as pdimport numpy as np # data of 2018 drivers world championshipdict1 ={'Driver':['Hamilton', 'Vettel', 'Raikkonen', 'Verstappen', 'Bottas', 'Ricciardo', 'Hulkenberg', 'Perez', 'Magnussen', 'Sainz', 'Alonso', 'Ocon', 'Leclerc', 'Grosjean', 'Gasly', 'Vandoorne', 'Ericsson', 'Stroll', 'Hartley', 'Sirotkin'], 'Points':[408, 320, 251, 249, 247, 170, 69, 62, 56, 53, 50, 49, 39, 37, 29, 12, 9, 6, 4, 1], 'Age':[33, 31, 39, 21, 29, 29, 31, 28, 26, 24, 37, 22, 21, 32, 22, 26, 28, 20, 29, 23]} # creating dataframe using DataFrame constructordf = pd.DataFrame(dict1) # Which row has maximum age | # who is the youngest driver ?print(df[df.Age == df.Age.min()]) Output: pandas-dataframe-program Picked Python pandas-dataFrame Python-pandas Technical Scripter 2018 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 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 Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Jan, 2019" }, { "code": null, "e": 144, "s": 28, "text": "Let’s see how can we select row with maximum and minimum value in Pandas dataframe with help of different examples." }, { "code": null, "e": 167, "s": 144, "text": "Consider this dataset." }, { "code": "# importing pandas and numpyimport pandas as pdimport numpy as np # data of 2018 drivers world championshipdict1 ={'Driver':['Hamilton', 'Vettel', 'Raikkonen', 'Verstappen', 'Bottas', 'Ricciardo', 'Hulkenberg', 'Perez', 'Magnussen', 'Sainz', 'Alonso', 'Ocon', 'Leclerc', 'Grosjean', 'Gasly', 'Vandoorne', 'Ericsson', 'Stroll', 'Hartley', 'Sirotkin'], 'Points':[408, 320, 251, 249, 247, 170, 69, 62, 56, 53, 50, 49, 39, 37, 29, 12, 9, 6, 4, 1], 'Age':[33, 31, 39, 21, 29, 29, 31, 28, 26, 24, 37, 22, 21, 32, 22, 26, 28, 20, 29, 23]} # creating dataframe using DataFrame constructordf = pd.DataFrame(dict1)print(df.head(10))", "e": 994, "s": 167, "text": null }, { "code": null, "e": 1002, "s": 994, "text": "Output:" }, { "code": null, "e": 1053, "s": 1002, "text": "Code #1: Shows max on Driver, Points, Age columns." }, { "code": "# importing pandas and numpyimport pandas as pdimport numpy as np # data of 2018 drivers world championshipdict1 ={'Driver':['Hamilton', 'Vettel', 'Raikkonen', 'Verstappen', 'Bottas', 'Ricciardo', 'Hulkenberg', 'Perez', 'Magnussen', 'Sainz', 'Alonso', 'Ocon', 'Leclerc', 'Grosjean', 'Gasly', 'Vandoorne', 'Ericsson', 'Stroll', 'Hartley', 'Sirotkin'], 'Points':[408, 320, 251, 249, 247, 170, 69, 62, 56, 53, 50, 49, 39, 37, 29, 12, 9, 6, 4, 1], 'Age':[33, 31, 39, 21, 29, 29, 31, 28, 26, 24, 37, 22, 21, 32, 22, 26, 28, 20, 29, 23]} # creating dataframe using DataFrame constructordf = pd.DataFrame(dict1) # the result shows max on# Driver, Points, Age columns.print(df.max())", "e": 1934, "s": 1053, "text": null }, { "code": null, "e": 1973, "s": 1934, "text": "Output: Code #2: Who scored max points" }, { "code": "# importing pandas and numpyimport pandas as pdimport numpy as np # data of 2018 drivers world championshipdict1 ={'Driver':['Hamilton', 'Vettel', 'Raikkonen', 'Verstappen', 'Bottas', 'Ricciardo', 'Hulkenberg', 'Perez', 'Magnussen', 'Sainz', 'Alonso', 'Ocon', 'Leclerc', 'Grosjean', 'Gasly', 'Vandoorne', 'Ericsson', 'Stroll', 'Hartley', 'Sirotkin'], 'Points':[408, 320, 251, 249, 247, 170, 69, 62, 56, 53, 50, 49, 39, 37, 29, 12, 9, 6, 4, 1], 'Age':[33, 31, 39, 21, 29, 29, 31, 28, 26, 24, 37, 22, 21, 32, 22, 26, 28, 20, 29, 23]} # creating dataframe using DataFrame constructordf = pd.DataFrame(dict1) # Who scored more points ?print(df[df.Points == df.Points.max()])", "e": 2849, "s": 1973, "text": null }, { "code": null, "e": 2858, "s": 2849, "text": "Output: " }, { "code": null, "e": 2891, "s": 2858, "text": "Code #3: What is the maximum age" }, { "code": "# importing pandas and numpyimport pandas as pdimport numpy as np # data of 2018 drivers world championshipdict1 ={'Driver':['Hamilton', 'Vettel', 'Raikkonen', 'Verstappen', 'Bottas', 'Ricciardo', 'Hulkenberg', 'Perez', 'Magnussen', 'Sainz', 'Alonso', 'Ocon', 'Leclerc', 'Grosjean', 'Gasly', 'Vandoorne', 'Ericsson', 'Stroll', 'Hartley', 'Sirotkin'], 'Points':[408, 320, 251, 249, 247, 170, 69, 62, 56, 53, 50, 49, 39, 37, 29, 12, 9, 6, 4, 1], 'Age':[33, 31, 39, 21, 29, 29, 31, 28, 26, 24, 37, 22, 21, 32, 22, 26, 28, 20, 29, 23]} # creating dataframe using DataFrame constructordf = pd.DataFrame(dict1) # what is the maximum age ?print(df.Age.max())", "e": 3748, "s": 2891, "text": null }, { "code": null, "e": 3756, "s": 3748, "text": "Output:" }, { "code": null, "e": 3837, "s": 3756, "text": "Code #4: Which row has maximum age in the dataframe | who is the oldest driver ?" }, { "code": "# importing pandas and numpyimport pandas as pdimport numpy as np # data of 2018 drivers world championshipdict1 ={'Driver':['Hamilton', 'Vettel', 'Raikkonen', 'Verstappen', 'Bottas', 'Ricciardo', 'Hulkenberg', 'Perez', 'Magnussen', 'Sainz', 'Alonso', 'Ocon', 'Leclerc', 'Grosjean', 'Gasly', 'Vandoorne', 'Ericsson', 'Stroll', 'Hartley', 'Sirotkin'], 'Points':[408, 320, 251, 249, 247, 170, 69, 62, 56, 53, 50, 49, 39, 37, 29, 12, 9, 6, 4, 1], 'Age':[33, 31, 39, 21, 29, 29, 31, 28, 26, 24, 37, 22, 21, 32, 22, 26, 28, 20, 29, 23]} # creating dataframe using DataFrame constructordf = pd.DataFrame(dict1) # Which row has maximum age |# who is the oldest driver ?print(df[df.Age == df.Age.max()])", "e": 4738, "s": 3837, "text": null }, { "code": null, "e": 4746, "s": 4738, "text": "Output:" }, { "code": null, "e": 4797, "s": 4746, "text": "Code #1: Shows min on Driver, Points, Age columns." }, { "code": "# importing pandas and numpyimport pandas as pdimport numpy as np # data of 2018 drivers world championshipdict1 ={'Driver':['Hamilton', 'Vettel', 'Raikkonen', 'Verstappen', 'Bottas', 'Ricciardo', 'Hulkenberg', 'Perez', 'Magnussen', 'Sainz', 'Alonso', 'Ocon', 'Leclerc', 'Grosjean', 'Gasly', 'Vandoorne', 'Ericsson', 'Stroll', 'Hartley', 'Sirotkin'], 'Points':[408, 320, 251, 249, 247, 170, 69, 62, 56, 53, 50, 49, 39, 37, 29, 12, 9, 6, 4, 1], 'Age':[33, 31, 39, 21, 29, 29, 31, 28, 26, 24, 37, 22, 21, 32, 22, 26, 28, 20, 29, 23]} # creating dataframe using DataFrame constructordf = pd.DataFrame(dict1) # the result shows min on # Driver, Points, Age columns.print(df.min())", "e": 5679, "s": 4797, "text": null }, { "code": null, "e": 5688, "s": 5679, "text": "Output: " }, { "code": null, "e": 5720, "s": 5688, "text": "Code #2: Who scored less points" }, { "code": "# importing pandas and numpyimport pandas as pdimport numpy as np # data of 2018 drivers world championshipdict1 ={'Driver':['Hamilton', 'Vettel', 'Raikkonen', 'Verstappen', 'Bottas', 'Ricciardo', 'Hulkenberg', 'Perez', 'Magnussen', 'Sainz', 'Alonso', 'Ocon', 'Leclerc', 'Grosjean', 'Gasly', 'Vandoorne', 'Ericsson', 'Stroll', 'Hartley', 'Sirotkin'], 'Points':[408, 320, 251, 249, 247, 170, 69, 62, 56, 53, 50, 49, 39, 37, 29, 12, 9, 6, 4, 1], 'Age':[33, 31, 39, 21, 29, 29, 31, 28, 26, 24, 37, 22, 21, 32, 22, 26, 28, 20, 29, 23]} # creating dataframe using DataFrame constructordf = pd.DataFrame(dict1) # Who scored less points ?print(df[df.Points == df.Points.min()])", "e": 6596, "s": 5720, "text": null }, { "code": null, "e": 6685, "s": 6596, "text": "Output: Code #3: Which row has minimum age in the dataframe | who is the youngest driver" }, { "code": "# importing pandas and numpyimport pandas as pdimport numpy as np # data of 2018 drivers world championshipdict1 ={'Driver':['Hamilton', 'Vettel', 'Raikkonen', 'Verstappen', 'Bottas', 'Ricciardo', 'Hulkenberg', 'Perez', 'Magnussen', 'Sainz', 'Alonso', 'Ocon', 'Leclerc', 'Grosjean', 'Gasly', 'Vandoorne', 'Ericsson', 'Stroll', 'Hartley', 'Sirotkin'], 'Points':[408, 320, 251, 249, 247, 170, 69, 62, 56, 53, 50, 49, 39, 37, 29, 12, 9, 6, 4, 1], 'Age':[33, 31, 39, 21, 29, 29, 31, 28, 26, 24, 37, 22, 21, 32, 22, 26, 28, 20, 29, 23]} # creating dataframe using DataFrame constructordf = pd.DataFrame(dict1) # Which row has maximum age | # who is the youngest driver ?print(df[df.Age == df.Age.min()])", "e": 7589, "s": 6685, "text": null }, { "code": null, "e": 7597, "s": 7589, "text": "Output:" }, { "code": null, "e": 7622, "s": 7597, "text": "pandas-dataframe-program" }, { "code": null, "e": 7629, "s": 7622, "text": "Picked" }, { "code": null, "e": 7653, "s": 7629, "text": "Python pandas-dataFrame" }, { "code": null, "e": 7667, "s": 7653, "text": "Python-pandas" }, { "code": null, "e": 7691, "s": 7667, "text": "Technical Scripter 2018" }, { "code": null, "e": 7698, "s": 7691, "text": "Python" }, { "code": null, "e": 7717, "s": 7698, "text": "Technical Scripter" }, { "code": null, "e": 7815, "s": 7717, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7833, "s": 7815, "text": "Python Dictionary" }, { "code": null, "e": 7875, "s": 7833, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 7897, "s": 7875, "text": "Enumerate() in Python" }, { "code": null, "e": 7923, "s": 7897, "text": "Python String | replace()" }, { "code": null, "e": 7955, "s": 7923, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 7984, "s": 7955, "text": "*args and **kwargs in Python" }, { "code": null, "e": 8011, "s": 7984, "text": "Python Classes and Objects" }, { "code": null, "e": 8041, "s": 8011, "text": "Iterate over a list in Python" }, { "code": null, "e": 8062, "s": 8041, "text": "Python OOPs Concepts" } ]
Node.js process.hrtime( ) Method
29 Sep, 2021 The process.hrtime() method to measure code execution time which returns array which include current high-resolution real time in a [seconds, nanoseconds]. We measure the code execution time by providing the time returned by the first process.hrtime() call as a parameter in the second process.hrtime() call. The Advantage of process.hrtime() is it measures time very accurate execution time which last less than a millisecond. Syntax: process.hrtime([time]) Parameter: This method accept a single parameter as mentioned above an described below. time : The time is an optional parameter that must be the result of a previous process.hrtime() call to difference with the current time. Return Type: It returns an array of 2 ints. The 1. int contains the seconds and the 2. int the nanoseconds. These times are relative to an arbitrary time in the past, and not related to the time of day. Example 1: Javascript // Implement the function.. var hrTime = process.hrtime() // Time in millisecond...console.log("Time in millisecond is: ", hrTime[0] * 1000 + hrTime[1] / 1000000) Output: Time in millisecond is: 218394926745.5 Example 2: Javascript // Create a variable and call the process.hrtime() function.var start_time = process.hrtime(); // Print the Start time:console.log("Start Time:",start_time); // Make the add functionsetTimeout(function(){ // Create two variablevar a = '40',b = '50'; // Print the Addition result:console.log("Add of two number is :",(a - 0) + (b - 0)); // Create a variable and call the second process.hrtime() // function and pass the start time as parameter. var end_time = process.hrtime(start_time); // Print the Execution time. console.log("End Time:",end_time); }, 1000); Output: It means 1 second and 8779100 nanoseconds from start to end time is taken. Start Time: [ 682340, 452477300 ] Add of two number is : 90 End Time: [ 1, 8779100 ] Example 3: Javascript // Create a variable and call the process.hrtime() function.var start_time = process.hrtime(); // Print the Start time:console.log("Start Time:",start_time); // Make the add functionsetTimeout(function(){ console.log("Execution time will be calculated"+ " for printing this message...."); // Create a variable and call the second process.hrtime() // function and pass the start time as. var end_time = process.hrtime(start_time); // Print the Execution time. console.log("End Time:",end_time); }, 1000); Output: It means 1 second and 10987200 nanoseconds from start to end time is taken. Start Time: [ 682865, 516565300 ] Execution time will be calculated for printing this message.... End Time: [ 1, 10987200 ] Reference Taken : https://nodejs.org/api/process.html#process_process_hrtime_time sagartomar9927 kerbaton Node.js-Methods Node.js-process-module Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Sep, 2021" }, { "code": null, "e": 337, "s": 28, "text": "The process.hrtime() method to measure code execution time which returns array which include current high-resolution real time in a [seconds, nanoseconds]. We measure the code execution time by providing the time returned by the first process.hrtime() call as a parameter in the second process.hrtime() call." }, { "code": null, "e": 456, "s": 337, "text": "The Advantage of process.hrtime() is it measures time very accurate execution time which last less than a millisecond." }, { "code": null, "e": 464, "s": 456, "text": "Syntax:" }, { "code": null, "e": 487, "s": 464, "text": "process.hrtime([time])" }, { "code": null, "e": 575, "s": 487, "text": "Parameter: This method accept a single parameter as mentioned above an described below." }, { "code": null, "e": 713, "s": 575, "text": "time : The time is an optional parameter that must be the result of a previous process.hrtime() call to difference with the current time." }, { "code": null, "e": 916, "s": 713, "text": "Return Type: It returns an array of 2 ints. The 1. int contains the seconds and the 2. int the nanoseconds. These times are relative to an arbitrary time in the past, and not related to the time of day." }, { "code": null, "e": 927, "s": 916, "text": "Example 1:" }, { "code": null, "e": 938, "s": 927, "text": "Javascript" }, { "code": "// Implement the function.. var hrTime = process.hrtime() // Time in millisecond...console.log(\"Time in millisecond is: \", hrTime[0] * 1000 + hrTime[1] / 1000000)", "e": 1101, "s": 938, "text": null }, { "code": null, "e": 1111, "s": 1101, "text": " Output: " }, { "code": null, "e": 1151, "s": 1111, "text": "Time in millisecond is: 218394926745.5" }, { "code": null, "e": 1164, "s": 1153, "text": "Example 2:" }, { "code": null, "e": 1177, "s": 1166, "text": "Javascript" }, { "code": "// Create a variable and call the process.hrtime() function.var start_time = process.hrtime(); // Print the Start time:console.log(\"Start Time:\",start_time); // Make the add functionsetTimeout(function(){ // Create two variablevar a = '40',b = '50'; // Print the Addition result:console.log(\"Add of two number is :\",(a - 0) + (b - 0)); // Create a variable and call the second process.hrtime() // function and pass the start time as parameter. var end_time = process.hrtime(start_time); // Print the Execution time. console.log(\"End Time:\",end_time); }, 1000);", "e": 1762, "s": 1177, "text": null }, { "code": null, "e": 1845, "s": 1762, "text": "Output: It means 1 second and 8779100 nanoseconds from start to end time is taken." }, { "code": null, "e": 1930, "s": 1845, "text": "Start Time: [ 682340, 452477300 ]\nAdd of two number is : 90\nEnd Time: [ 1, 8779100 ]" }, { "code": null, "e": 1941, "s": 1930, "text": "Example 3:" }, { "code": null, "e": 1952, "s": 1941, "text": "Javascript" }, { "code": "// Create a variable and call the process.hrtime() function.var start_time = process.hrtime(); // Print the Start time:console.log(\"Start Time:\",start_time); // Make the add functionsetTimeout(function(){ console.log(\"Execution time will be calculated\"+ \" for printing this message....\"); // Create a variable and call the second process.hrtime() // function and pass the start time as. var end_time = process.hrtime(start_time); // Print the Execution time. console.log(\"End Time:\",end_time); }, 1000);", "e": 2497, "s": 1952, "text": null }, { "code": null, "e": 2584, "s": 2500, "text": "Output: It means 1 second and 10987200 nanoseconds from start to end time is taken." }, { "code": null, "e": 2710, "s": 2586, "text": "Start Time: [ 682865, 516565300 ]\nExecution time will be calculated for printing this message....\nEnd Time: [ 1, 10987200 ]" }, { "code": null, "e": 2794, "s": 2712, "text": "Reference Taken : https://nodejs.org/api/process.html#process_process_hrtime_time" }, { "code": null, "e": 2811, "s": 2796, "text": "sagartomar9927" }, { "code": null, "e": 2820, "s": 2811, "text": "kerbaton" }, { "code": null, "e": 2836, "s": 2820, "text": "Node.js-Methods" }, { "code": null, "e": 2859, "s": 2836, "text": "Node.js-process-module" }, { "code": null, "e": 2867, "s": 2859, "text": "Node.js" }, { "code": null, "e": 2884, "s": 2867, "text": "Web Technologies" } ]
Handling Errors in R Programming
28 Dec, 2021 Error Handling is a process in which we deal with unwanted or anomalous errors which may cause abnormal termination of the program during its execution. In R Programming, there are basically two ways in which we can implement an error handling mechanism. Either we can directly call the functions like stop() or warning(), or we can use the error options such as “warn” or “warning.expression”. The basic functions that one can use for error handling in the code : stop(...): It halts the evaluation of the current statement and generates a message argument. The control is returned to the top level. waiting(...): Its evaluation depends on the value of the error option warn. If the value of the warning is negative then it is ignored. In case the value is 0 (zero) they are stored and printed only after the top-level function completes its execution. If the value is 1 (one) then it is printed as soon as it has been encountered while if the value is 2 (two) then immediately the generated warning is converted into an error. tryCatch(...): It helps to evaluate the code and assign the exceptions. Generally, if we encounter any unexpected errors while executing a program we need an efficient and interactive way to debug the error and know what went wrong. However, some errors are expected but sometimes the models fail to fit and throw an error. There are basically three methods to handle such conditions and errors in R : try(): it helps us to continue with the execution of the program even when an error occurs. tryCatch(): it helps to handle the conditions and control what happens based on the conditions. withCallingHandlers(): it is an alternative to tryCatch() that takes care of the local handlers. Unlike other programming languages such as Java, C++, and so on, the try-catch-finally statements are used as a function in R. The main two conditions to be handled in tryCatch() are “errors” and “warnings”. Syntax: check = tryCatch({ expression }, warning = function(w){ code that handles the warnings }, error = function(e){ code that handles the errors }, finally = function(f){ clean-up code }) Example: R # R program illustrating error handling# Applying tryCatchtryCatch( # Specifying expression expr = { 1 + 1 print("Everything was fine.") }, # Specifying error message error = function(e){ print("There was an error message.") }, warning = function(w){ print("There was a warning message.") }, finally = { print("finally Executed") }) Output: [1] "Everything was fine." [1] "finally Executed" In R, withCallingHandlers() is a variant of tryCatch(). The only difference is tryCatch() deals with exiting handlers while withCallingHandlers() deals with local handlers. Example: R # R program illustrating error handling # Evaluation of tryCatchcheck <- function(expression){ withCallingHandlers(expression, warning = function(w){ message("warning:\n", w) }, error = function(e){ message("error:\n", e) }, finally = { message("Completed") })} check({10/2})check({10/0})check({10/'noe'}) Output: nikhilaggarwal3 kumar_satyam Picked R Error-handling R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change column name of a given DataFrame in R Filter data by multiple conditions in R using Dplyr How to Replace specific values in column in R DataFrame ? Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Loops in R (for, while, repeat) Adding elements in a vector in R programming - append() method Group by function in R using Dplyr How to change Row Names of DataFrame in R ? Convert Factor to Numeric and Numeric to Factor in R Programming
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Dec, 2021" }, { "code": null, "e": 519, "s": 54, "text": "Error Handling is a process in which we deal with unwanted or anomalous errors which may cause abnormal termination of the program during its execution. In R Programming, there are basically two ways in which we can implement an error handling mechanism. Either we can directly call the functions like stop() or warning(), or we can use the error options such as “warn” or “warning.expression”. The basic functions that one can use for error handling in the code :" }, { "code": null, "e": 655, "s": 519, "text": "stop(...): It halts the evaluation of the current statement and generates a message argument. The control is returned to the top level." }, { "code": null, "e": 1083, "s": 655, "text": "waiting(...): Its evaluation depends on the value of the error option warn. If the value of the warning is negative then it is ignored. In case the value is 0 (zero) they are stored and printed only after the top-level function completes its execution. If the value is 1 (one) then it is printed as soon as it has been encountered while if the value is 2 (two) then immediately the generated warning is converted into an error." }, { "code": null, "e": 1155, "s": 1083, "text": "tryCatch(...): It helps to evaluate the code and assign the exceptions." }, { "code": null, "e": 1485, "s": 1155, "text": "Generally, if we encounter any unexpected errors while executing a program we need an efficient and interactive way to debug the error and know what went wrong. However, some errors are expected but sometimes the models fail to fit and throw an error. There are basically three methods to handle such conditions and errors in R :" }, { "code": null, "e": 1577, "s": 1485, "text": "try(): it helps us to continue with the execution of the program even when an error occurs." }, { "code": null, "e": 1673, "s": 1577, "text": "tryCatch(): it helps to handle the conditions and control what happens based on the conditions." }, { "code": null, "e": 1770, "s": 1673, "text": "withCallingHandlers(): it is an alternative to tryCatch() that takes care of the local handlers." }, { "code": null, "e": 1978, "s": 1770, "text": "Unlike other programming languages such as Java, C++, and so on, the try-catch-finally statements are used as a function in R. The main two conditions to be handled in tryCatch() are “errors” and “warnings”." }, { "code": null, "e": 1986, "s": 1978, "text": "Syntax:" }, { "code": null, "e": 2185, "s": 1986, "text": "check = tryCatch({\n expression\n}, warning = function(w){\n code that handles the warnings\n}, error = function(e){\n code that handles the errors\n}, finally = function(f){\n clean-up code\n})" }, { "code": null, "e": 2195, "s": 2185, "text": "Example: " }, { "code": null, "e": 2197, "s": 2195, "text": "R" }, { "code": "# R program illustrating error handling# Applying tryCatchtryCatch( # Specifying expression expr = { 1 + 1 print(\"Everything was fine.\") }, # Specifying error message error = function(e){ print(\"There was an error message.\") }, warning = function(w){ print(\"There was a warning message.\") }, finally = { print(\"finally Executed\") })", "e": 2623, "s": 2197, "text": null }, { "code": null, "e": 2631, "s": 2623, "text": "Output:" }, { "code": null, "e": 2681, "s": 2631, "text": "[1] \"Everything was fine.\"\n[1] \"finally Executed\"" }, { "code": null, "e": 2855, "s": 2681, "text": "In R, withCallingHandlers() is a variant of tryCatch(). The only difference is tryCatch() deals with exiting handlers while withCallingHandlers() deals with local handlers. " }, { "code": null, "e": 2864, "s": 2855, "text": "Example:" }, { "code": null, "e": 2866, "s": 2864, "text": "R" }, { "code": "# R program illustrating error handling # Evaluation of tryCatchcheck <- function(expression){ withCallingHandlers(expression, warning = function(w){ message(\"warning:\\n\", w) }, error = function(e){ message(\"error:\\n\", e) }, finally = { message(\"Completed\") })} check({10/2})check({10/0})check({10/'noe'})", "e": 3244, "s": 2866, "text": null }, { "code": null, "e": 3252, "s": 3244, "text": "Output:" }, { "code": null, "e": 3268, "s": 3252, "text": "nikhilaggarwal3" }, { "code": null, "e": 3281, "s": 3268, "text": "kumar_satyam" }, { "code": null, "e": 3288, "s": 3281, "text": "Picked" }, { "code": null, "e": 3305, "s": 3288, "text": "R Error-handling" }, { "code": null, "e": 3316, "s": 3305, "text": "R Language" }, { "code": null, "e": 3414, "s": 3316, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3459, "s": 3414, "text": "Change column name of a given DataFrame in R" }, { "code": null, "e": 3511, "s": 3459, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 3569, "s": 3511, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 3621, "s": 3569, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 3679, "s": 3621, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 3711, "s": 3679, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 3774, "s": 3711, "text": "Adding elements in a vector in R programming - append() method" }, { "code": null, "e": 3809, "s": 3774, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 3853, "s": 3809, "text": "How to change Row Names of DataFrame in R ?" } ]
PyQt5 – QApplication
25 Aug, 2021 The QApplication class manages the GUI application’s control flow and main settings. It specializes in the QGuiApplication with some functionality needed for QWidget based applications. It handles widget specific initialization, finalization. For any GUI application using Qt, there is precisely one QApplication object, no matter whether the application has 0, 1, 2, or more windows at any given time. For non-QWidget based Qt applications, use QGuiApplication instead, as it does not depend on the QtWidgets library. We then create a window instance and execute the QApplication object in the event loop using sys.exit(App.exec()) command, below are some useful and frequently methods and property used with the QApplication object. Syntax: App = QApplication(sys.argv) Parameters: beep: Sounds the bell, using the default volume and sound. This function is not available in Qt for Embedded Linux setFont: It sets the default font of the PyQt5 Application aboutQt: Displays a simple message box about Qt. The message includes the version number of Qt being used by the application. closeAllWindows: Closes all top-level windows. This function is particularly useful for applications with many top-level windows. setAutoSipEnabled: It automatically displays the SIP when entering widgets that accept keyboard input setCursorFlashTime: This method sets the text cursor’s flash (blink) time in milliseconds setDoubleClickInterval: This method sets the time limit in milliseconds that distinguishes a double click from two consecutive mouse clicks Example: We will create a simple PyQt5 application which produces a beep sound when it gets executed and many properties are set to the QApplication object, below is the implementation Python3 # 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, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a push button push = QPushButton("Press", self) # setting geometry to the push button push.setGeometry(100, 100, 120, 40) # creating a label label = QLabel("GeeksforGeeks", self) # setting geometry to the label label.setGeometry(100, 160, 200, 50) # setting alignment to the label label.setAlignment(Qt.AlignCenter) # font font = QFont("Arial", 12) # setting font to the label label.setFont(font) # setting style sheet to the label label.setStyleSheet("QLabel" "{" "border : 2px solid green;" "background : lightgreen;" "}") # hiding the label label.hide() # adding action method to the push button push.clicked.connect(lambda: do_something()) # method called by the push button when pressed def do_something(): # unhide the label label.show() # create pyqt5 appApp = QApplication(sys.argv) # setting cursor flashtimeApp.setCursorFlashTime(100) # setting application object nameApp.setObjectName("GfG") # setting application display nameApp.setApplicationDisplayName("GfG PyQt5") # beep sound will occur when application# is openedApp.beep() # message displayed about the QtApp.aboutQt() # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output:When we execute the code firstly the about Qt page will get displayed Then our application will get started sumitgumber28 Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 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 Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Aug, 2021" }, { "code": null, "e": 547, "s": 28, "text": "The QApplication class manages the GUI application’s control flow and main settings. It specializes in the QGuiApplication with some functionality needed for QWidget based applications. It handles widget specific initialization, finalization. For any GUI application using Qt, there is precisely one QApplication object, no matter whether the application has 0, 1, 2, or more windows at any given time. For non-QWidget based Qt applications, use QGuiApplication instead, as it does not depend on the QtWidgets library." }, { "code": null, "e": 763, "s": 547, "text": "We then create a window instance and execute the QApplication object in the event loop using sys.exit(App.exec()) command, below are some useful and frequently methods and property used with the QApplication object." }, { "code": null, "e": 800, "s": 763, "text": "Syntax: App = QApplication(sys.argv)" }, { "code": null, "e": 812, "s": 800, "text": "Parameters:" }, { "code": null, "e": 927, "s": 812, "text": "beep: Sounds the bell, using the default volume and sound. This function is not available in Qt for Embedded Linux" }, { "code": null, "e": 987, "s": 927, "text": "setFont: It sets the default font of the PyQt5 Application " }, { "code": null, "e": 1114, "s": 987, "text": "aboutQt: Displays a simple message box about Qt. The message includes the version number of Qt being used by the application. " }, { "code": null, "e": 1244, "s": 1114, "text": "closeAllWindows: Closes all top-level windows. This function is particularly useful for applications with many top-level windows." }, { "code": null, "e": 1346, "s": 1244, "text": "setAutoSipEnabled: It automatically displays the SIP when entering widgets that accept keyboard input" }, { "code": null, "e": 1437, "s": 1346, "text": "setCursorFlashTime: This method sets the text cursor’s flash (blink) time in milliseconds " }, { "code": null, "e": 1577, "s": 1437, "text": "setDoubleClickInterval: This method sets the time limit in milliseconds that distinguishes a double click from two consecutive mouse clicks" }, { "code": null, "e": 1587, "s": 1577, "text": "Example: " }, { "code": null, "e": 1763, "s": 1587, "text": "We will create a simple PyQt5 application which produces a beep sound when it gets executed and many properties are set to the QApplication object, below is the implementation" }, { "code": null, "e": 1771, "s": 1763, "text": "Python3" }, { "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, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a push button push = QPushButton(\"Press\", self) # setting geometry to the push button push.setGeometry(100, 100, 120, 40) # creating a label label = QLabel(\"GeeksforGeeks\", self) # setting geometry to the label label.setGeometry(100, 160, 200, 50) # setting alignment to the label label.setAlignment(Qt.AlignCenter) # font font = QFont(\"Arial\", 12) # setting font to the label label.setFont(font) # setting style sheet to the label label.setStyleSheet(\"QLabel\" \"{\" \"border : 2px solid green;\" \"background : lightgreen;\" \"}\") # hiding the label label.hide() # adding action method to the push button push.clicked.connect(lambda: do_something()) # method called by the push button when pressed def do_something(): # unhide the label label.show() # create pyqt5 appApp = QApplication(sys.argv) # setting cursor flashtimeApp.setCursorFlashTime(100) # setting application object nameApp.setObjectName(\"GfG\") # setting application display nameApp.setApplicationDisplayName(\"GfG PyQt5\") # beep sound will occur when application# is openedApp.beep() # message displayed about the QtApp.aboutQt() # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 3770, "s": 1771, "text": null }, { "code": null, "e": 3848, "s": 3770, "text": "Output:When we execute the code firstly the about Qt page will get displayed " }, { "code": null, "e": 3887, "s": 3848, "text": "Then our application will get started " }, { "code": null, "e": 3901, "s": 3887, "text": "sumitgumber28" }, { "code": null, "e": 3913, "s": 3901, "text": "Python-PyQt" }, { "code": null, "e": 3920, "s": 3913, "text": "Python" }, { "code": null, "e": 4018, "s": 3920, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4060, "s": 4018, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 4082, "s": 4060, "text": "Enumerate() in Python" }, { "code": null, "e": 4117, "s": 4082, "text": "Read a file line by line in Python" }, { "code": null, "e": 4143, "s": 4117, "text": "Python String | replace()" }, { "code": null, "e": 4175, "s": 4143, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4204, "s": 4175, "text": "*args and **kwargs in Python" }, { "code": null, "e": 4231, "s": 4204, "text": "Python Classes and Objects" }, { "code": null, "e": 4261, "s": 4231, "text": "Iterate over a list in Python" }, { "code": null, "e": 4282, "s": 4261, "text": "Python OOPs Concepts" } ]
How to create a Scroll To Top button in React JS ?
12 Mar, 2021 You will see there are lots of websites, that are using a useful feature like if you’re scrolling the webpage, and now you are at the bottom of that page then you can use this button to scroll up automatically like skip to the content. The following example covers create a Scroll To Top button in React JS using useState() hook. Prerequisite: Basic knowledge of npm & create-react-app command. Basic knowledge of styled-components. Basic Knowledge of useState() React hooks. Basic Setup: You will start a new project using create-react-app so open your terminal and type. npx create-react-app react-scroll-top Now go to your react-scroll-top folder by typing the given command in the terminal. cd react-scroll-top Required module: Install the dependencies required in this project by typing the given command in the terminal. npm install --save styled-components npm install --save react-icons Now create the components folder in src then go to the components folder and create two files ScrollButton.js and Styles.js. Project Structure: The file structure in the project will look like this. Example: In this example, we will design a webpage with Scroll To Top button, for that we will need to manipulate the App.js file and other created components file. We create a state with the first element visible as an initial state having a value of the false and the second element as function setVisible() for updating the state. Then a function is created by the name toggleVisible which sets the value of the state to true when we scroll down the page more than 300px ( you can choose any value as per your choice). Otherwise, the state value is set to false. Then a function is created by the name scrollToTop in which we use the scrollTo method to scroll our page to the top. When we scroll down the page more than 300px, the function toggleVisible gets triggered as an event through window.addEventListener property and sets the state visible to true. Now our state is used to show the Scroll to top icon to the user. When the user clicks on this icon, the function scrollToTop gets triggered as an onClick() event which scrolls our page smoothly to the top. You can also use ‘auto’ behavior in place of ‘smooth’. ScrollButton.js import React, {useState} from 'react';import {FaArrowCircleUp} from 'react-icons/fa';import { Button } from './Styles'; const ScrollButton = () =>{ const [visible, setVisible] = useState(false) const toggleVisible = () => { const scrolled = document.documentElement.scrollTop; if (scrolled > 300){ setVisible(true) } else if (scrolled <= 300){ setVisible(false) } }; const scrollToTop = () =>{ window.scrollTo({ top: 0, behavior: 'smooth' /* you can also use 'auto' behaviour in place of 'smooth' */ }); }; window.addEventListener('scroll', toggleVisible); return ( <Button> <FaArrowCircleUp onClick={scrollToTop} style={{display: visible ? 'inline' : 'none'}} /> </Button> );} export default ScrollButton; Styles.js import styled from 'styled-components'; export const Heading = styled.h1` text-align: center; color: green;`; export const Content = styled.div` overflowY: scroll; height: 2500px;`; export const Button = styled.div` position: fixed; width: 100%; left: 50%; bottom: 40px; height: 20px; font-size: 3rem; z-index: 1; cursor: pointer; color: green;` App.js import { Fragment } from 'react';import ScrollButton from './components/ScrollButton';import { Content, Heading } from './components/Styles'; function App() { return ( <Fragment> <Heading>GeeksForGeeks</Heading> <Content /> <ScrollButton /> </Fragment> );} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output. Using default behavior (auto): See how it directly jumps to the top. Using smooth behavior: See how it goes smoothly to the top. Styled-components ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n12 Mar, 2021" }, { "code": null, "e": 382, "s": 52, "text": "You will see there are lots of websites, that are using a useful feature like if you’re scrolling the webpage, and now you are at the bottom of that page then you can use this button to scroll up automatically like skip to the content. The following example covers create a Scroll To Top button in React JS using useState() hook." }, { "code": null, "e": 396, "s": 382, "text": "Prerequisite:" }, { "code": null, "e": 447, "s": 396, "text": "Basic knowledge of npm & create-react-app command." }, { "code": null, "e": 485, "s": 447, "text": "Basic knowledge of styled-components." }, { "code": null, "e": 528, "s": 485, "text": "Basic Knowledge of useState() React hooks." }, { "code": null, "e": 625, "s": 528, "text": "Basic Setup: You will start a new project using create-react-app so open your terminal and type." }, { "code": null, "e": 663, "s": 625, "text": "npx create-react-app react-scroll-top" }, { "code": null, "e": 747, "s": 663, "text": "Now go to your react-scroll-top folder by typing the given command in the terminal." }, { "code": null, "e": 767, "s": 747, "text": "cd react-scroll-top" }, { "code": null, "e": 879, "s": 767, "text": "Required module: Install the dependencies required in this project by typing the given command in the terminal." }, { "code": null, "e": 947, "s": 879, "text": "npm install --save styled-components\nnpm install --save react-icons" }, { "code": null, "e": 1072, "s": 947, "text": "Now create the components folder in src then go to the components folder and create two files ScrollButton.js and Styles.js." }, { "code": null, "e": 1146, "s": 1072, "text": "Project Structure: The file structure in the project will look like this." }, { "code": null, "e": 1311, "s": 1146, "text": "Example: In this example, we will design a webpage with Scroll To Top button, for that we will need to manipulate the App.js file and other created components file." }, { "code": null, "e": 1712, "s": 1311, "text": "We create a state with the first element visible as an initial state having a value of the false and the second element as function setVisible() for updating the state. Then a function is created by the name toggleVisible which sets the value of the state to true when we scroll down the page more than 300px ( you can choose any value as per your choice). Otherwise, the state value is set to false." }, { "code": null, "e": 2269, "s": 1712, "text": "Then a function is created by the name scrollToTop in which we use the scrollTo method to scroll our page to the top. When we scroll down the page more than 300px, the function toggleVisible gets triggered as an event through window.addEventListener property and sets the state visible to true. Now our state is used to show the Scroll to top icon to the user. When the user clicks on this icon, the function scrollToTop gets triggered as an onClick() event which scrolls our page smoothly to the top. You can also use ‘auto’ behavior in place of ‘smooth’." }, { "code": null, "e": 2285, "s": 2269, "text": "ScrollButton.js" }, { "code": "import React, {useState} from 'react';import {FaArrowCircleUp} from 'react-icons/fa';import { Button } from './Styles'; const ScrollButton = () =>{ const [visible, setVisible] = useState(false) const toggleVisible = () => { const scrolled = document.documentElement.scrollTop; if (scrolled > 300){ setVisible(true) } else if (scrolled <= 300){ setVisible(false) } }; const scrollToTop = () =>{ window.scrollTo({ top: 0, behavior: 'smooth' /* you can also use 'auto' behaviour in place of 'smooth' */ }); }; window.addEventListener('scroll', toggleVisible); return ( <Button> <FaArrowCircleUp onClick={scrollToTop} style={{display: visible ? 'inline' : 'none'}} /> </Button> );} export default ScrollButton;", "e": 3083, "s": 2285, "text": null }, { "code": null, "e": 3093, "s": 3083, "text": "Styles.js" }, { "code": "import styled from 'styled-components'; export const Heading = styled.h1` text-align: center; color: green;`; export const Content = styled.div` overflowY: scroll; height: 2500px;`; export const Button = styled.div` position: fixed; width: 100%; left: 50%; bottom: 40px; height: 20px; font-size: 3rem; z-index: 1; cursor: pointer; color: green;`", "e": 3469, "s": 3093, "text": null }, { "code": null, "e": 3476, "s": 3469, "text": "App.js" }, { "code": "import { Fragment } from 'react';import ScrollButton from './components/ScrollButton';import { Content, Heading } from './components/Styles'; function App() { return ( <Fragment> <Heading>GeeksForGeeks</Heading> <Content /> <ScrollButton /> </Fragment> );} export default App;", "e": 3778, "s": 3476, "text": null }, { "code": null, "e": 3891, "s": 3778, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 3901, "s": 3891, "text": "npm start" }, { "code": null, "e": 4000, "s": 3901, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output." }, { "code": null, "e": 4069, "s": 4000, "text": "Using default behavior (auto): See how it directly jumps to the top." }, { "code": null, "e": 4129, "s": 4069, "text": "Using smooth behavior: See how it goes smoothly to the top." }, { "code": null, "e": 4147, "s": 4129, "text": "Styled-components" }, { "code": null, "e": 4155, "s": 4147, "text": "ReactJS" }, { "code": null, "e": 4172, "s": 4155, "text": "Web Technologies" } ]
Queue Interface In Java
08 Jul, 2022 The Queue interface is present in java.util package and extends the Collection interface is used to hold the elements about to be processed in FIFO(First In First Out) order. It is an ordered list of objects with its use limited to inserting elements at the end of the list and deleting elements from the start of the list, (i.e.), it follows the FIFO or the First-In-First-Out principle. Being an interface the queue needs a concrete class for the declaration and the most common classes are the PriorityQueue and LinkedList in Java. Note that neither of these implementations is thread-safe. PriorityBlockingQueue is one alternative implementation if the thread-safe implementation is needed. Declaration: The Queue interface is declared as: public interface Queue extends Collection Creating Queue Objects: Since Queue is an interface, objects cannot be created of the type queue. We always need a class which extends this list in order to create an object. And also, after the introduction of Generics in Java 1.5, it is possible to restrict the type of object that can be stored in the Queue. This type-safe queue can be defined as: // Obj is the type of the object to be stored in Queue Queue<Obj> queue = new PriorityQueue<Obj> (); Example: Queue Java // Java program to demonstrate a Queue import java.util.LinkedList;import java.util.Queue; public class QueueExample { public static void main(String[] args) { Queue<Integer> q = new LinkedList<>(); // Adds elements {0, 1, 2, 3, 4} to // the queue for (int i = 0; i < 5; i++) q.add(i); // Display contents of the queue. System.out.println("Elements of queue " + q); // To remove the head of queue. int removedele = q.remove(); System.out.println("removed element-" + removedele); System.out.println(q); // To view the head of queue int head = q.peek(); System.out.println("head of queue-" + head); // Rest all methods of collection // interface like size and contains // can be used with this // implementation. int size = q.size(); System.out.println("Size of queue-" + size); }} Elements of queue [0, 1, 2, 3, 4] removed element-0 [1, 2, 3, 4] head of queue-1 Size of queue-4 Let’s see how to perform a few frequently used operations on the queue using the Priority Queue class. 1. Adding Elements: In order to add an element in a queue, we can use the add() method. The insertion order is not retained in the PriorityQueue. The elements are stored based on the priority order which is ascending by default. Example Java // Java program to add elements// to a Queue import java.util.*; public class GFG { public static void main(String args[]) { Queue<String> pq = new PriorityQueue<>(); pq.add("Geeks"); pq.add("For"); pq.add("Geeks"); System.out.println(pq); }} [For, Geeks, Geeks] 2. Removing Elements: In order to remove an element from a queue, we can use the remove() method. If there are multiple such objects, then the first occurrence of the object is removed. Apart from that, poll() method is also used to remove the head and return it. Example Java // Java program to remove elements// from a Queue import java.util.*; public class GFG { public static void main(String args[]) { Queue<String> pq = new PriorityQueue<>(); pq.add("Geeks"); pq.add("For"); pq.add("Geeks"); System.out.println("Initial Queue " + pq); pq.remove("Geeks"); System.out.println("After Remove " + pq); System.out.println("Poll Method " + pq.poll()); System.out.println("Final Queue " + pq); }} Initial Queue [For, Geeks, Geeks] After Remove [For, Geeks] Poll Method For Final Queue [Geeks] 3. Iterating the Queue: There are multiple ways to iterate through the Queue. The most famous way is converting the queue to the array and traversing using the for loop. However, the queue also has an inbuilt iterator which can be used to iterate through the queue. Example Java // Java program to iterate elements// to a Queue import java.util.*; public class GFG { public static void main(String args[]) { Queue<String> pq = new PriorityQueue<>(); pq.add("Geeks"); pq.add("For"); pq.add("Geeks"); Iterator iterator = pq.iterator(); while (iterator.hasNext()) { System.out.print(iterator.next() + " "); } }} For Geeks Geeks Characteristics of a Queue: The following are the characteristics of the queue: The Queue is used to insert elements at the end of the queue and removes from the beginning of the queue. It follows FIFO concept. The Java Queue supports all methods of Collection interface including insertion, deletion, etc. LinkedList, ArrayBlockingQueue and PriorityQueue are the most frequently used implementations. If any null operation is performed on BlockingQueues, NullPointerException is thrown. The Queues which are available in java.util package are Unbounded Queues. The Queues which are available in java.util.concurrent package are the Bounded Queues. All Queues except the Deques supports insertion and removal at the tail and head of the queue respectively. The Deques support element insertion and removal at both ends. 1. PriorityQueue: PriorityQueue class which is implemented in the collection framework provides us a way to process the objects based on the priority. It is known that a queue follows the First-In-First-Out algorithm, but sometimes the elements of the queue are needed to be processed according to the priority, that’s when the PriorityQueue comes into play. Let’s see how to create a queue object using this class. Example Java // Java program to demonstrate the// creation of queue object using the// PriorityQueue class import java.util.*; class GfG { public static void main(String args[]) { // Creating empty priority queue Queue<Integer> pQueue = new PriorityQueue<Integer>(); // Adding items to the pQueue // using add() pQueue.add(10); pQueue.add(20); pQueue.add(15); // Printing the top element of // the PriorityQueue System.out.println(pQueue.peek()); // Printing the top element and removing it // from the PriorityQueue container System.out.println(pQueue.poll()); // Printing the top element again System.out.println(pQueue.peek()); }} 10 10 15 2. LinkedList: LinkedList is a class which is implemented in the collection framework which inherently implements the linked list data structure. It is a linear data structure where the elements are not stored in contiguous locations and every element is a separate object with a data part and address part. The elements are linked using pointers and addresses. Each element is known as a node. Due to the dynamicity and ease of insertions and deletions, they are preferred over the arrays or queues. Let’s see how to create a queue object using this class. Example Java // Java program to demonstrate the// creation of queue object using the// LinkedList class import java.util.*; class GfG { public static void main(String args[]) { // Creating empty LinkedList Queue<Integer> ll = new LinkedList<Integer>(); // Adding items to the ll // using add() ll.add(10); ll.add(20); ll.add(15); // Printing the top element of // the LinkedList System.out.println(ll.peek()); // Printing the top element and removing it // from the LinkedList container System.out.println(ll.poll()); // Printing the top element again System.out.println(ll.peek()); }} 10 10 20 3. PriorityBlockingQueue: It is to be noted that both the implementations, the PriorityQueue and LinkedList are not thread-safe. PriorityBlockingQueue is one alternative implementation if thread-safe implementation is needed. PriorityBlockingQueue is an unbounded blocking queue that uses the same ordering rules as class PriorityQueue and supplies blocking retrieval operations. Since it is unbounded, adding elements may sometimes fail due to resource exhaustion resulting in OutOfMemoryError. Let’s see how to create a queue object using this class. Example Java // Java program to demonstrate the// creation of queue object using the// PriorityBlockingQueue class import java.util.concurrent.PriorityBlockingQueue;import java.util.*; class GfG { public static void main(String args[]) { // Creating empty priority // blocking queue Queue<Integer> pbq = new PriorityBlockingQueue<Integer>(); // Adding items to the pbq // using add() pbq.add(10); pbq.add(20); pbq.add(15); // Printing the top element of // the PriorityBlockingQueue System.out.println(pbq.peek()); // Printing the top element and // removing it from the // PriorityBlockingQueue System.out.println(pbq.poll()); // Printing the top element again System.out.println(pbq.peek()); }} 10 10 15 The queue interface inherits all the methods present in the collections interface while implementing the following methods: Method Description Chinmoy Lenka BharatGupta3 codekaust KaashyapMSK siddharth chandran.e maxfuller5 adhavrushikesh6 nandinigujral hardikkoriintern Java-Collections java-queue Java Queue Java Queue Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Jul, 2022" }, { "code": null, "e": 441, "s": 52, "text": "The Queue interface is present in java.util package and extends the Collection interface is used to hold the elements about to be processed in FIFO(First In First Out) order. It is an ordered list of objects with its use limited to inserting elements at the end of the list and deleting elements from the start of the list, (i.e.), it follows the FIFO or the First-In-First-Out principle." }, { "code": null, "e": 747, "s": 441, "text": "Being an interface the queue needs a concrete class for the declaration and the most common classes are the PriorityQueue and LinkedList in Java. Note that neither of these implementations is thread-safe. PriorityBlockingQueue is one alternative implementation if the thread-safe implementation is needed." }, { "code": null, "e": 796, "s": 747, "text": "Declaration: The Queue interface is declared as:" }, { "code": null, "e": 840, "s": 796, "text": "public interface Queue extends Collection " }, { "code": null, "e": 1192, "s": 840, "text": "Creating Queue Objects: Since Queue is an interface, objects cannot be created of the type queue. We always need a class which extends this list in order to create an object. And also, after the introduction of Generics in Java 1.5, it is possible to restrict the type of object that can be stored in the Queue. This type-safe queue can be defined as:" }, { "code": null, "e": 1296, "s": 1192, "text": "// Obj is the type of the object to be stored in Queue \nQueue<Obj> queue = new PriorityQueue<Obj> (); " }, { "code": null, "e": 1311, "s": 1296, "text": "Example: Queue" }, { "code": null, "e": 1316, "s": 1311, "text": "Java" }, { "code": "// Java program to demonstrate a Queue import java.util.LinkedList;import java.util.Queue; public class QueueExample { public static void main(String[] args) { Queue<Integer> q = new LinkedList<>(); // Adds elements {0, 1, 2, 3, 4} to // the queue for (int i = 0; i < 5; i++) q.add(i); // Display contents of the queue. System.out.println(\"Elements of queue \" + q); // To remove the head of queue. int removedele = q.remove(); System.out.println(\"removed element-\" + removedele); System.out.println(q); // To view the head of queue int head = q.peek(); System.out.println(\"head of queue-\" + head); // Rest all methods of collection // interface like size and contains // can be used with this // implementation. int size = q.size(); System.out.println(\"Size of queue-\" + size); }}", "e": 2381, "s": 1316, "text": null }, { "code": null, "e": 2478, "s": 2381, "text": "Elements of queue [0, 1, 2, 3, 4]\nremoved element-0\n[1, 2, 3, 4]\nhead of queue-1\nSize of queue-4" }, { "code": null, "e": 2583, "s": 2480, "text": "Let’s see how to perform a few frequently used operations on the queue using the Priority Queue class." }, { "code": null, "e": 2813, "s": 2583, "text": "1. Adding Elements: In order to add an element in a queue, we can use the add() method. The insertion order is not retained in the PriorityQueue. The elements are stored based on the priority order which is ascending by default. " }, { "code": null, "e": 2821, "s": 2813, "text": "Example" }, { "code": null, "e": 2826, "s": 2821, "text": "Java" }, { "code": "// Java program to add elements// to a Queue import java.util.*; public class GFG { public static void main(String args[]) { Queue<String> pq = new PriorityQueue<>(); pq.add(\"Geeks\"); pq.add(\"For\"); pq.add(\"Geeks\"); System.out.println(pq); }}", "e": 3121, "s": 2826, "text": null }, { "code": null, "e": 3141, "s": 3121, "text": "[For, Geeks, Geeks]" }, { "code": null, "e": 3408, "s": 3143, "text": "2. Removing Elements: In order to remove an element from a queue, we can use the remove() method. If there are multiple such objects, then the first occurrence of the object is removed. Apart from that, poll() method is also used to remove the head and return it. " }, { "code": null, "e": 3416, "s": 3408, "text": "Example" }, { "code": null, "e": 3421, "s": 3416, "text": "Java" }, { "code": "// Java program to remove elements// from a Queue import java.util.*; public class GFG { public static void main(String args[]) { Queue<String> pq = new PriorityQueue<>(); pq.add(\"Geeks\"); pq.add(\"For\"); pq.add(\"Geeks\"); System.out.println(\"Initial Queue \" + pq); pq.remove(\"Geeks\"); System.out.println(\"After Remove \" + pq); System.out.println(\"Poll Method \" + pq.poll()); System.out.println(\"Final Queue \" + pq); }}", "e": 3927, "s": 3421, "text": null }, { "code": null, "e": 4023, "s": 3927, "text": "Initial Queue [For, Geeks, Geeks]\nAfter Remove [For, Geeks]\nPoll Method For\nFinal Queue [Geeks]" }, { "code": null, "e": 4292, "s": 4025, "text": "3. Iterating the Queue: There are multiple ways to iterate through the Queue. The most famous way is converting the queue to the array and traversing using the for loop. However, the queue also has an inbuilt iterator which can be used to iterate through the queue. " }, { "code": null, "e": 4300, "s": 4292, "text": "Example" }, { "code": null, "e": 4305, "s": 4300, "text": "Java" }, { "code": "// Java program to iterate elements// to a Queue import java.util.*; public class GFG { public static void main(String args[]) { Queue<String> pq = new PriorityQueue<>(); pq.add(\"Geeks\"); pq.add(\"For\"); pq.add(\"Geeks\"); Iterator iterator = pq.iterator(); while (iterator.hasNext()) { System.out.print(iterator.next() + \" \"); } }}", "e": 4714, "s": 4305, "text": null }, { "code": null, "e": 4730, "s": 4714, "text": "For Geeks Geeks" }, { "code": null, "e": 4812, "s": 4732, "text": "Characteristics of a Queue: The following are the characteristics of the queue:" }, { "code": null, "e": 4943, "s": 4812, "text": "The Queue is used to insert elements at the end of the queue and removes from the beginning of the queue. It follows FIFO concept." }, { "code": null, "e": 5039, "s": 4943, "text": "The Java Queue supports all methods of Collection interface including insertion, deletion, etc." }, { "code": null, "e": 5134, "s": 5039, "text": "LinkedList, ArrayBlockingQueue and PriorityQueue are the most frequently used implementations." }, { "code": null, "e": 5220, "s": 5134, "text": "If any null operation is performed on BlockingQueues, NullPointerException is thrown." }, { "code": null, "e": 5294, "s": 5220, "text": "The Queues which are available in java.util package are Unbounded Queues." }, { "code": null, "e": 5381, "s": 5294, "text": "The Queues which are available in java.util.concurrent package are the Bounded Queues." }, { "code": null, "e": 5553, "s": 5381, "text": "All Queues except the Deques supports insertion and removal at the tail and head of the queue respectively. The Deques support element insertion and removal at both ends. " }, { "code": null, "e": 5969, "s": 5553, "text": "1. PriorityQueue: PriorityQueue class which is implemented in the collection framework provides us a way to process the objects based on the priority. It is known that a queue follows the First-In-First-Out algorithm, but sometimes the elements of the queue are needed to be processed according to the priority, that’s when the PriorityQueue comes into play. Let’s see how to create a queue object using this class." }, { "code": null, "e": 5977, "s": 5969, "text": "Example" }, { "code": null, "e": 5982, "s": 5977, "text": "Java" }, { "code": "// Java program to demonstrate the// creation of queue object using the// PriorityQueue class import java.util.*; class GfG { public static void main(String args[]) { // Creating empty priority queue Queue<Integer> pQueue = new PriorityQueue<Integer>(); // Adding items to the pQueue // using add() pQueue.add(10); pQueue.add(20); pQueue.add(15); // Printing the top element of // the PriorityQueue System.out.println(pQueue.peek()); // Printing the top element and removing it // from the PriorityQueue container System.out.println(pQueue.poll()); // Printing the top element again System.out.println(pQueue.peek()); }}", "e": 6740, "s": 5982, "text": null }, { "code": null, "e": 6749, "s": 6740, "text": "10\n10\n15" }, { "code": null, "e": 7309, "s": 6751, "text": "2. LinkedList: LinkedList is a class which is implemented in the collection framework which inherently implements the linked list data structure. It is a linear data structure where the elements are not stored in contiguous locations and every element is a separate object with a data part and address part. The elements are linked using pointers and addresses. Each element is known as a node. Due to the dynamicity and ease of insertions and deletions, they are preferred over the arrays or queues. Let’s see how to create a queue object using this class." }, { "code": null, "e": 7317, "s": 7309, "text": "Example" }, { "code": null, "e": 7322, "s": 7317, "text": "Java" }, { "code": "// Java program to demonstrate the// creation of queue object using the// LinkedList class import java.util.*; class GfG { public static void main(String args[]) { // Creating empty LinkedList Queue<Integer> ll = new LinkedList<Integer>(); // Adding items to the ll // using add() ll.add(10); ll.add(20); ll.add(15); // Printing the top element of // the LinkedList System.out.println(ll.peek()); // Printing the top element and removing it // from the LinkedList container System.out.println(ll.poll()); // Printing the top element again System.out.println(ll.peek()); }}", "e": 8032, "s": 7322, "text": null }, { "code": null, "e": 8041, "s": 8032, "text": "10\n10\n20" }, { "code": null, "e": 8596, "s": 8043, "text": "3. PriorityBlockingQueue: It is to be noted that both the implementations, the PriorityQueue and LinkedList are not thread-safe. PriorityBlockingQueue is one alternative implementation if thread-safe implementation is needed. PriorityBlockingQueue is an unbounded blocking queue that uses the same ordering rules as class PriorityQueue and supplies blocking retrieval operations. Since it is unbounded, adding elements may sometimes fail due to resource exhaustion resulting in OutOfMemoryError. Let’s see how to create a queue object using this class." }, { "code": null, "e": 8604, "s": 8596, "text": "Example" }, { "code": null, "e": 8609, "s": 8604, "text": "Java" }, { "code": "// Java program to demonstrate the// creation of queue object using the// PriorityBlockingQueue class import java.util.concurrent.PriorityBlockingQueue;import java.util.*; class GfG { public static void main(String args[]) { // Creating empty priority // blocking queue Queue<Integer> pbq = new PriorityBlockingQueue<Integer>(); // Adding items to the pbq // using add() pbq.add(10); pbq.add(20); pbq.add(15); // Printing the top element of // the PriorityBlockingQueue System.out.println(pbq.peek()); // Printing the top element and // removing it from the // PriorityBlockingQueue System.out.println(pbq.poll()); // Printing the top element again System.out.println(pbq.peek()); }}", "e": 9442, "s": 8609, "text": null }, { "code": null, "e": 9451, "s": 9442, "text": "10\n10\n15" }, { "code": null, "e": 9577, "s": 9453, "text": "The queue interface inherits all the methods present in the collections interface while implementing the following methods:" }, { "code": null, "e": 9584, "s": 9577, "text": "Method" }, { "code": null, "e": 9596, "s": 9584, "text": "Description" }, { "code": null, "e": 9610, "s": 9596, "text": "Chinmoy Lenka" }, { "code": null, "e": 9623, "s": 9610, "text": "BharatGupta3" }, { "code": null, "e": 9633, "s": 9623, "text": "codekaust" }, { "code": null, "e": 9645, "s": 9633, "text": "KaashyapMSK" }, { "code": null, "e": 9666, "s": 9645, "text": "siddharth chandran.e" }, { "code": null, "e": 9677, "s": 9666, "text": "maxfuller5" }, { "code": null, "e": 9693, "s": 9677, "text": "adhavrushikesh6" }, { "code": null, "e": 9707, "s": 9693, "text": "nandinigujral" }, { "code": null, "e": 9724, "s": 9707, "text": "hardikkoriintern" }, { "code": null, "e": 9741, "s": 9724, "text": "Java-Collections" }, { "code": null, "e": 9752, "s": 9741, "text": "java-queue" }, { "code": null, "e": 9757, "s": 9752, "text": "Java" }, { "code": null, "e": 9763, "s": 9757, "text": "Queue" }, { "code": null, "e": 9768, "s": 9763, "text": "Java" }, { "code": null, "e": 9774, "s": 9768, "text": "Queue" }, { "code": null, "e": 9791, "s": 9774, "text": "Java-Collections" } ]
ISRO CS 2014 - GeeksforGeeks
27 Sep, 2021 while (m < n) if (x > y ) and (a < b) then a=a+1 y=y-1 end if m=m+1 end while = (number of edges) - (number of nodes) + 1 = 8-6+2 = 4 = Total number of regions = 4 = Total number of decision points + 1 = 3+1 = 4 S → SS S → (S) S → ε 1) S → (S) 2) S → (SS) 3) S → ((S)S) 4) S → ((SS)S) 5) S → (((S)S))S) 6) S → (((S)(S))S) 7) S → (((S)(S))(S)) [S → ε] 8) S → ((()(S))S) [S → ε] 9) S → ((()())S) [S → ε] 10) S → ((()())) Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 29498, "s": 29470, "text": "\n27 Sep, 2021" }, { "code": null, "e": 29599, "s": 29498, "text": "while (m < n)\n if (x > y ) and (a < b) then\n a=a+1\n y=y-1\n end if\n m=m+1 \nend while " }, { "code": null, "e": 29734, "s": 29599, "text": "= (number of edges) - (number of nodes) + 1 = 8-6+2 = 4\n= Total number of regions = 4\n= Total number of decision points + 1 = 3+1 = 4 " }, { "code": null, "e": 29756, "s": 29734, "text": "S → SS\nS → (S)\nS → ε\n" }, { "code": null, "e": 29957, "s": 29756, "text": "1) S → (S)\n2) S → (SS)\n3) S → ((S)S)\n4) S → ((SS)S)\n5) S → (((S)S))S)\n6) S → (((S)(S))S)\n7) S → (((S)(S))(S)) [S → ε] \n8) S → ((()(S))S) [S → ε]\n9) S → ((()())S) [S → ε] \n10) S → ((()()))\n" } ]
ABS() Function in SQL Server
29 Dec, 2020 ABS() function : This function in SQL Server is used to return the absolute value of a specified number. Absolute value is used for depicting the distance of a number on the number line from 0. The direction of the number from zero is not considered since the absolute value of a number is never negative. This function takes as an argument any numeric data type or any non-numeric data type that can be implicitly converted to a numeric data type. The value returned by this function is of the same data type as the numeric data type of the argument. Features : This function is used to find the absolute value of a specified number. This function accepts a single parameter. The accepted parameter is of numeric data type or any non-numeric data type that can be implicitly converted to a numeric data type. The returned value will be in the same data type as the numeric data type of the specified parameter. Syntax : SELECT ABS(number); Parameter : This method accepts a parameter as given below: number: Specified numeric value whose absolute value going to be returned. Returns : It returns the absolute value of a specified number. Example-1 : Getting the absolute value 0 of a specified number 0. SELECT ABS(0); Output : 0 Example-2 : Getting the absolute value .7 of a specified number -0.7 SELECT ABS(-0.7); Output : .7 Example-3 : Using ABS() function with a variable and getting the absolute value 123 of a specified number 123. DECLARE @Parameter_Value INT; SET @Parameter_Value = 123; SELECT ABS(@Parameter_Value); Output : 123 Example-4 : Using ABS() function with a variable and getting the absolute value 34.87 of a specified float value “-34.87”. DECLARE @Parameter_Value float; SET @Parameter_Value = -34.87; SELECT ABS(@Parameter_Value); Output : 34.869999999999997 Application : This function is used to return the absolute value of a specified numeric value. DBMS-SQL SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Dec, 2020" }, { "code": null, "e": 45, "s": 28, "text": "ABS() function :" }, { "code": null, "e": 580, "s": 45, "text": "This function in SQL Server is used to return the absolute value of a specified number. Absolute value is used for depicting the distance of a number on the number line from 0. The direction of the number from zero is not considered since the absolute value of a number is never negative. This function takes as an argument any numeric data type or any non-numeric data type that can be implicitly converted to a numeric data type. The value returned by this function is of the same data type as the numeric data type of the argument." }, { "code": null, "e": 591, "s": 580, "text": "Features :" }, { "code": null, "e": 663, "s": 591, "text": "This function is used to find the absolute value of a specified number." }, { "code": null, "e": 705, "s": 663, "text": "This function accepts a single parameter." }, { "code": null, "e": 838, "s": 705, "text": "The accepted parameter is of numeric data type or any non-numeric data type that can be implicitly converted to a numeric data type." }, { "code": null, "e": 940, "s": 838, "text": "The returned value will be in the same data type as the numeric data type of the specified parameter." }, { "code": null, "e": 949, "s": 940, "text": "Syntax :" }, { "code": null, "e": 969, "s": 949, "text": "SELECT ABS(number);" }, { "code": null, "e": 981, "s": 969, "text": "Parameter :" }, { "code": null, "e": 1029, "s": 981, "text": "This method accepts a parameter as given below:" }, { "code": null, "e": 1104, "s": 1029, "text": "number: Specified numeric value whose absolute value going to be returned." }, { "code": null, "e": 1114, "s": 1104, "text": "Returns :" }, { "code": null, "e": 1167, "s": 1114, "text": "It returns the absolute value of a specified number." }, { "code": null, "e": 1179, "s": 1167, "text": "Example-1 :" }, { "code": null, "e": 1233, "s": 1179, "text": "Getting the absolute value 0 of a specified number 0." }, { "code": null, "e": 1248, "s": 1233, "text": "SELECT ABS(0);" }, { "code": null, "e": 1257, "s": 1248, "text": "Output :" }, { "code": null, "e": 1259, "s": 1257, "text": "0" }, { "code": null, "e": 1271, "s": 1259, "text": "Example-2 :" }, { "code": null, "e": 1328, "s": 1271, "text": "Getting the absolute value .7 of a specified number -0.7" }, { "code": null, "e": 1346, "s": 1328, "text": "SELECT ABS(-0.7);" }, { "code": null, "e": 1355, "s": 1346, "text": "Output :" }, { "code": null, "e": 1358, "s": 1355, "text": ".7" }, { "code": null, "e": 1370, "s": 1358, "text": "Example-3 :" }, { "code": null, "e": 1469, "s": 1370, "text": "Using ABS() function with a variable and getting the absolute value 123 of a specified number 123." }, { "code": null, "e": 1557, "s": 1469, "text": "DECLARE @Parameter_Value INT;\nSET @Parameter_Value = 123;\nSELECT ABS(@Parameter_Value);" }, { "code": null, "e": 1566, "s": 1557, "text": "Output :" }, { "code": null, "e": 1570, "s": 1566, "text": "123" }, { "code": null, "e": 1582, "s": 1570, "text": "Example-4 :" }, { "code": null, "e": 1693, "s": 1582, "text": "Using ABS() function with a variable and getting the absolute value 34.87 of a specified float value “-34.87”." }, { "code": null, "e": 1786, "s": 1693, "text": "DECLARE @Parameter_Value float;\nSET @Parameter_Value = -34.87;\nSELECT ABS(@Parameter_Value);" }, { "code": null, "e": 1795, "s": 1786, "text": "Output :" }, { "code": null, "e": 1814, "s": 1795, "text": "34.869999999999997" }, { "code": null, "e": 1828, "s": 1814, "text": "Application :" }, { "code": null, "e": 1909, "s": 1828, "text": "This function is used to return the absolute value of a specified numeric value." }, { "code": null, "e": 1918, "s": 1909, "text": "DBMS-SQL" }, { "code": null, "e": 1929, "s": 1918, "text": "SQL-Server" }, { "code": null, "e": 1933, "s": 1929, "text": "SQL" }, { "code": null, "e": 1937, "s": 1933, "text": "SQL" } ]
How to draw with mouse in HTML 5 canvas ?
20 Mar, 2020 In this article, we shall explore a few ways to draw with the mouse pointer on the HTML 5 canvas. The HTML canvas is essentially a container for various graphics elements such as squares, rectangles, arcs, images, etc. It gives us flexible control over animating the graphics elements inside the canvas. However, functionality to the canvas has to be added through JavaScript. In the following procedure, we will use a flag variable to toggle the drawing on and off in relation to the mouse events. The events we will be listening to the mousedown, mouseup and the mousemove events in JavaScript. The canvas element by default has some properties such as padding etc.(can be changed styles). Hence, properties offsetTop and offsetLeft are used to retrieve the position of the canvas, relative to its offsetParent (closest ancestor element of the canvas in the DOM). By subtracting these values from event.clientX and event.clientY, we can reposition the starting point of the drawing to the tip of the cursor. In the function sketch(), we use the following in-built methods to add functionality. beginPath(): Starts a new path, every time left mouse button is clicked. lineWidth: Sets the width of the line that will be drawn. strokeStyle: In this regard, we use it to set the color of the line to black. This attribute can be changed to produce lines of different colors. moveTo(): The Starting position of the path moves to the specified coordinates on the canvas. lineTo(): Creates a line to from the said position to the coordinates specified. stroke(): Adds stroke to the line created. Without this, the line will not be visible. Creating a Canvas Element:<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title> Draw with the mouse in a HTML5 canvas </title> <style> * { overflow: hidden; } body { text-align: center; } h1 { color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <b>Draw anything you want</b> <hr> <canvas id="canvas"></canvas> <script src="index.js"></script></body> </html> <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title> Draw with the mouse in a HTML5 canvas </title> <style> * { overflow: hidden; } body { text-align: center; } h1 { color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <b>Draw anything you want</b> <hr> <canvas id="canvas"></canvas> <script src="index.js"></script></body> </html> JavaScript code to make interactive canvas:// wait for the content of the window element// to load, then performs the operations.// This is considered best practice.window.addEventListener('load', ()=>{ resize(); // Resizes the canvas once the window loads document.addEventListener('mousedown', startPainting); document.addEventListener('mouseup', stopPainting); document.addEventListener('mousemove', sketch); window.addEventListener('resize', resize);}); const canvas = document.querySelector('#canvas'); // Context for the canvas for 2 dimensional operationsconst ctx = canvas.getContext('2d'); // Resizes the canvas to the available size of the window.function resize(){ ctx.canvas.width = window.innerWidth; ctx.canvas.height = window.innerHeight;} // Stores the initial position of the cursorlet coord = {x:0 , y:0}; // This is the flag that we are going to use to // trigger drawinglet paint = false; // Updates the coordianates of the cursor when // an event e is triggered to the coordinates where // the said event is triggered.function getPosition(event){ coord.x = event.clientX - canvas.offsetLeft; coord.y = event.clientY - canvas.offsetTop;} // The following functions toggle the flag to start// and stop drawingfunction startPainting(event){ paint = true; getPosition(event);}function stopPainting(){ paint = false;} function sketch(event){ if (!paint) return; ctx.beginPath(); ctx.lineWidth = 5; // Sets the end of the lines drawn // to a round shape. ctx.lineCap = 'round'; ctx.strokeStyle = 'green'; // The cursor to start drawing // moves to this coordinate ctx.moveTo(coord.x, coord.y); // The position of the cursor // gets updated as we move the // mouse around. getPosition(event); // A line is traced from start // coordinate to this coordinate ctx.lineTo(coord.x , coord.y); // Draws the line. ctx.stroke();} // wait for the content of the window element// to load, then performs the operations.// This is considered best practice.window.addEventListener('load', ()=>{ resize(); // Resizes the canvas once the window loads document.addEventListener('mousedown', startPainting); document.addEventListener('mouseup', stopPainting); document.addEventListener('mousemove', sketch); window.addEventListener('resize', resize);}); const canvas = document.querySelector('#canvas'); // Context for the canvas for 2 dimensional operationsconst ctx = canvas.getContext('2d'); // Resizes the canvas to the available size of the window.function resize(){ ctx.canvas.width = window.innerWidth; ctx.canvas.height = window.innerHeight;} // Stores the initial position of the cursorlet coord = {x:0 , y:0}; // This is the flag that we are going to use to // trigger drawinglet paint = false; // Updates the coordianates of the cursor when // an event e is triggered to the coordinates where // the said event is triggered.function getPosition(event){ coord.x = event.clientX - canvas.offsetLeft; coord.y = event.clientY - canvas.offsetTop;} // The following functions toggle the flag to start// and stop drawingfunction startPainting(event){ paint = true; getPosition(event);}function stopPainting(){ paint = false;} function sketch(event){ if (!paint) return; ctx.beginPath(); ctx.lineWidth = 5; // Sets the end of the lines drawn // to a round shape. ctx.lineCap = 'round'; ctx.strokeStyle = 'green'; // The cursor to start drawing // moves to this coordinate ctx.moveTo(coord.x, coord.y); // The position of the cursor // gets updated as we move the // mouse around. getPosition(event); // A line is traced from start // coordinate to this coordinate ctx.lineTo(coord.x , coord.y); // Draws the line. ctx.stroke();} Output: The function sketch() will only execute if the value of the flag is true.It is important to update the coordinates stored in the object coord after beginPath(), hence getPosition(event) is called. After linking the JavaScript file to the HTML file, the following code will be obtained. CSS-Misc HTML-Canvas HTML-Misc JavaScript-Misc Picked CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of CSS (Cascading Style Sheet) Design a Tribute Page using HTML & CSS How to set space between the flexbox ? How to Upload Image into Database and Display it using PHP ? Build a Survey Form using HTML and CSS REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Types of CSS (Cascading Style Sheet)
[ { "code": null, "e": 53, "s": 25, "text": "\n20 Mar, 2020" }, { "code": null, "e": 430, "s": 53, "text": "In this article, we shall explore a few ways to draw with the mouse pointer on the HTML 5 canvas. The HTML canvas is essentially a container for various graphics elements such as squares, rectangles, arcs, images, etc. It gives us flexible control over animating the graphics elements inside the canvas. However, functionality to the canvas has to be added through JavaScript." }, { "code": null, "e": 650, "s": 430, "text": "In the following procedure, we will use a flag variable to toggle the drawing on and off in relation to the mouse events. The events we will be listening to the mousedown, mouseup and the mousemove events in JavaScript." }, { "code": null, "e": 1149, "s": 650, "text": "The canvas element by default has some properties such as padding etc.(can be changed styles). Hence, properties offsetTop and offsetLeft are used to retrieve the position of the canvas, relative to its offsetParent (closest ancestor element of the canvas in the DOM). By subtracting these values from event.clientX and event.clientY, we can reposition the starting point of the drawing to the tip of the cursor. In the function sketch(), we use the following in-built methods to add functionality." }, { "code": null, "e": 1222, "s": 1149, "text": "beginPath(): Starts a new path, every time left mouse button is clicked." }, { "code": null, "e": 1280, "s": 1222, "text": "lineWidth: Sets the width of the line that will be drawn." }, { "code": null, "e": 1426, "s": 1280, "text": "strokeStyle: In this regard, we use it to set the color of the line to black. This attribute can be changed to produce lines of different colors." }, { "code": null, "e": 1520, "s": 1426, "text": "moveTo(): The Starting position of the path moves to the specified coordinates on the canvas." }, { "code": null, "e": 1601, "s": 1520, "text": "lineTo(): Creates a line to from the said position to the coordinates specified." }, { "code": null, "e": 1688, "s": 1601, "text": "stroke(): Adds stroke to the line created. Without this, the line will not be visible." }, { "code": null, "e": 2283, "s": 1688, "text": "Creating a Canvas Element:<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title> Draw with the mouse in a HTML5 canvas </title> <style> * { overflow: hidden; } body { text-align: center; } h1 { color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <b>Draw anything you want</b> <hr> <canvas id=\"canvas\"></canvas> <script src=\"index.js\"></script></body> </html>" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title> Draw with the mouse in a HTML5 canvas </title> <style> * { overflow: hidden; } body { text-align: center; } h1 { color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <b>Draw anything you want</b> <hr> <canvas id=\"canvas\"></canvas> <script src=\"index.js\"></script></body> </html>", "e": 2852, "s": 2283, "text": null }, { "code": null, "e": 4785, "s": 2852, "text": "JavaScript code to make interactive canvas:// wait for the content of the window element// to load, then performs the operations.// This is considered best practice.window.addEventListener('load', ()=>{ resize(); // Resizes the canvas once the window loads document.addEventListener('mousedown', startPainting); document.addEventListener('mouseup', stopPainting); document.addEventListener('mousemove', sketch); window.addEventListener('resize', resize);}); const canvas = document.querySelector('#canvas'); // Context for the canvas for 2 dimensional operationsconst ctx = canvas.getContext('2d'); // Resizes the canvas to the available size of the window.function resize(){ ctx.canvas.width = window.innerWidth; ctx.canvas.height = window.innerHeight;} // Stores the initial position of the cursorlet coord = {x:0 , y:0}; // This is the flag that we are going to use to // trigger drawinglet paint = false; // Updates the coordianates of the cursor when // an event e is triggered to the coordinates where // the said event is triggered.function getPosition(event){ coord.x = event.clientX - canvas.offsetLeft; coord.y = event.clientY - canvas.offsetTop;} // The following functions toggle the flag to start// and stop drawingfunction startPainting(event){ paint = true; getPosition(event);}function stopPainting(){ paint = false;} function sketch(event){ if (!paint) return; ctx.beginPath(); ctx.lineWidth = 5; // Sets the end of the lines drawn // to a round shape. ctx.lineCap = 'round'; ctx.strokeStyle = 'green'; // The cursor to start drawing // moves to this coordinate ctx.moveTo(coord.x, coord.y); // The position of the cursor // gets updated as we move the // mouse around. getPosition(event); // A line is traced from start // coordinate to this coordinate ctx.lineTo(coord.x , coord.y); // Draws the line. ctx.stroke();}" }, { "code": "// wait for the content of the window element// to load, then performs the operations.// This is considered best practice.window.addEventListener('load', ()=>{ resize(); // Resizes the canvas once the window loads document.addEventListener('mousedown', startPainting); document.addEventListener('mouseup', stopPainting); document.addEventListener('mousemove', sketch); window.addEventListener('resize', resize);}); const canvas = document.querySelector('#canvas'); // Context for the canvas for 2 dimensional operationsconst ctx = canvas.getContext('2d'); // Resizes the canvas to the available size of the window.function resize(){ ctx.canvas.width = window.innerWidth; ctx.canvas.height = window.innerHeight;} // Stores the initial position of the cursorlet coord = {x:0 , y:0}; // This is the flag that we are going to use to // trigger drawinglet paint = false; // Updates the coordianates of the cursor when // an event e is triggered to the coordinates where // the said event is triggered.function getPosition(event){ coord.x = event.clientX - canvas.offsetLeft; coord.y = event.clientY - canvas.offsetTop;} // The following functions toggle the flag to start// and stop drawingfunction startPainting(event){ paint = true; getPosition(event);}function stopPainting(){ paint = false;} function sketch(event){ if (!paint) return; ctx.beginPath(); ctx.lineWidth = 5; // Sets the end of the lines drawn // to a round shape. ctx.lineCap = 'round'; ctx.strokeStyle = 'green'; // The cursor to start drawing // moves to this coordinate ctx.moveTo(coord.x, coord.y); // The position of the cursor // gets updated as we move the // mouse around. getPosition(event); // A line is traced from start // coordinate to this coordinate ctx.lineTo(coord.x , coord.y); // Draws the line. ctx.stroke();}", "e": 6675, "s": 4785, "text": null }, { "code": null, "e": 6969, "s": 6675, "text": "Output: The function sketch() will only execute if the value of the flag is true.It is important to update the coordinates stored in the object coord after beginPath(), hence getPosition(event) is called. After linking the JavaScript file to the HTML file, the following code will be obtained." }, { "code": null, "e": 6978, "s": 6969, "text": "CSS-Misc" }, { "code": null, "e": 6990, "s": 6978, "text": "HTML-Canvas" }, { "code": null, "e": 7000, "s": 6990, "text": "HTML-Misc" }, { "code": null, "e": 7016, "s": 7000, "text": "JavaScript-Misc" }, { "code": null, "e": 7023, "s": 7016, "text": "Picked" }, { "code": null, "e": 7027, "s": 7023, "text": "CSS" }, { "code": null, "e": 7032, "s": 7027, "text": "HTML" }, { "code": null, "e": 7049, "s": 7032, "text": "Web Technologies" }, { "code": null, "e": 7076, "s": 7049, "text": "Web technologies Questions" }, { "code": null, "e": 7081, "s": 7076, "text": "HTML" }, { "code": null, "e": 7179, "s": 7081, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7216, "s": 7179, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 7255, "s": 7216, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 7294, "s": 7255, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 7355, "s": 7294, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 7394, "s": 7355, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 7418, "s": 7394, "text": "REST API (Introduction)" }, { "code": null, "e": 7471, "s": 7418, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 7531, "s": 7471, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 7592, "s": 7531, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Python – Assign values to Values List
02 Sep, 2020 Given 2 dictionaries, assign values to value list elements mapping from dictionary 2. Input : test_dict = {‘Gfg’ : [3, 6], ‘best’ :[9]}, look_dict = {3 : [1, 5], 6 : “Best”, 9 : 12}Output : {‘Gfg’: {3: [1, 5], 6: ‘Best’}, ‘best’: {9: 12}}Explanation : 3 is replaced by key 3 and value [1, 5] and so on. Input : test_dict = {‘Gfg’ : [3, 6]}, look_dict = {3 : [1, 5], 6 : “Best”}Output : {‘Gfg’: {3: [1, 5], 6: ‘Best’}}Explanation : 3 is replaced by key 3 and value [1, 5] and so on. Method #1 : Using nested dictionary comprehension In this, we use inner dictionary comprehension to map values elements to dict 2, and outer dict is used to extract all keys from dictionary 1. Python3 # Python3 code to demonstrate working of # Assign values to Values List# Using nested dictionary comprehension # initializing dictionarytest_dict = {'Gfg' : [3, 6], 'is' : [4, 2], 'best' :[9]} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # initializing lookup dict look_dict = {3 : [1, 5], 6 : "Best", 4 : 10, 9 : 12, 2 : "CS"} # nested dictionaries to sought solutionres = {idx: {ikey: look_dict[ikey] for ikey in test_dict[idx]} for idx in test_dict} # printing result print("The mapped dictionary : " + str(res)) The original dictionary is : {'Gfg': [3, 6], 'is': [4, 2], 'best': [9]} The mapped dictionary : {'Gfg': {3: [1, 5], 6: 'Best'}, 'is': {4: 10, 2: 'CS'}, 'best': {9: 12}} Method #2 : Using items() + dictionary comprehension Similar to above method, another one-liner, difference being that items() is used for element access. Python3 # Python3 code to demonstrate working of# Assign values to Values List# Using items() + dictionary comprehension # initializing dictionarytest_dict = {'Gfg': [3, 6], 'is': [4, 2], 'best': [9]} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # initializing lookup dictlook_dict = {3: [1, 5], 6: "Best", 4: 10, 9: 12, 2: "CS"} # nested dictionaries to sought solution# items() used to access key-val pairsres = {key: {ikey: ival for (ikey, ival) in look_dict.items() if ikey in val} for (key, val) in test_dict.items()} # printing resultprint("The mapped dictionary : " + str(res)) The original dictionary is : {'Gfg': [3, 6], 'is': [4, 2], 'best': [9]} The mapped dictionary : {'Gfg': {3: [1, 5], 6: 'Best'}, 'is': {4: 10, 2: 'CS'}, 'best': {9: 12}} Python dictionary-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 Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Sep, 2020" }, { "code": null, "e": 114, "s": 28, "text": "Given 2 dictionaries, assign values to value list elements mapping from dictionary 2." }, { "code": null, "e": 331, "s": 114, "text": "Input : test_dict = {‘Gfg’ : [3, 6], ‘best’ :[9]}, look_dict = {3 : [1, 5], 6 : “Best”, 9 : 12}Output : {‘Gfg’: {3: [1, 5], 6: ‘Best’}, ‘best’: {9: 12}}Explanation : 3 is replaced by key 3 and value [1, 5] and so on." }, { "code": null, "e": 510, "s": 331, "text": "Input : test_dict = {‘Gfg’ : [3, 6]}, look_dict = {3 : [1, 5], 6 : “Best”}Output : {‘Gfg’: {3: [1, 5], 6: ‘Best’}}Explanation : 3 is replaced by key 3 and value [1, 5] and so on." }, { "code": null, "e": 560, "s": 510, "text": "Method #1 : Using nested dictionary comprehension" }, { "code": null, "e": 703, "s": 560, "text": "In this, we use inner dictionary comprehension to map values elements to dict 2, and outer dict is used to extract all keys from dictionary 1." }, { "code": null, "e": 711, "s": 703, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Assign values to Values List# Using nested dictionary comprehension # initializing dictionarytest_dict = {'Gfg' : [3, 6], 'is' : [4, 2], 'best' :[9]} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # initializing lookup dict look_dict = {3 : [1, 5], 6 : \"Best\", 4 : 10, 9 : 12, 2 : \"CS\"} # nested dictionaries to sought solutionres = {idx: {ikey: look_dict[ikey] for ikey in test_dict[idx]} for idx in test_dict} # printing result print(\"The mapped dictionary : \" + str(res)) ", "e": 1299, "s": 711, "text": null }, { "code": null, "e": 1469, "s": 1299, "text": "The original dictionary is : {'Gfg': [3, 6], 'is': [4, 2], 'best': [9]}\nThe mapped dictionary : {'Gfg': {3: [1, 5], 6: 'Best'}, 'is': {4: 10, 2: 'CS'}, 'best': {9: 12}}\n" }, { "code": null, "e": 1522, "s": 1469, "text": "Method #2 : Using items() + dictionary comprehension" }, { "code": null, "e": 1624, "s": 1522, "text": "Similar to above method, another one-liner, difference being that items() is used for element access." }, { "code": null, "e": 1632, "s": 1624, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Assign values to Values List# Using items() + dictionary comprehension # initializing dictionarytest_dict = {'Gfg': [3, 6], 'is': [4, 2], 'best': [9]} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # initializing lookup dictlook_dict = {3: [1, 5], 6: \"Best\", 4: 10, 9: 12, 2: \"CS\"} # nested dictionaries to sought solution# items() used to access key-val pairsres = {key: {ikey: ival for (ikey, ival) in look_dict.items() if ikey in val} for (key, val) in test_dict.items()} # printing resultprint(\"The mapped dictionary : \" + str(res))", "e": 2279, "s": 1632, "text": null }, { "code": null, "e": 2449, "s": 2279, "text": "The original dictionary is : {'Gfg': [3, 6], 'is': [4, 2], 'best': [9]}\nThe mapped dictionary : {'Gfg': {3: [1, 5], 6: 'Best'}, 'is': {4: 10, 2: 'CS'}, 'best': {9: 12}}\n" }, { "code": null, "e": 2476, "s": 2449, "text": "Python dictionary-programs" }, { "code": null, "e": 2483, "s": 2476, "text": "Python" }, { "code": null, "e": 2499, "s": 2483, "text": "Python Programs" }, { "code": null, "e": 2597, "s": 2499, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2615, "s": 2597, "text": "Python Dictionary" }, { "code": null, "e": 2657, "s": 2615, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2692, "s": 2657, "text": "Read a file line by line in Python" }, { "code": null, "e": 2718, "s": 2692, "text": "Python String | replace()" }, { "code": null, "e": 2750, "s": 2718, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2793, "s": 2750, "text": "Python program to convert a list to string" }, { "code": null, "e": 2815, "s": 2793, "text": "Defaultdict in Python" }, { "code": null, "e": 2854, "s": 2815, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2892, "s": 2854, "text": "Python | Convert a list to dictionary" } ]
Python program to convert integer to roman
21 Dec, 2021 Given an integer, the task is to write a Python program to convert integer to roman. Examples: Input: 5 Output: V Input: 9 Output: IX Input: 40 Output: XL Input: 1904 Output: MCMIV Below table shows the list of Roman symbols including their corresponding integer values also: Idea is to convert the units, tens, hundreds, and thousands of places of the given number separately. If the digit is 0, then there’s no corresponding Roman numeral symbol. The conversion of digits 4’s and 9’s are a little bit different from other digits because these digits follow subtractive notation. Algorithm to convert an Integer value to Roman Numeral Compare given number with base values in the order 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1. The base value that is just smaller or equal to the given number will be the initial base value (largest base value), Divide the number by its largest base value, the corresponding base symbol will be repeated quotient times, the remainder will then become the number for future division and repetitions. The process will be repeated until the number becomes zero. Initially number = 3549, Since 3549 >= 1000 ; largest base value will be 1000 initially. And Divide 3549/1000. Quotient = 3, Remainder =549. The corresponding symbol M will be repeated thrice. Now, number become 549 and 1000 > 549 >= 500, largest base value will be 500 then divide 549/500. Quotient = 1, Remainder =49. The corresponding symbol D will be repeated once. Now, number = 49 and 50 > 49 >= 40, largest base value is 40. Then divide 49/40. Quotient = 1, Remainder = 9. The corresponding symbol XL will be repeated once. Now, number = 9 and 10> 9 >= 9, largest base value is 9. Then divide 9/9. Quotient = 1, Remainder = 0. The corresponding symbol IX will be repeated once. Finally, the number becomes 0, the algorithm stops here. The output obtained MMMDXLIX. Below example shows the implementation of the above algorithm: Python3 # Python3 program to convert# integer value to roman values # Function to convert integer to Roman valuesdef printRoman(number): num = [1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000] sym = ["I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M"] i = 12 while number: div = number // num[i] number %= num[i] while div: print(sym[i], end = "") div -= 1 i -= 1 # Driver codeif __name__ == "__main__": number = 3549 print("Roman value is:", end = " ") printRoman(number) Output: Roman value is: MMMDXLIX In this method, we have to first observe the problem. The number given in the problem statement can be a maximum of 4 digits. The idea to solve this problem is: Divide the given number into digits at different places like one’s, two’s, hundred’s, or thousand’s. Starting from the thousand’s place print the corresponding roman value. For example, if the digit at thousand’s place is 3 then print the roman equivalent of 3000. Repeat the second step until we reach one’s place. Suppose the input number is 3549. So, starting from thousand’s place we will start printing the roman equivalent. In this case, we will print in the order as given below: The Roman equivalent of 3000 The Roman equivalent of 500 The Roman equivalent of 40 The Roman equivalent of 9 So, the output will be: MMMDXLIX The below example shows the implementation of the above approach: Python3 # Python3 program for above approach # Function to calculate Roman valuesdef intToRoman(num): # Storing roman values of digits from 0-9 # when placed at different places m = ["", "M", "MM", "MMM"] c = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM "] x = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"] i = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"] # Converting to roman thousands = m[num // 1000] hundreds = c[(num % 1000) // 100] tens = x[(num % 100) // 10] ones = i[num % 10] ans = (thousands + hundreds + tens + ones) return ans # Driver codeif __name__ == "__main__": number = 3549 print(intToRoman(number)) Output: MMMDXLIX In this approach, we consider the main significant digit in the number. Ex: in 1234, the main significant digit is 1. Similarly, in 345 it is 3. In order to extract main significant digit out, we need to maintain a divisor (lets call it div) like 1000 for 1234 (since 1234 / 1000 = 1) and 100 for 345 (345 / 100 = 3). Also, let’s maintain a dictionary called roman numeral = {1 : ‘I’, 5: ‘V’, 10: ‘X’, 50: ‘L’, 100: ‘C’, 500: ‘D’, 1000: ‘M’} The below example shows the implementation of the above algorithm: Python3 # Python 3 program to convert integer# number to Roman valuesimport math def integerToRoman(A): romansDict = \ { 1: "I", 5: "V", 10: "X", 50: "L", 100: "C", 500: "D", 1000: "M", 5000: "G", 10000: "H" } div = 1 while A >= div: div *= 10 div /= 10 res = "" while A: # main significant digit extracted # into lastNum lastNum = int(A / div) if lastNum <= 3: res += (romansDict[div] * lastNum) elif lastNum == 4: res += (romansDict[div] + romansDict[div * 5]) elif 5 <= lastNum <= 8: res += (romansDict[div * 5] + (romansDict[div] * (lastNum - 5))) elif lastNum == 9: res += (romansDict[div] + romansDict[div * 10]) A = math.floor(A % div) div /= 10 return res # Driver codeprint("Roman value for the integer is:" + str(integerToRoman(3549))) Output: Roman value for the integer is: MMMDXLIX simmytarika5 Picked Python math-library Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python OOPs Concepts Python Classes and Objects Introduction To PYTHON Python | os.path.join() method Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers Python program to check whether a number is Prime or not
[ { "code": null, "e": 53, "s": 25, "text": "\n21 Dec, 2021" }, { "code": null, "e": 138, "s": 53, "text": "Given an integer, the task is to write a Python program to convert integer to roman." }, { "code": null, "e": 150, "s": 138, "text": "Examples: " }, { "code": null, "e": 240, "s": 150, "text": "Input: 5\nOutput: V\n\nInput: 9\nOutput: IX\n\nInput: 40\nOutput: XL\n\nInput: 1904\nOutput: MCMIV" }, { "code": null, "e": 335, "s": 240, "text": "Below table shows the list of Roman symbols including their corresponding integer values also:" }, { "code": null, "e": 642, "s": 335, "text": "Idea is to convert the units, tens, hundreds, and thousands of places of the given number separately. If the digit is 0, then there’s no corresponding Roman numeral symbol. The conversion of digits 4’s and 9’s are a little bit different from other digits because these digits follow subtractive notation. " }, { "code": null, "e": 699, "s": 642, "text": "Algorithm to convert an Integer value to Roman Numeral " }, { "code": null, "e": 1169, "s": 699, "text": "Compare given number with base values in the order 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1. The base value that is just smaller or equal to the given number will be the initial base value (largest base value), Divide the number by its largest base value, the corresponding base symbol will be repeated quotient times, the remainder will then become the number for future division and repetitions. The process will be repeated until the number becomes zero." }, { "code": null, "e": 1362, "s": 1169, "text": "Initially number = 3549, Since 3549 >= 1000 ; largest base value will be 1000 initially. And Divide 3549/1000. Quotient = 3, Remainder =549. The corresponding symbol M will be repeated thrice." }, { "code": null, "e": 1539, "s": 1362, "text": "Now, number become 549 and 1000 > 549 >= 500, largest base value will be 500 then divide 549/500. Quotient = 1, Remainder =49. The corresponding symbol D will be repeated once." }, { "code": null, "e": 1700, "s": 1539, "text": "Now, number = 49 and 50 > 49 >= 40, largest base value is 40. Then divide 49/40. Quotient = 1, Remainder = 9. The corresponding symbol XL will be repeated once." }, { "code": null, "e": 1854, "s": 1700, "text": "Now, number = 9 and 10> 9 >= 9, largest base value is 9. Then divide 9/9. Quotient = 1, Remainder = 0. The corresponding symbol IX will be repeated once." }, { "code": null, "e": 1941, "s": 1854, "text": "Finally, the number becomes 0, the algorithm stops here. The output obtained MMMDXLIX." }, { "code": null, "e": 2005, "s": 1941, "text": "Below example shows the implementation of the above algorithm: " }, { "code": null, "e": 2013, "s": 2005, "text": "Python3" }, { "code": "# Python3 program to convert# integer value to roman values # Function to convert integer to Roman valuesdef printRoman(number): num = [1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000] sym = [\"I\", \"IV\", \"V\", \"IX\", \"X\", \"XL\", \"L\", \"XC\", \"C\", \"CD\", \"D\", \"CM\", \"M\"] i = 12 while number: div = number // num[i] number %= num[i] while div: print(sym[i], end = \"\") div -= 1 i -= 1 # Driver codeif __name__ == \"__main__\": number = 3549 print(\"Roman value is:\", end = \" \") printRoman(number)", "e": 2597, "s": 2013, "text": null }, { "code": null, "e": 2605, "s": 2597, "text": "Output:" }, { "code": null, "e": 2630, "s": 2605, "text": "Roman value is: MMMDXLIX" }, { "code": null, "e": 2793, "s": 2630, "text": "In this method, we have to first observe the problem. The number given in the problem statement can be a maximum of 4 digits. The idea to solve this problem is: " }, { "code": null, "e": 2894, "s": 2793, "text": "Divide the given number into digits at different places like one’s, two’s, hundred’s, or thousand’s." }, { "code": null, "e": 3058, "s": 2894, "text": "Starting from the thousand’s place print the corresponding roman value. For example, if the digit at thousand’s place is 3 then print the roman equivalent of 3000." }, { "code": null, "e": 3109, "s": 3058, "text": "Repeat the second step until we reach one’s place." }, { "code": null, "e": 3282, "s": 3109, "text": "Suppose the input number is 3549. So, starting from thousand’s place we will start printing the roman equivalent. In this case, we will print in the order as given below: " }, { "code": null, "e": 3311, "s": 3282, "text": "The Roman equivalent of 3000" }, { "code": null, "e": 3339, "s": 3311, "text": "The Roman equivalent of 500" }, { "code": null, "e": 3366, "s": 3339, "text": "The Roman equivalent of 40" }, { "code": null, "e": 3392, "s": 3366, "text": "The Roman equivalent of 9" }, { "code": null, "e": 3425, "s": 3392, "text": "So, the output will be: MMMDXLIX" }, { "code": null, "e": 3491, "s": 3425, "text": "The below example shows the implementation of the above approach:" }, { "code": null, "e": 3499, "s": 3491, "text": "Python3" }, { "code": "# Python3 program for above approach # Function to calculate Roman valuesdef intToRoman(num): # Storing roman values of digits from 0-9 # when placed at different places m = [\"\", \"M\", \"MM\", \"MMM\"] c = [\"\", \"C\", \"CC\", \"CCC\", \"CD\", \"D\", \"DC\", \"DCC\", \"DCCC\", \"CM \"] x = [\"\", \"X\", \"XX\", \"XXX\", \"XL\", \"L\", \"LX\", \"LXX\", \"LXXX\", \"XC\"] i = [\"\", \"I\", \"II\", \"III\", \"IV\", \"V\", \"VI\", \"VII\", \"VIII\", \"IX\"] # Converting to roman thousands = m[num // 1000] hundreds = c[(num % 1000) // 100] tens = x[(num % 100) // 10] ones = i[num % 10] ans = (thousands + hundreds + tens + ones) return ans # Driver codeif __name__ == \"__main__\": number = 3549 print(intToRoman(number))", "e": 4245, "s": 3499, "text": null }, { "code": null, "e": 4253, "s": 4245, "text": "Output:" }, { "code": null, "e": 4262, "s": 4253, "text": "MMMDXLIX" }, { "code": null, "e": 4704, "s": 4262, "text": "In this approach, we consider the main significant digit in the number. Ex: in 1234, the main significant digit is 1. Similarly, in 345 it is 3. In order to extract main significant digit out, we need to maintain a divisor (lets call it div) like 1000 for 1234 (since 1234 / 1000 = 1) and 100 for 345 (345 / 100 = 3). Also, let’s maintain a dictionary called roman numeral = {1 : ‘I’, 5: ‘V’, 10: ‘X’, 50: ‘L’, 100: ‘C’, 500: ‘D’, 1000: ‘M’}" }, { "code": null, "e": 4771, "s": 4704, "text": "The below example shows the implementation of the above algorithm:" }, { "code": null, "e": 4779, "s": 4771, "text": "Python3" }, { "code": "# Python 3 program to convert integer# number to Roman valuesimport math def integerToRoman(A): romansDict = \\ { 1: \"I\", 5: \"V\", 10: \"X\", 50: \"L\", 100: \"C\", 500: \"D\", 1000: \"M\", 5000: \"G\", 10000: \"H\" } div = 1 while A >= div: div *= 10 div /= 10 res = \"\" while A: # main significant digit extracted # into lastNum lastNum = int(A / div) if lastNum <= 3: res += (romansDict[div] * lastNum) elif lastNum == 4: res += (romansDict[div] + romansDict[div * 5]) elif 5 <= lastNum <= 8: res += (romansDict[div * 5] + (romansDict[div] * (lastNum - 5))) elif lastNum == 9: res += (romansDict[div] + romansDict[div * 10]) A = math.floor(A % div) div /= 10 return res # Driver codeprint(\"Roman value for the integer is:\" + str(integerToRoman(3549)))", "e": 5863, "s": 4779, "text": null }, { "code": null, "e": 5871, "s": 5863, "text": "Output:" }, { "code": null, "e": 5912, "s": 5871, "text": "Roman value for the integer is: MMMDXLIX" }, { "code": null, "e": 5925, "s": 5912, "text": "simmytarika5" }, { "code": null, "e": 5932, "s": 5925, "text": "Picked" }, { "code": null, "e": 5952, "s": 5932, "text": "Python math-library" }, { "code": null, "e": 5959, "s": 5952, "text": "Python" }, { "code": null, "e": 5975, "s": 5959, "text": "Python Programs" }, { "code": null, "e": 6073, "s": 5975, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6105, "s": 6073, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 6126, "s": 6105, "text": "Python OOPs Concepts" }, { "code": null, "e": 6153, "s": 6126, "text": "Python Classes and Objects" }, { "code": null, "e": 6176, "s": 6153, "text": "Introduction To PYTHON" }, { "code": null, "e": 6207, "s": 6176, "text": "Python | os.path.join() method" }, { "code": null, "e": 6229, "s": 6207, "text": "Defaultdict in Python" }, { "code": null, "e": 6268, "s": 6229, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 6306, "s": 6268, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 6343, "s": 6306, "text": "Python Program for Fibonacci numbers" } ]
Create a Bar chart using Recharts in ReactJS
27 Jul, 2021 Introduction: Rechart JS is a library that is used for creating charts for React JS. This library is used for building Line charts, Bar charts, Pie charts, etc, with the help of React and D3 (Data-Driven Documents). To create Bar Chart using Recharts, we create a dataset with x and y coordinate details. Then we define the bars using bar element with dataKey property which will have the data of the dataset created and then we create a cartesian grid and both axes using data coordinates. Creating React Application And Installing Module: Step 1: Create a React application using the following command.npx create-react-app foldername Step 1: Create a React application using the following command. npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command.cd foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command. cd foldername Step 3: After creating the ReactJS application, Install the required modules using the following command.npm install --save recharts Step 3: After creating the ReactJS application, Install the required modules using the following command. npm install --save recharts Project Structure: It will look like the following. Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React from 'react';import { BarChart, Bar, CartesianGrid, XAxis, YAxis } from 'recharts'; const App = () => { // Sample dataconst data = [ {name: 'Geeksforgeeks', students: 400}, {name: 'Technical scripter', students: 700}, {name: 'Geek-i-knack', students: 200}, {name: 'Geek-o-mania', students: 1000}]; return (<BarChart width={600} height={600} data={data}> <Bar dataKey="students" fill="green" /> <CartesianGrid stroke="#ccc" /> <XAxis dataKey="name" /> <YAxis /> </BarChart>);} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Output React-Questions Recharts JavaScript ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Jul, 2021" }, { "code": null, "e": 246, "s": 28, "text": "Introduction: Rechart JS is a library that is used for creating charts for React JS. This library is used for building Line charts, Bar charts, Pie charts, etc, with the help of React and D3 (Data-Driven Documents). " }, { "code": null, "e": 521, "s": 246, "text": "To create Bar Chart using Recharts, we create a dataset with x and y coordinate details. Then we define the bars using bar element with dataKey property which will have the data of the dataset created and then we create a cartesian grid and both axes using data coordinates." }, { "code": null, "e": 571, "s": 521, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 666, "s": 571, "text": "Step 1: Create a React application using the following command.npx create-react-app foldername" }, { "code": null, "e": 730, "s": 666, "text": "Step 1: Create a React application using the following command." }, { "code": null, "e": 762, "s": 730, "text": "npx create-react-app foldername" }, { "code": null, "e": 875, "s": 762, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command.cd foldername" }, { "code": null, "e": 975, "s": 875, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command." }, { "code": null, "e": 989, "s": 975, "text": "cd foldername" }, { "code": null, "e": 1122, "s": 989, "text": "Step 3: After creating the ReactJS application, Install the required modules using the following command.npm install --save recharts" }, { "code": null, "e": 1228, "s": 1122, "text": "Step 3: After creating the ReactJS application, Install the required modules using the following command." }, { "code": null, "e": 1256, "s": 1228, "text": "npm install --save recharts" }, { "code": null, "e": 1308, "s": 1256, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 1438, "s": 1308, "text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 1445, "s": 1438, "text": "App.js" }, { "code": "import React from 'react';import { BarChart, Bar, CartesianGrid, XAxis, YAxis } from 'recharts'; const App = () => { // Sample dataconst data = [ {name: 'Geeksforgeeks', students: 400}, {name: 'Technical scripter', students: 700}, {name: 'Geek-i-knack', students: 200}, {name: 'Geek-o-mania', students: 1000}]; return (<BarChart width={600} height={600} data={data}> <Bar dataKey=\"students\" fill=\"green\" /> <CartesianGrid stroke=\"#ccc\" /> <XAxis dataKey=\"name\" /> <YAxis /> </BarChart>);} export default App;", "e": 1979, "s": 1445, "text": null }, { "code": null, "e": 2092, "s": 1979, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 2102, "s": 2092, "text": "npm start" }, { "code": null, "e": 2201, "s": 2102, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 2208, "s": 2201, "text": "Output" }, { "code": null, "e": 2224, "s": 2208, "text": "React-Questions" }, { "code": null, "e": 2233, "s": 2224, "text": "Recharts" }, { "code": null, "e": 2244, "s": 2233, "text": "JavaScript" }, { "code": null, "e": 2252, "s": 2244, "text": "ReactJS" }, { "code": null, "e": 2269, "s": 2252, "text": "Web Technologies" } ]
Plot line graph from NumPy array
17 Dec, 2021 For plotting graphs in Python, we will use the Matplotlib library. Matplotlib is used along with NumPy data to plot any type of graph. From matplotlib we use the specific function i.e. pyplot(), which is used to plot two-dimensional data. Different functions used are explained below: np.arange(start, end): This function returns equally spaced values from the interval [start, end). plt.title(): It is used to give a title to the graph. Title is passed as the parameter to this function. plt.xlabel(): It sets the label name at X-axis. Name of X-axis is passed as argument to this function. plt.ylabel(): It sets the label name at Y-axis. Name of Y-axis is passed as argument to this function. plt.plot(): It plots the values of parameters passed to it together. plt.show(): It shows all the graph to the console. Example 1 : Python3 # importing the modulesimport numpy as npimport matplotlib.pyplot as plt # data to be plottedx = np.arange(1, 11)y = x * x # plottingplt.title("Line graph")plt.xlabel("X axis")plt.ylabel("Y axis")plt.plot(x, y, color ="red")plt.show() Output : Example 2 : Python3 # importing the libraryimport numpy as npimport matplotlib.pyplot as plt # data to be plottedx = np.arange(1, 11)y = np.array([100, 10, 300, 20, 500, 60, 700, 80, 900, 100]) # plottingplt.title("Line graph")plt.xlabel("X axis")plt.ylabel("Y axis")plt.plot(x, y, color ="green")plt.show() Output : simmytarika5 saurabh1990aror thordask Python-matplotlib Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n17 Dec, 2021" }, { "code": null, "e": 291, "s": 52, "text": "For plotting graphs in Python, we will use the Matplotlib library. Matplotlib is used along with NumPy data to plot any type of graph. From matplotlib we use the specific function i.e. pyplot(), which is used to plot two-dimensional data." }, { "code": null, "e": 337, "s": 291, "text": "Different functions used are explained below:" }, { "code": null, "e": 436, "s": 337, "text": "np.arange(start, end): This function returns equally spaced values from the interval [start, end)." }, { "code": null, "e": 541, "s": 436, "text": "plt.title(): It is used to give a title to the graph. Title is passed as the parameter to this function." }, { "code": null, "e": 644, "s": 541, "text": "plt.xlabel(): It sets the label name at X-axis. Name of X-axis is passed as argument to this function." }, { "code": null, "e": 747, "s": 644, "text": "plt.ylabel(): It sets the label name at Y-axis. Name of Y-axis is passed as argument to this function." }, { "code": null, "e": 816, "s": 747, "text": "plt.plot(): It plots the values of parameters passed to it together." }, { "code": null, "e": 867, "s": 816, "text": "plt.show(): It shows all the graph to the console." }, { "code": null, "e": 879, "s": 867, "text": "Example 1 :" }, { "code": null, "e": 887, "s": 879, "text": "Python3" }, { "code": "# importing the modulesimport numpy as npimport matplotlib.pyplot as plt # data to be plottedx = np.arange(1, 11)y = x * x # plottingplt.title(\"Line graph\")plt.xlabel(\"X axis\")plt.ylabel(\"Y axis\")plt.plot(x, y, color =\"red\")plt.show()", "e": 1122, "s": 887, "text": null }, { "code": null, "e": 1133, "s": 1122, "text": " Output : " }, { "code": null, "e": 1145, "s": 1133, "text": "Example 2 :" }, { "code": null, "e": 1153, "s": 1145, "text": "Python3" }, { "code": "# importing the libraryimport numpy as npimport matplotlib.pyplot as plt # data to be plottedx = np.arange(1, 11)y = np.array([100, 10, 300, 20, 500, 60, 700, 80, 900, 100]) # plottingplt.title(\"Line graph\")plt.xlabel(\"X axis\")plt.ylabel(\"Y axis\")plt.plot(x, y, color =\"green\")plt.show()", "e": 1441, "s": 1153, "text": null }, { "code": null, "e": 1452, "s": 1441, "text": " Output : " }, { "code": null, "e": 1467, "s": 1454, "text": "simmytarika5" }, { "code": null, "e": 1483, "s": 1467, "text": "saurabh1990aror" }, { "code": null, "e": 1492, "s": 1483, "text": "thordask" }, { "code": null, "e": 1510, "s": 1492, "text": "Python-matplotlib" }, { "code": null, "e": 1523, "s": 1510, "text": "Python-numpy" }, { "code": null, "e": 1530, "s": 1523, "text": "Python" } ]
Materialize CSS Grids
24 Mar, 2022 There are 12 standard columns fluid responsive grid systems that helps you to layout your page in an ordered and easy way. It uses the row and column style classes to define rows and columns respectively. Rows are used to specify a padding-less container to be used for responsive columns and col are used to specify a column with sub-classes. There is a container class used to center the page content. The container class is set to ~70% of the window width. To add a container just put your content inside a <div> tag with a container class. Here is the syntax: <body> <div class="container"> <!-- Page Content goes here --> </div> </body> Now let’s understand how the grid system works: The standard grid has 12 columns. No matter the size of the browser, each of these columns will always have equal width. Remember when creating a layout that all columns must be contained inside a row and that you must add the col class to your inner <div>s to make them into columns. You can easily change the order of your columns with push and pull. Simply add push-s2 or pull-s2 to the class where s is the screen class-prefix (s = small, m = medium, l = large), and the number after is the number of columns that you want to push or pull. Example: <!DOCTYPE html><html> <head> <!--Import Google Icon Font--> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <!-- Compiled and minified CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css"> <!-- Compiled and minified JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/js/materialize.min.js"> </script> <!--Let browser know website is optimized for mobile--> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /></head> <body> <div class="green center"> <h2>GeeksforGeeks</h2> </div> <div class="row"> <div class="col s1 green center">1</div> <div class="col s1 green darken-3 center">2</div> <div class="col s1 green center">3</div> <div class="col s1 green darken-3 center">4</div> <div class="col s1 green center">5</div> <div class="col s1 green darken-3 center">6</div> <div class="col s1 green center">7</div> <div class="col s1 green darken-3 center">8</div> <div class="col s1 green center">9</div> <div class="col s1 green darken-3 center">10</div> <div class="col s1 green center">11</div> <div class="col s1 green darken-3 center">12</div> </div> <div class="row"> <div class="col s7 push-s5 green darken-1"> <span class="flow-text"> This div is 7-columns wide on pushed to the right by 5-columns. </div> <div class="col s5 pull-s7 light-green"> <span class="flow-text"> 5-columns wide pulled to the left by 7-columns. </div> </div></body> </html> Grid Classes: The materialize grid system has four classes: .s (for mobile devices) .m (tablet devices) .l (desktop devices) .xl (large desktop devices) Mobile devices <= 600px Tablet devices > 600px Desktop devices > 992px Large desktop devices >1200px In the previous example, we only define the size for small screens using “col s12”. By just saying s12, we are essentially saying “col s12 m12 l12”. But by explicitly defining the size we can make our website more responsive. <!DOCTYPE html><html> <head> <!--Import Google Icon Font--> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <!-- Compiled and minified CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css"> <!-- Compiled and minified JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/js/materialize.min.js"> </script> <!--Let browser know website is optimized for mobile--> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /></head> <body> <div class="green center"> <h2>GeeksforGeeks</h2> </div> <!--Responsive layout--> <div class="row"> <div class="grid-example col s12 light-green center"> <span class="flow-text"> Always full-width (col s12) </div> <div class="grid-example col s8 m6 green center"> <span class="flow-text"> Full-width on mobile (col s8 m6) </div> </div></body> </html> Output: Materialize Materialize-CSS CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Mar, 2022" }, { "code": null, "e": 372, "s": 28, "text": "There are 12 standard columns fluid responsive grid systems that helps you to layout your page in an ordered and easy way. It uses the row and column style classes to define rows and columns respectively. Rows are used to specify a padding-less container to be used for responsive columns and col are used to specify a column with sub-classes." }, { "code": null, "e": 592, "s": 372, "text": "There is a container class used to center the page content. The container class is set to ~70% of the window width. To add a container just put your content inside a <div> tag with a container class. Here is the syntax:" }, { "code": null, "e": 693, "s": 592, "text": " <body>\n <div class=\"container\">\n <!-- Page Content goes here -->\n </div>\n </body>\n" }, { "code": null, "e": 741, "s": 693, "text": "Now let’s understand how the grid system works:" }, { "code": null, "e": 1285, "s": 741, "text": "The standard grid has 12 columns. No matter the size of the browser, each of these columns will always have equal width. Remember when creating a layout that all columns must be contained inside a row and that you must add the col class to your inner <div>s to make them into columns. You can easily change the order of your columns with push and pull. Simply add push-s2 or pull-s2 to the class where s is the screen class-prefix (s = small, m = medium, l = large), and the number after is the number of columns that you want to push or pull." }, { "code": null, "e": 1294, "s": 1285, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <!--Import Google Icon Font--> <link href=\"https://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\"> <!-- Compiled and minified CSS --> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css\"> <!-- Compiled and minified JavaScript --> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/js/materialize.min.js\"> </script> <!--Let browser know website is optimized for mobile--> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /></head> <body> <div class=\"green center\"> <h2>GeeksforGeeks</h2> </div> <div class=\"row\"> <div class=\"col s1 green center\">1</div> <div class=\"col s1 green darken-3 center\">2</div> <div class=\"col s1 green center\">3</div> <div class=\"col s1 green darken-3 center\">4</div> <div class=\"col s1 green center\">5</div> <div class=\"col s1 green darken-3 center\">6</div> <div class=\"col s1 green center\">7</div> <div class=\"col s1 green darken-3 center\">8</div> <div class=\"col s1 green center\">9</div> <div class=\"col s1 green darken-3 center\">10</div> <div class=\"col s1 green center\">11</div> <div class=\"col s1 green darken-3 center\">12</div> </div> <div class=\"row\"> <div class=\"col s7 push-s5 green darken-1\"> <span class=\"flow-text\"> This div is 7-columns wide on pushed to the right by 5-columns. </div> <div class=\"col s5 pull-s7 light-green\"> <span class=\"flow-text\"> 5-columns wide pulled to the left by 7-columns. </div> </div></body> </html>", "e": 3168, "s": 1294, "text": null }, { "code": null, "e": 3234, "s": 3168, "text": "Grid Classes: The materialize grid system has four classes:" }, { "code": null, "e": 3258, "s": 3234, "text": ".s (for mobile devices)" }, { "code": null, "e": 3278, "s": 3258, "text": ".m (tablet devices)" }, { "code": null, "e": 3299, "s": 3278, "text": ".l (desktop devices)" }, { "code": null, "e": 3328, "s": 3299, "text": ".xl (large desktop devices) " }, { "code": null, "e": 3343, "s": 3328, "text": "Mobile devices" }, { "code": null, "e": 3352, "s": 3343, "text": "<= 600px" }, { "code": null, "e": 3367, "s": 3352, "text": "Tablet devices" }, { "code": null, "e": 3375, "s": 3367, "text": "> 600px" }, { "code": null, "e": 3391, "s": 3375, "text": "Desktop devices" }, { "code": null, "e": 3399, "s": 3391, "text": "> 992px" }, { "code": null, "e": 3421, "s": 3399, "text": "Large desktop devices" }, { "code": null, "e": 3429, "s": 3421, "text": ">1200px" }, { "code": null, "e": 3655, "s": 3429, "text": "In the previous example, we only define the size for small screens using “col s12”. By just saying s12, we are essentially saying “col s12 m12 l12”. But by explicitly defining the size we can make our website more responsive." }, { "code": "<!DOCTYPE html><html> <head> <!--Import Google Icon Font--> <link href=\"https://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\"> <!-- Compiled and minified CSS --> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css\"> <!-- Compiled and minified JavaScript --> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/js/materialize.min.js\"> </script> <!--Let browser know website is optimized for mobile--> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /></head> <body> <div class=\"green center\"> <h2>GeeksforGeeks</h2> </div> <!--Responsive layout--> <div class=\"row\"> <div class=\"grid-example col s12 light-green center\"> <span class=\"flow-text\"> Always full-width (col s12) </div> <div class=\"grid-example col s8 m6 green center\"> <span class=\"flow-text\"> Full-width on mobile (col s8 m6) </div> </div></body> </html>", "e": 4838, "s": 3655, "text": null }, { "code": null, "e": 4846, "s": 4838, "text": "Output:" }, { "code": null, "e": 4858, "s": 4846, "text": "Materialize" }, { "code": null, "e": 4874, "s": 4858, "text": "Materialize-CSS" }, { "code": null, "e": 4878, "s": 4874, "text": "CSS" }, { "code": null, "e": 4895, "s": 4878, "text": "Web Technologies" } ]
How to fixed one column and scrollable other column or columns in Bootstrap ?
30 Nov, 2019 Bootstrap provides several built-in features to the users. This makes development faster and smoother. However, in some cases, external CSS and jQuery has to be implemented to the web page’s coding in order to give it a personalized touch. Usually, the Bootstrap grid is used to divide the web-page into 12 equal columns. These columns can be grouped together to create wider columns. The columns are responsive in nature. This means that the columns will cover the whole screen on big screens, but will stack on top of each other on small screen devices.When the webpage is divided into two equal columns, and the content inside the columns starts to overflow, the columns become scrollable. However, by doing some small modifications, the columns can be fixed. This article will demonstrate how to keep one column fixed, and the other column scrollable. Syntax: To fixed the column make not scrollable.<div class="col-sm-6 col-2 fixed-top one"> <div class="col-sm-6 col-2 fixed-top one"> To make the column scrollable.<div class="col-sm-6 offset-sm-6 two"> <div class="col-sm-6 offset-sm-6 two"> Below example illustrates the above approach: Example: You can run the code by hitting the run button so you can see the right column is scrollable but left is not. <!DOCTYPE html><html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> <style> .one{ background-color:lightgreen; } .two{ background-color:green; } .container-fluid{ font-size:120%; } </style> </head> <body> <div class="container-fluid"> <div class="row"> <div class="col-sm-6 col-2 fixed-top one"> <h2>Fixed</h2><br> It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. Also, any geeks can help other geeks by writing articles on the GeeksforGeeks, publishing articles follow few steps that are Articles that need little modification/ improvement from reviewers are published first. To quickly get your articles reviewed, please refer existing articles, their formatting style, coding style, and try to make you are close to them. Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. Also, any geeks can help other geeks by writing articles on the GeeksforGeeks, publishing articles follow few steps that are Articles that need little modification/ improvement from reviewers are published first. To </div> <div class="col-sm-6 offset-sm-6 two"> <h2>Scrollable</h2><br> It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. Also, any geeks can help other geeks by writing articles on the GeeksforGeeks, publishing articles follow few steps that are Articles that need little modification/ improvement from reviewers are published first. To quickly get your articles reviewed, please refer existing articles, their formatting style, coding style, and try to make you are close to them. Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. Also, any geeks can help other geeks by writing articles on the GeeksforGeeks, publishing articles follow few steps that are Articles that need little modification/ improvement from reviewers are published first. To </div> </div> </body></html> Output: Bootstrap-4 Bootstrap-Misc CSS-Misc HTML-Misc Picked Bootstrap Technical Scripter Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to set Bootstrap Timepicker using datetimepicker library ? How to pass data into a bootstrap modal? How to Show Images on Click using HTML ? How to Use Bootstrap with React? Difference between Bootstrap 4 and Bootstrap 5 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": "\n30 Nov, 2019" }, { "code": null, "e": 884, "s": 28, "text": "Bootstrap provides several built-in features to the users. This makes development faster and smoother. However, in some cases, external CSS and jQuery has to be implemented to the web page’s coding in order to give it a personalized touch. Usually, the Bootstrap grid is used to divide the web-page into 12 equal columns. These columns can be grouped together to create wider columns. The columns are responsive in nature. This means that the columns will cover the whole screen on big screens, but will stack on top of each other on small screen devices.When the webpage is divided into two equal columns, and the content inside the columns starts to overflow, the columns become scrollable. However, by doing some small modifications, the columns can be fixed. This article will demonstrate how to keep one column fixed, and the other column scrollable." }, { "code": null, "e": 892, "s": 884, "text": "Syntax:" }, { "code": null, "e": 975, "s": 892, "text": "To fixed the column make not scrollable.<div class=\"col-sm-6 col-2 fixed-top one\">" }, { "code": null, "e": 1018, "s": 975, "text": "<div class=\"col-sm-6 col-2 fixed-top one\">" }, { "code": null, "e": 1087, "s": 1018, "text": "To make the column scrollable.<div class=\"col-sm-6 offset-sm-6 two\">" }, { "code": null, "e": 1126, "s": 1087, "text": "<div class=\"col-sm-6 offset-sm-6 two\">" }, { "code": null, "e": 1172, "s": 1126, "text": "Below example illustrates the above approach:" }, { "code": null, "e": 1291, "s": 1172, "text": "Example: You can run the code by hitting the run button so you can see the right column is scrollable but left is not." }, { "code": "<!DOCTYPE html><html> <head> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script> <style> .one{ background-color:lightgreen; } .two{ background-color:green; } .container-fluid{ font-size:120%; } </style> </head> <body> <div class=\"container-fluid\"> <div class=\"row\"> <div class=\"col-sm-6 col-2 fixed-top one\"> <h2>Fixed</h2><br> It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. Also, any geeks can help other geeks by writing articles on the GeeksforGeeks, publishing articles follow few steps that are Articles that need little modification/ improvement from reviewers are published first. To quickly get your articles reviewed, please refer existing articles, their formatting style, coding style, and try to make you are close to them. Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. Also, any geeks can help other geeks by writing articles on the GeeksforGeeks, publishing articles follow few steps that are Articles that need little modification/ improvement from reviewers are published first. To </div> <div class=\"col-sm-6 offset-sm-6 two\"> <h2>Scrollable</h2><br> It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. Also, any geeks can help other geeks by writing articles on the GeeksforGeeks, publishing articles follow few steps that are Articles that need little modification/ improvement from reviewers are published first. To quickly get your articles reviewed, please refer existing articles, their formatting style, coding style, and try to make you are close to them. Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. Also, any geeks can help other geeks by writing articles on the GeeksforGeeks, publishing articles follow few steps that are Articles that need little modification/ improvement from reviewers are published first. To </div> </div> </body></html> ", "e": 5663, "s": 1291, "text": null }, { "code": null, "e": 5671, "s": 5663, "text": "Output:" }, { "code": null, "e": 5683, "s": 5671, "text": "Bootstrap-4" }, { "code": null, "e": 5698, "s": 5683, "text": "Bootstrap-Misc" }, { "code": null, "e": 5707, "s": 5698, "text": "CSS-Misc" }, { "code": null, "e": 5717, "s": 5707, "text": "HTML-Misc" }, { "code": null, "e": 5724, "s": 5717, "text": "Picked" }, { "code": null, "e": 5734, "s": 5724, "text": "Bootstrap" }, { "code": null, "e": 5753, "s": 5734, "text": "Technical Scripter" }, { "code": null, "e": 5770, "s": 5753, "text": "Web Technologies" }, { "code": null, "e": 5797, "s": 5770, "text": "Web technologies Questions" }, { "code": null, "e": 5895, "s": 5797, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5958, "s": 5895, "text": "How to set Bootstrap Timepicker using datetimepicker library ?" }, { "code": null, "e": 5999, "s": 5958, "text": "How to pass data into a bootstrap modal?" }, { "code": null, "e": 6040, "s": 5999, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 6073, "s": 6040, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 6120, "s": 6073, "text": "Difference between Bootstrap 4 and Bootstrap 5" }, { "code": null, "e": 6153, "s": 6120, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 6215, "s": 6153, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 6276, "s": 6215, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 6326, "s": 6276, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Java Runtime Polymorphism with multilevel inheritance
Method overriding is an example of runtime polymorphism. In method overriding, a subclass overrides a method with the same signature as that of in its superclass. During compile time, the check is made on the reference type. However, in the runtime, JVM figures out the object type and would run the method that belongs to that particular object. We can override a method at any level of multilevel inheritance. See the example below to understand the concept − Live Demo class Animal { public void move() { System.out.println("Animals can move"); } } class Dog extends Animal { public void move() { System.out.println("Dogs can walk and run"); } } class Puppy extends Dog { public void move() { System.out.println("Puppy can move."); } } public class Tester { public static void main(String args[]) { Animal a = new Animal(); // Animal reference and object Animal b = new Puppy(); // Animal reference but Puppy object a.move(); // runs the method in Animal class b.move(); // runs the method in Puppy class } } Animals can move Puppy can move.
[ { "code": null, "e": 1409, "s": 1062, "text": "Method overriding is an example of runtime polymorphism. In method overriding, a subclass overrides a method with the same signature as that of in its superclass. During compile time, the check is made on the reference type. However, in the runtime, JVM figures out the object type and would run the method that belongs to that particular object." }, { "code": null, "e": 1524, "s": 1409, "text": "We can override a method at any level of multilevel inheritance. See the example below to understand the concept −" }, { "code": null, "e": 1535, "s": 1524, "text": " Live Demo" }, { "code": null, "e": 2141, "s": 1535, "text": "class Animal {\n public void move() {\n System.out.println(\"Animals can move\");\n }\n}\nclass Dog extends Animal {\n public void move() {\n System.out.println(\"Dogs can walk and run\");\n }\n}\nclass Puppy extends Dog {\n public void move() {\n System.out.println(\"Puppy can move.\");\n }\n}\npublic class Tester {\n public static void main(String args[]) {\n Animal a = new Animal(); // Animal reference and object\n Animal b = new Puppy(); // Animal reference but Puppy object\n a.move(); // runs the method in Animal class\n b.move(); // runs the method in Puppy class\n }\n}" }, { "code": null, "e": 2174, "s": 2141, "text": "Animals can move\nPuppy can move." } ]
Hardware Synchronization
In Synchronization hardware, we explore several more solutions to the critical-section problem using techniques ranging from hardware to software based APIs available to application programmers. These solutions are based on the premise of locking; however, the design of such locks can be quite sophisticated. These Hardware features can make any programming task easier and improve system efficiency. Here, we present some simple hardware instructions that are available on many systems and show how they can be used effectively in solving the critical-section problem. If we could prevent interrupts from occurring while a shared variable was being modified. The critical-section problem could be solved simply in a uniprocessor environment. In this manner, we would be assuring that the current sequence of instructions would be allowed to execute in order without preemption. No other instructions would be run, so no unexpected modifications could be made to the shared variable. This is the approach taken by non-preemptive kernels. But unfortunately, this solution is not as feasible in a multiprocessor environment. Since the message is passed to all the processors, disabling interrupts on a multiprocessor can be time consuming. System efficiency decreases when this massage passing delays entry into each critical section. Also the effect on a system’s clock is considered if the clock is kept updated by interrupts. So many modern computer systems therefore provide special hardware instructions that allow us that we can test and modify the content of a word or to swap the contents of two words atomically—that is, as one uninterruptible unit. We may use these special instructions to solve the critical-section problem in a relatively simple manner. Now we abstract the main concepts behind these types of instructions. The TestAndSet() instruction can be defined as shown in below code. boolean test and set(boolean *target){ boolean rv = *target; *target = true; return rv; } Definition of the test and set() instruction. The essential characteristic is that this instruction is executed atomically. So, if two TestAndSet C) instructions are executed simultaneously (each on a different CPU), they will be executed sequentially in some arbitrary order. we can implement mutual exclusion by declaring a Boolean variable lock, initialized to false, if the machine supports the TestAndSet () instruction. The structure of process P, is shown in below. do { while (test and set(&lock)) ; /* do nothing */ /* critical section */ lock = false; /* remainder section */ } while (true); Mutual-exclusion implementation with test and set(). The SwapO instruction, in contrast to the TestAndSet0 instruction, operates on the contents of two words; it is executed atomically. mutual exclusion can be provided as follows if the machine supports the SwapO instruction. Here, a global Boolean variable lock is declared and is initialized to false. Additionally, each process has a local Boolean variable key. The structure of process P, is shown in figure below. int compare_and_swap(int *val, int expected, int new val){ int temp = *val; if (*val == expected) *val = new val; return temp; } Definition of the compare and swap() instruction. do{ while (compare_and_swap(&lock, 0, 1) != 0) ; /* do nothing */ /* critical section */ lock = 0; /* remainder section */ } while (true); Mutual-exclusion implementation with the compare and swap() instruction. Since these algorithms satisfy the mutual-exclusion requirement, they do not satisfy the bounded-waiting requirement. In below code, we present another algorithm using the TestAndSet() instruction that satisfies all the critical-section requirements. do{ waiting[i] = true; key = true; while (waiting[i] && key) key = test and set(&lock); waiting[i] = false; /* critical section */ j = (i + 1) % n; while ((j != i) && !waiting[j]) j = (j + 1) % n; if (j == i) lock = false; else waiting[j] = false; /* remainder section */ } while (true); Bounded-waiting mutual exclusion with test and set(). The same data structures are boolean waiting[n]; boolean lock; These data structures are initialized to false. To prove the point that the mutual exclusion requirement is met, we note that process P; can enter its critical section only if either waiting[i] == false or key -- false. The value of key can become false only if the TestAndSet() is executed. The first process to execute the TestAndSet() will find key == false; all others must wait. The variable waiting[i] may become false only if another process leaves its critical section; only one waiting [i] is set to false, maintaining the mutual-exclusion requirement. To prove the point that the progress requirement is met, we note that the arguments presented for mutual exclusion also apply here, since a process exiting the critical section either set lock to false or sets waiting[j] to false. Both of them allow a process that is waiting to enter its critical section to proceed. To prove the point that the bounded-waiting requirement is met, we note that, when a process leaves its critical section, it scans the array waiting in the cyclic ordering (z' + 1, i + 2,..., n — 1, 0, ..., i — 1). It designates the first process in this ordering that is in the entry section (waiting [j] =- true) as the next one to enter the critical section. Any process that waiting to enter its critical section will thus do so within n — 1 turns. Unfortunately for hardware designers, implementing atomic TestAndSet() instructions on multiprocessors is not a trivial task.
[ { "code": null, "e": 1372, "s": 1062, "text": "In Synchronization hardware, we explore several more solutions to the critical-section problem using techniques ranging from hardware to software based APIs available to application programmers. These solutions are based on the premise of locking; however, the design of such locks can be quite sophisticated." }, { "code": null, "e": 2301, "s": 1372, "text": "These Hardware features can make any programming task easier and improve system efficiency. Here, we present some simple hardware instructions that are available on many systems and show how they can be used effectively in solving the critical-section problem. If we could prevent interrupts from occurring while a shared variable was being modified. The critical-section problem could be solved simply in a uniprocessor environment. In this manner, we would be assuring that the current sequence of instructions would be allowed to execute in order without preemption. No other instructions would be run, so no unexpected modifications could be made to the shared variable. This is the approach taken by non-preemptive kernels. But unfortunately, this solution is not as feasible in a multiprocessor environment. Since the message is passed to all the processors, disabling interrupts on a multiprocessor can be time consuming." }, { "code": null, "e": 2965, "s": 2301, "text": "System efficiency decreases when this massage passing delays entry into each critical section. Also the effect on a system’s clock is considered if the clock is kept updated by interrupts. So many modern computer systems therefore provide special hardware instructions that allow us that we can test and modify the content of a word or to swap the contents of two words atomically—that is, as one uninterruptible unit. We may use these special instructions to solve the critical-section problem in a relatively simple manner. Now we abstract the main concepts behind these types of instructions. The TestAndSet() instruction can be defined as shown in below code." }, { "code": null, "e": 3064, "s": 2965, "text": "boolean test and set(boolean *target){\n boolean rv = *target;\n *target = true;\n return rv;\n}" }, { "code": null, "e": 3110, "s": 3064, "text": "Definition of the test and set() instruction." }, { "code": null, "e": 3537, "s": 3110, "text": "The essential characteristic is that this instruction is executed atomically. So, if two TestAndSet C) instructions are executed simultaneously (each on a different CPU), they will be executed sequentially in some arbitrary order. we can implement mutual exclusion by declaring a Boolean variable lock, initialized to false, if the machine supports the TestAndSet () instruction. The structure of process P, is shown in below." }, { "code": null, "e": 3681, "s": 3537, "text": "do {\n while (test and set(&lock)) ;\n /* do nothing */\n /* critical section */\n lock = false;\n /* remainder section */\n}\nwhile (true);" }, { "code": null, "e": 3734, "s": 3681, "text": "Mutual-exclusion implementation with test and set()." }, { "code": null, "e": 4151, "s": 3734, "text": "The SwapO instruction, in contrast to the TestAndSet0 instruction, operates on the contents of two words; it is executed atomically. mutual exclusion can be provided as follows if the machine supports the SwapO instruction. Here, a global Boolean variable lock is declared and is initialized to false. Additionally, each process has a local Boolean variable key. The structure of process P, is shown in figure below." }, { "code": null, "e": 4292, "s": 4151, "text": "int compare_and_swap(int *val, int expected, int new val){\n int temp = *val;\n if (*val == expected)\n *val = new val;\n return temp;\n}" }, { "code": null, "e": 4342, "s": 4292, "text": "Definition of the compare and swap() instruction." }, { "code": null, "e": 4496, "s": 4342, "text": "do{\n while (compare_and_swap(&lock, 0, 1) != 0) ;\n /* do nothing */\n /* critical section */\n lock = 0;\n /* remainder section */\n}\nwhile (true);" }, { "code": null, "e": 4569, "s": 4496, "text": "Mutual-exclusion implementation with the compare and swap() instruction." }, { "code": null, "e": 4820, "s": 4569, "text": "Since these algorithms satisfy the mutual-exclusion requirement, they do not satisfy the bounded-waiting requirement. In below code, we present another algorithm using the TestAndSet() instruction that satisfies all the critical-section requirements." }, { "code": null, "e": 5162, "s": 4820, "text": "do{\n waiting[i] = true;\n key = true;\n while (waiting[i] && key)\n key = test and set(&lock);\n waiting[i] = false;\n /* critical section */\n j = (i + 1) % n;\n while ((j != i) && !waiting[j])\n j = (j + 1) % n;\n if (j == i)\n lock = false;\n else\n waiting[j] = false;\n /* remainder section */\n}\nwhile (true);" }, { "code": null, "e": 5216, "s": 5162, "text": "Bounded-waiting mutual exclusion with test and set()." }, { "code": null, "e": 5841, "s": 5216, "text": "The same data structures are boolean waiting[n]; boolean lock; These data structures are initialized to false. To prove the point that the mutual exclusion requirement is met, we note that process P; can enter its critical section only if either waiting[i] == false or key -- false. The value of key can become false only if the TestAndSet() is executed. The first process to execute the TestAndSet() will find key == false; all others must wait. The variable waiting[i] may become false only if another process leaves its critical section; only one waiting [i] is set to false, maintaining the mutual-exclusion requirement." }, { "code": null, "e": 6521, "s": 5841, "text": "To prove the point that the progress requirement is met, we note that the arguments presented for mutual exclusion also apply here, since a process exiting the critical section either set lock to false or sets waiting[j] to false. Both of them allow a process that is waiting to enter its critical section to proceed. To prove the point that the bounded-waiting requirement is met, we note that, when a process leaves its critical section, it scans the array waiting in the cyclic ordering (z' + 1, i + 2,..., n — 1, 0, ..., i — 1). It designates the first process in this ordering that is in the entry section (waiting [j] =- true) as the next one to enter the critical section." }, { "code": null, "e": 6738, "s": 6521, "text": "Any process that waiting to enter its critical section will thus do so within n — 1 turns. Unfortunately for hardware designers, implementing atomic TestAndSet() instructions on multiprocessors is not a trivial task." } ]
Python Program to Select the nth Smallest Element from a List in Expected Linear Time
When it is required to select the nth smallest element from a list in linear time complexity, two methods are required. One method to find the smallest element, and another method that divides the list into two parts. This division depends on the ‘i’ value that is given by user. Based on this value, the list is split, and the smallest element is determined. Below is a demonstration of the same − Live Demo def select_smallest(my_list, beg, end, i): if end - beg <= 1: return my_list[beg] pivot_val = start_partition(my_list, beg, end) k = pivot_val - beg + 1 if i < k: return select_smallest(my_list, beg, pivot_val, i) elif i > k: return select_smallest(my_list, pivot_val + 1, end, i - k) return my_list[pivot_val] def start_partition(my_list, beg, end): pivot_val = my_list[beg] i = beg + 1 j = end - 1 while True: while (i <= j and my_list[i] <= pivot_val): i = i + 1 while (i <= j and my_list[j] >= pivot_val): j = j - 1 if i <= j: my_list[i], my_list[j] = my_list[j], my_list[i] else: my_list[beg], my_list[j] = my_list[j], my_list[beg] return j my_list = input('Enter the list of numbers.. ') my_list = my_list.split() my_list = [int(x) for x in my_list] i = int(input('Enter the value for i.. ')) ith_smallest = select_smallest(my_list, 0, len(my_list), i) print('The result is {}.'.format(ith_smallest)) Enter the list of numbers.. 43 12 67 89 99 0 Enter the value for i.. 3 The result is 43. A method named ‘select_smallest’ is defined, that takes the list, the beginning, end and an ‘i’ value is taken as parameter. A method named ‘select_smallest’ is defined, that takes the list, the beginning, end and an ‘i’ value is taken as parameter. Another method named ‘start_partition’ is defined that divides the list into two parts depending on the value of ‘i’. Another method named ‘start_partition’ is defined that divides the list into two parts depending on the value of ‘i’. This method is called in the ‘select_smallest’ method. This method is called in the ‘select_smallest’ method. The ‘select_smallest’ is also called again inside the same function- this is how recursion works. The ‘select_smallest’ is also called again inside the same function- this is how recursion works. The numbers are taken as input from the user. The numbers are taken as input from the user. It is split based on default value. It is split based on default value. It is iterated over. It is iterated over. A value for ‘i’ is taken from the user. A value for ‘i’ is taken from the user. Based on this ‘i’ value, the list is divided into two parts. Based on this ‘i’ value, the list is divided into two parts. The ‘select_smallest’ method is called on one of the lists. The ‘select_smallest’ method is called on one of the lists. The output is displayed on the console. The output is displayed on the console.
[ { "code": null, "e": 1422, "s": 1062, "text": "When it is required to select the nth smallest element from a list in linear time complexity, two methods are required. One method to find the smallest element, and another method that divides the list into two parts. This division depends on the ‘i’ value that is given by user. Based on this value, the list is split, and the smallest element is determined." }, { "code": null, "e": 1461, "s": 1422, "text": "Below is a demonstration of the same −" }, { "code": null, "e": 1472, "s": 1461, "text": " Live Demo" }, { "code": null, "e": 2489, "s": 1472, "text": "def select_smallest(my_list, beg, end, i):\n if end - beg <= 1:\n return my_list[beg]\n pivot_val = start_partition(my_list, beg, end)\n\n k = pivot_val - beg + 1\n\n if i < k:\n return select_smallest(my_list, beg, pivot_val, i)\n elif i > k:\n return select_smallest(my_list, pivot_val + 1, end, i - k)\n\n return my_list[pivot_val]\n\ndef start_partition(my_list, beg, end):\n pivot_val = my_list[beg]\n i = beg + 1\n j = end - 1\n\n while True:\n while (i <= j and my_list[i] <= pivot_val):\n i = i + 1\n while (i <= j and my_list[j] >= pivot_val):\n j = j - 1\n\n if i <= j:\n my_list[i], my_list[j] = my_list[j], my_list[i]\n else:\n my_list[beg], my_list[j] = my_list[j], my_list[beg]\n return j\n\nmy_list = input('Enter the list of numbers.. ')\nmy_list = my_list.split()\nmy_list = [int(x) for x in my_list]\ni = int(input('Enter the value for i.. '))\n\nith_smallest = select_smallest(my_list, 0, len(my_list), i)\nprint('The result is {}.'.format(ith_smallest))" }, { "code": null, "e": 2578, "s": 2489, "text": "Enter the list of numbers.. 43 12 67 89 99 0\nEnter the value for i.. 3\nThe result is 43." }, { "code": null, "e": 2703, "s": 2578, "text": "A method named ‘select_smallest’ is defined, that takes the list, the beginning, end and an ‘i’ value is taken as parameter." }, { "code": null, "e": 2828, "s": 2703, "text": "A method named ‘select_smallest’ is defined, that takes the list, the beginning, end and an ‘i’ value is taken as parameter." }, { "code": null, "e": 2946, "s": 2828, "text": "Another method named ‘start_partition’ is defined that divides the list into two parts depending on the value of ‘i’." }, { "code": null, "e": 3064, "s": 2946, "text": "Another method named ‘start_partition’ is defined that divides the list into two parts depending on the value of ‘i’." }, { "code": null, "e": 3119, "s": 3064, "text": "This method is called in the ‘select_smallest’ method." }, { "code": null, "e": 3174, "s": 3119, "text": "This method is called in the ‘select_smallest’ method." }, { "code": null, "e": 3272, "s": 3174, "text": "The ‘select_smallest’ is also called again inside the same function- this is how recursion works." }, { "code": null, "e": 3370, "s": 3272, "text": "The ‘select_smallest’ is also called again inside the same function- this is how recursion works." }, { "code": null, "e": 3416, "s": 3370, "text": "The numbers are taken as input from the user." }, { "code": null, "e": 3462, "s": 3416, "text": "The numbers are taken as input from the user." }, { "code": null, "e": 3498, "s": 3462, "text": "It is split based on default value." }, { "code": null, "e": 3534, "s": 3498, "text": "It is split based on default value." }, { "code": null, "e": 3555, "s": 3534, "text": "It is iterated over." }, { "code": null, "e": 3576, "s": 3555, "text": "It is iterated over." }, { "code": null, "e": 3616, "s": 3576, "text": "A value for ‘i’ is taken from the user." }, { "code": null, "e": 3656, "s": 3616, "text": "A value for ‘i’ is taken from the user." }, { "code": null, "e": 3717, "s": 3656, "text": "Based on this ‘i’ value, the list is divided into two parts." }, { "code": null, "e": 3778, "s": 3717, "text": "Based on this ‘i’ value, the list is divided into two parts." }, { "code": null, "e": 3838, "s": 3778, "text": "The ‘select_smallest’ method is called on one of the lists." }, { "code": null, "e": 3898, "s": 3838, "text": "The ‘select_smallest’ method is called on one of the lists." }, { "code": null, "e": 3938, "s": 3898, "text": "The output is displayed on the console." }, { "code": null, "e": 3978, "s": 3938, "text": "The output is displayed on the console." } ]
Convert Json String to Java Object Using GSON - GeeksforGeeks
24 Jan, 2022 Pre-requisite: Convert Java Object to Json String Using GSONJSON Stand for JavaScript Object Notation. It’s a standard text-based format which shows structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications. JSON is highly recommended to transmit data between a server and web application. To convert a Java object into JSON, the following methods can be used: GSON: It is an open-source Java library which is used to serialize and deserialize Java objects to JSON. Jackson API In this article, a predefined JSON String is converted into Java Object using GSON.Examples: Input: { “organisation_name” : “GeeksforGeeks”, “description” : “A computer Science portal for Geeks”, “Employee” : “2000” } Output: Organisation [organisation_name=GeeksforGeeks, description=A computer Science portal for Geeks, Employees=0]Input: { “Student_name” : “XYZ”, “Organisation_name” : “GeeksForGeeks” “Roll_No” : “1” } Output: Student [Student_name=XYZ, Organisation_name=GeeksForGeeks, Roll_no=1] The steps to do this are as follows: Add jar files of Jackson (in case of Maven project add Gson dependencies in the pom.xml file) html <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.6.2</version> </dependency> Below is the screenshot showing this step:- Create a POJO (Plain Old Java Object) to be converted into JSON Java package GeeksforGeeks.Geeks;public class Organisation { private String organisation_name; private String description; private int Employees; // Calling getters and setters public String getOrganisation_name() { return organisation_name; } public void setOrganisation_name(String organisation_name) { this.organisation_name = organisation_name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getEmployees() { return Employees; } public void setEmployees(int employees) { Employees = employees; } // Creating toString @Override public String toString() { return "Organisation [organisation_name=" + organisation_name + ", description=" + description + ", Employees=" + Employees + "]"; }} Below is the screenshot showing this step:- Create a String Variable for Storing Json String: Note: This Json string should not be a simple Json String. Preprocess the JSON String and add slashes before passing it into GSON object.Example of Preprocessing: Initial JSON String: {“organisation_name” : “GeeksforGeeks”, “description” : “A computer Science portal for Geeks”, “Employee” : “2000”}Preprocessed JSON String: { \”organisation_name\” : \”GeeksforGeeks\”, \”description\” : \”A computer Science portal for Geeks\”, \”Employee\” : \”2000\” } Create a Java class for converting the Json into Organisation object: Java package GeeksforGeeks.Geeks; import com.google.gson.Gson; public class JsonToObject { public static void main(String[] args) { // Creating object of Organisation Organisation org = new Organisation(); // Converting json to object org = getOrganisationObject(); // Displaying object System.out.println(org); } private static Organisation getOrganisationObject() { // Storing preprocessed json(Added slashes) String OrganisationJson = "{\"organisation_name\" : \"GeeksforGeeks\", \"description\" : \"A computer Science portal for Geeks\", \"Employee\" : \"2000\"}"; // Creating a Gson Object Gson gson = new Gson(); // Converting json to object // first parameter should be preprocessed json // and second should be mapping class Organisation organisation = gson.fromJson(OrganisationJson, Organisation.class); // return object return organisation; }} Below is the screenshot showing this step:- Execute the process Output: Organisation [organisation_name=GeeksforGeeks, description=A computer Science portal for Geeks, Employees=0] sagartomar9927 ayushpandey3july sweetyty Java-Object Oriented JSON Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Initialize an ArrayList in Java Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java How to iterate any Map in Java ArrayList in Java Multidimensional Arrays in Java Stream In Java Stack Class in Java Singleton Class in Java
[ { "code": null, "e": 24922, "s": 24894, "text": "\n24 Jan, 2022" }, { "code": null, "e": 25340, "s": 24922, "text": "Pre-requisite: Convert Java Object to Json String Using GSONJSON Stand for JavaScript Object Notation. It’s a standard text-based format which shows structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications. JSON is highly recommended to transmit data between a server and web application. To convert a Java object into JSON, the following methods can be used: " }, { "code": null, "e": 25445, "s": 25340, "text": "GSON: It is an open-source Java library which is used to serialize and deserialize Java objects to JSON." }, { "code": null, "e": 25457, "s": 25445, "text": "Jackson API" }, { "code": null, "e": 25552, "s": 25457, "text": "In this article, a predefined JSON String is converted into Java Object using GSON.Examples: " }, { "code": null, "e": 25963, "s": 25552, "text": "Input: { “organisation_name” : “GeeksforGeeks”, “description” : “A computer Science portal for Geeks”, “Employee” : “2000” } Output: Organisation [organisation_name=GeeksforGeeks, description=A computer Science portal for Geeks, Employees=0]Input: { “Student_name” : “XYZ”, “Organisation_name” : “GeeksForGeeks” “Roll_No” : “1” } Output: Student [Student_name=XYZ, Organisation_name=GeeksForGeeks, Roll_no=1] " }, { "code": null, "e": 26001, "s": 25963, "text": "The steps to do this are as follows: " }, { "code": null, "e": 26097, "s": 26001, "text": "Add jar files of Jackson (in case of Maven project add Gson dependencies in the pom.xml file) " }, { "code": null, "e": 26102, "s": 26097, "text": "html" }, { "code": "<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.6.2</version> </dependency>", "e": 26244, "s": 26102, "text": null }, { "code": null, "e": 26290, "s": 26244, "text": "Below is the screenshot showing this step:- " }, { "code": null, "e": 26356, "s": 26290, "text": "Create a POJO (Plain Old Java Object) to be converted into JSON " }, { "code": null, "e": 26361, "s": 26356, "text": "Java" }, { "code": "package GeeksforGeeks.Geeks;public class Organisation { private String organisation_name; private String description; private int Employees; // Calling getters and setters public String getOrganisation_name() { return organisation_name; } public void setOrganisation_name(String organisation_name) { this.organisation_name = organisation_name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getEmployees() { return Employees; } public void setEmployees(int employees) { Employees = employees; } // Creating toString @Override public String toString() { return \"Organisation [organisation_name=\" + organisation_name + \", description=\" + description + \", Employees=\" + Employees + \"]\"; }}", "e": 27339, "s": 26361, "text": null }, { "code": null, "e": 27385, "s": 27339, "text": "Below is the screenshot showing this step:- " }, { "code": null, "e": 27600, "s": 27385, "text": "Create a String Variable for Storing Json String: Note: This Json string should not be a simple Json String. Preprocess the JSON String and add slashes before passing it into GSON object.Example of Preprocessing: " }, { "code": null, "e": 27894, "s": 27600, "text": "Initial JSON String: {“organisation_name” : “GeeksforGeeks”, “description” : “A computer Science portal for Geeks”, “Employee” : “2000”}Preprocessed JSON String: { \\”organisation_name\\” : \\”GeeksforGeeks\\”, \\”description\\” : \\”A computer Science portal for Geeks\\”, \\”Employee\\” : \\”2000\\” } " }, { "code": null, "e": 27964, "s": 27894, "text": "Create a Java class for converting the Json into Organisation object:" }, { "code": null, "e": 27969, "s": 27964, "text": "Java" }, { "code": "package GeeksforGeeks.Geeks; import com.google.gson.Gson; public class JsonToObject { public static void main(String[] args) { // Creating object of Organisation Organisation org = new Organisation(); // Converting json to object org = getOrganisationObject(); // Displaying object System.out.println(org); } private static Organisation getOrganisationObject() { // Storing preprocessed json(Added slashes) String OrganisationJson = \"{\\\"organisation_name\\\" : \\\"GeeksforGeeks\\\", \\\"description\\\" : \\\"A computer Science portal for Geeks\\\", \\\"Employee\\\" : \\\"2000\\\"}\"; // Creating a Gson Object Gson gson = new Gson(); // Converting json to object // first parameter should be preprocessed json // and second should be mapping class Organisation organisation = gson.fromJson(OrganisationJson, Organisation.class); // return object return organisation; }}", "e": 29060, "s": 27969, "text": null }, { "code": null, "e": 29106, "s": 29060, "text": "Below is the screenshot showing this step:- " }, { "code": null, "e": 29128, "s": 29106, "text": "Execute the process " }, { "code": null, "e": 29138, "s": 29128, "text": "Output: " }, { "code": null, "e": 29247, "s": 29138, "text": "Organisation [organisation_name=GeeksforGeeks, description=A computer Science portal for Geeks, Employees=0]" }, { "code": null, "e": 29262, "s": 29247, "text": "sagartomar9927" }, { "code": null, "e": 29279, "s": 29262, "text": "ayushpandey3july" }, { "code": null, "e": 29288, "s": 29279, "text": "sweetyty" }, { "code": null, "e": 29309, "s": 29288, "text": "Java-Object Oriented" }, { "code": null, "e": 29314, "s": 29309, "text": "JSON" }, { "code": null, "e": 29319, "s": 29314, "text": "Java" }, { "code": null, "e": 29324, "s": 29319, "text": "Java" }, { "code": null, "e": 29422, "s": 29324, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29454, "s": 29422, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 29505, "s": 29454, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 29535, "s": 29505, "text": "HashMap in Java with Examples" }, { "code": null, "e": 29554, "s": 29535, "text": "Interfaces in Java" }, { "code": null, "e": 29585, "s": 29554, "text": "How to iterate any Map in Java" }, { "code": null, "e": 29603, "s": 29585, "text": "ArrayList in Java" }, { "code": null, "e": 29635, "s": 29603, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 29650, "s": 29635, "text": "Stream In Java" }, { "code": null, "e": 29670, "s": 29650, "text": "Stack Class in Java" } ]
Python os.pipe() Method
Python method pipe() creates a pipe and returns a pair of file descriptors (r, w) usable for reading and writing, respectively Following is the syntax for pipe() method − os.pipe() NA NA This method returns a pair of file descriptors. The following example shows the usage of pipe() method. #!/usr/bin/python import os, sys print "The child will write text to a pipe and " print "the parent will read the text written by child..." # file descriptors r, w for reading and writing r, w = os.pipe() processid = os.fork() if processid: # This is the parent process # Closes file descriptor w os.close(w) r = os.fdopen(r) print "Parent reading" str = r.read() print "text =", str sys.exit(0) else: # This is the child process os.close(r) w = os.fdopen(w, 'w') print "Child writing" w.write("Text written by child...") w.close() print "Child closing" sys.exit(0) When we run above program, it produces following result − The child will write text to a pipe and the parent will read the text written by child... Parent reading Child writing Child closing text = Text written by child... 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2371, "s": 2244, "text": "Python method pipe() creates a pipe and returns a pair of file descriptors (r, w) usable for reading and writing, respectively" }, { "code": null, "e": 2415, "s": 2371, "text": "Following is the syntax for pipe() method −" }, { "code": null, "e": 2426, "s": 2415, "text": "os.pipe()\n" }, { "code": null, "e": 2429, "s": 2426, "text": "NA" }, { "code": null, "e": 2432, "s": 2429, "text": "NA" }, { "code": null, "e": 2480, "s": 2432, "text": "This method returns a pair of file descriptors." }, { "code": null, "e": 2536, "s": 2480, "text": "The following example shows the usage of pipe() method." }, { "code": null, "e": 3159, "s": 2536, "text": "#!/usr/bin/python\n\nimport os, sys\n\nprint \"The child will write text to a pipe and \"\nprint \"the parent will read the text written by child...\"\n\n# file descriptors r, w for reading and writing\nr, w = os.pipe() \n\nprocessid = os.fork()\nif processid:\n # This is the parent process \n # Closes file descriptor w\n os.close(w)\n r = os.fdopen(r)\n print \"Parent reading\"\n str = r.read()\n print \"text =\", str \n sys.exit(0)\nelse:\n # This is the child process\n os.close(r)\n w = os.fdopen(w, 'w')\n print \"Child writing\"\n w.write(\"Text written by child...\")\n w.close()\n print \"Child closing\"\n sys.exit(0)" }, { "code": null, "e": 3217, "s": 3159, "text": "When we run above program, it produces following result −" }, { "code": null, "e": 3383, "s": 3217, "text": "The child will write text to a pipe and\nthe parent will read the text written by child...\nParent reading\nChild writing\nChild closing\ntext = Text written by child...\n" }, { "code": null, "e": 3420, "s": 3383, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3436, "s": 3420, "text": " Malhar Lathkar" }, { "code": null, "e": 3469, "s": 3436, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3488, "s": 3469, "text": " Arnab Chakraborty" }, { "code": null, "e": 3523, "s": 3488, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3545, "s": 3523, "text": " In28Minutes Official" }, { "code": null, "e": 3579, "s": 3545, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3607, "s": 3579, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3642, "s": 3607, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3656, "s": 3642, "text": " Lets Kode It" }, { "code": null, "e": 3689, "s": 3656, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3706, "s": 3689, "text": " Abhilash Nelson" }, { "code": null, "e": 3713, "s": 3706, "text": " Print" }, { "code": null, "e": 3724, "s": 3713, "text": " Add Notes" } ]
Maximum Subarray Sum in a given Range in C++
We are given with an array of integer elements of any given size. The task is to find the maximum sum which will be calculated by forming the subarrays from the given array within the given range which can be started from any possible index value in an array. Let us see various input output scenarios for this - In − int arr[] = { 3, 2, -1, 6, 7, 2 }, int first = 0, int last = 5 Out − Maximum Subarray Sum in a given Range is: 19 Explanation − we are given with an array containing both positive and negative values and a range starting from 0 till 5 i.e. covering all the indexes of an array. So the subarray with maximum sum can be 3 + 6 + 7 + 2 + 2 - 1 i.e. 19. In − int arr[] = {-2, 1, 3, 4, 8, 9, 23}, int first = 0, int last = 3 Out − Maximum Subarray Sum in a given Range is: 8 Explanation − we are given with an array containing both positive and negative values and a range starting from 0 till 3 i.e. covering 0 till 3 indexes of an array. So the subarray with maximum sum can be 1 + 3 + 4 i.e. 8. Construct a structure for a tree that will store max_val, max_temp, total, sub_sum as a member variables and set max_val, max_temp, sum_sum and total as maximum values using default constructor. Construct a structure for a tree that will store max_val, max_temp, total, sub_sum as a member variables and set max_val, max_temp, sum_sum and total as maximum values using default constructor. Create a method of structure as set_node that will form the tree by setting max_val as max(left.max_val, left.total + right.max_val), max_temp as max(right.max_temp, right.total + left.max_temp), total as left.total + right.total and sub_sum as max({left.sub_sum, right.sub_sum, left.max_temp + right.max_val}) then return node. Create a method of structure as set_node that will form the tree by setting max_val as max(left.max_val, left.total + right.max_val), max_temp as max(right.max_temp, right.total + left.max_temp), total as left.total + right.total and sub_sum as max({left.sub_sum, right.sub_sum, left.max_temp + right.max_val}) then return node. Create a method as build_tree that will be used to construct a tree.Check IF first = last then set total, max_temp, max_val and sub_sum as arr[first] and return.Make a call to the build_tree method as build_tree(node, arr, first, temp, 2 * inx) and build_tree(node, arr, temp + 1, last, 2 * inx + 1) then set node[inx] to set_nodes(node[2 * inx], node[2 * inx + 1]) Create a method as build_tree that will be used to construct a tree. Check IF first = last then set total, max_temp, max_val and sub_sum as arr[first] and return. Check IF first = last then set total, max_temp, max_val and sub_sum as arr[first] and return. Make a call to the build_tree method as build_tree(node, arr, first, temp, 2 * inx) and build_tree(node, arr, temp + 1, last, 2 * inx + 1) then set node[inx] to set_nodes(node[2 * inx], node[2 * inx + 1]) Make a call to the build_tree method as build_tree(node, arr, first, temp, 2 * inx) and build_tree(node, arr, temp + 1, last, 2 * inx + 1) then set node[inx] to set_nodes(node[2 * inx], node[2 * inx + 1]) Create a method as create_tree and set temp as (int)(ceil(log2(size))) then make a call to the build_tree() method by passing node object of tree, arr, value 0, size of an array -1 , value 1 as an argument. Create a method as create_tree and set temp as (int)(ceil(log2(size))) then make a call to the build_tree() method by passing node object of tree, arr, value 0, size of an array -1 , value 1 as an argument. Create a method to find the maximum subarray sum as maximum_sub(Tree* node, int temp, int temp_2, int temp_3, int temp_4, int inx)Check IF temp greater than temp_4 OR temp_2 less than temp_3then return NULLCheck IF temp greater than temp_3 AND temp_2 less than temp_4 then return node[inx]Make a call to the method as left to call the function maximum_sub(node, temp, mid, temp_3, temp_4, 2 * inx) and right to maximum_sub(node, mid + 1, temp_2, temp_3, temp_4, 2 * inx + 1)Set result as set_nodes(left, right)Return result. Create a method to find the maximum subarray sum as maximum_sub(Tree* node, int temp, int temp_2, int temp_3, int temp_4, int inx) Check IF temp greater than temp_4 OR temp_2 less than temp_3then return NULL Check IF temp greater than temp_4 OR temp_2 less than temp_3then return NULL Check IF temp greater than temp_3 AND temp_2 less than temp_4 then return node[inx] Check IF temp greater than temp_3 AND temp_2 less than temp_4 then return node[inx] Make a call to the method as left to call the function maximum_sub(node, temp, mid, temp_3, temp_4, 2 * inx) and right to maximum_sub(node, mid + 1, temp_2, temp_3, temp_4, 2 * inx + 1) Make a call to the method as left to call the function maximum_sub(node, temp, mid, temp_3, temp_4, 2 * inx) and right to maximum_sub(node, mid + 1, temp_2, temp_3, temp_4, 2 * inx + 1) Set result as set_nodes(left, right) Set result as set_nodes(left, right) Return result. Return result. Create a method as maximum_subarray(Tree* node, int first, int last, int size)Create a call to the method as maximum_sub(node, 0, size - 1, first, last, 1)Return temp.sub_sum Create a method as maximum_subarray(Tree* node, int first, int last, int size) Create a call to the method as maximum_sub(node, 0, size - 1, first, last, 1) Create a call to the method as maximum_sub(node, 0, size - 1, first, last, 1) Return temp.sub_sum Return temp.sub_sum In the main() functionDeclare an array of integer types with positive and negative values and calculate the size of an array.Define the range from first index to last index.Call the function maximum_subarray(node, first, last, size) to calculate the maximum subarray sum in the given range In the main() function Declare an array of integer types with positive and negative values and calculate the size of an array. Declare an array of integer types with positive and negative values and calculate the size of an array. Define the range from first index to last index. Define the range from first index to last index. Call the function maximum_subarray(node, first, last, size) to calculate the maximum subarray sum in the given range Call the function maximum_subarray(node, first, last, size) to calculate the maximum subarray sum in the given range #include <bits/stdc++.h> using namespace std; #define MAX 0x3f3f struct Tree{ int max_val; int max_temp; int total; int sub_sum; Tree(){ max_val = max_temp = sub_sum = -MAX; total = -MAX; } }; Tree set_nodes(Tree left, Tree right){ Tree node; node.max_val = max(left.max_val, left.total + right.max_val); node.max_temp = max(right.max_temp, right.total + left.max_temp); node.total = left.total + right.total; node.sub_sum = max({left.sub_sum, right.sub_sum, left.max_temp + right.max_val}); return node; } void build_tree(Tree* node, int arr[], int first, int last, int inx){ if(first == last){ node[inx].total = arr[first]; node[inx].max_temp = arr[first]; node[inx].max_val = arr[first]; node[inx].sub_sum = arr[first]; return; } int temp = (first + last) / 2; build_tree(node, arr, first, temp, 2 * inx); build_tree(node, arr, temp + 1, last, 2 * inx + 1); node[inx] = set_nodes(node[2 * inx], node[2 * inx + 1]); } Tree* create_tree(int arr[], int size){ int temp = (int)(ceil(log2(size))); int n = 2 * (int)pow(2, temp) - 1; Tree* node = new Tree[n]; build_tree(node, arr, 0, size - 1, 1); return node; } Tree maximum_sub(Tree* node, int temp, int temp_2, int temp_3, int temp_4, int inx){ if(temp > temp_4 || temp_2 < temp_3){ Tree nullNode; return nullNode; } if(temp >= temp_3 && temp_2 <= temp_4){ return node[inx]; } int mid = (temp + temp_2) / 2; Tree left = maximum_sub(node, temp, mid, temp_3, temp_4, 2 * inx); Tree right = maximum_sub(node, mid + 1, temp_2, temp_3, temp_4, 2 * inx + 1); Tree result = set_nodes(left, right); return result; } int maximum_subarray(Tree* node, int first, int last, int size){ Tree temp = maximum_sub(node, 0, size - 1, first, last, 1); return temp.sub_sum; } int main(){ int arr[] = { 3, 2, -1, 6, 7, 2 }; int size = sizeof(arr) / sizeof(arr[0]); Tree* node = create_tree(arr, size); int first = 0; int last = 5; int sub_sum = maximum_subarray(node, first, last, size); cout<< "Maximum Subarray Sum in a given Range is: "<< sub_sum; return 0; } If we run the above code it will generate the following Output Maximum Subarray Sum in a given Range is: 19
[ { "code": null, "e": 1322, "s": 1062, "text": "We are given with an array of integer elements of any given size. The task is to find the maximum sum which will be calculated by forming the subarrays from the given array within the given range which can be started from any possible index value in an array." }, { "code": null, "e": 1375, "s": 1322, "text": "Let us see various input output scenarios for this -" }, { "code": null, "e": 1443, "s": 1375, "text": "In − int arr[] = { 3, 2, -1, 6, 7, 2 }, int first = 0, int last = 5" }, { "code": null, "e": 1494, "s": 1443, "text": "Out − Maximum Subarray Sum in a given Range is: 19" }, { "code": null, "e": 1729, "s": 1494, "text": "Explanation − we are given with an array containing both positive and negative values and a range starting from 0 till 5 i.e. covering all the indexes of an array. So the subarray with\nmaximum sum can be 3 + 6 + 7 + 2 + 2 - 1 i.e. 19." }, { "code": null, "e": 1799, "s": 1729, "text": "In − int arr[] = {-2, 1, 3, 4, 8, 9, 23}, int first = 0, int last = 3" }, { "code": null, "e": 1850, "s": 1799, "text": "Out − Maximum Subarray Sum in a given Range is: 8" }, { "code": null, "e": 2073, "s": 1850, "text": "Explanation − we are given with an array containing both positive and negative values and a range starting from 0 till 3 i.e. covering 0 till 3 indexes of an array. So the subarray with\nmaximum sum can be 1 + 3 + 4 i.e. 8." }, { "code": null, "e": 2268, "s": 2073, "text": "Construct a structure for a tree that will store max_val, max_temp, total, sub_sum as a member variables and set max_val, max_temp, sum_sum and total as maximum values using default constructor." }, { "code": null, "e": 2463, "s": 2268, "text": "Construct a structure for a tree that will store max_val, max_temp, total, sub_sum as a member variables and set max_val, max_temp, sum_sum and total as maximum values using default constructor." }, { "code": null, "e": 2792, "s": 2463, "text": "Create a method of structure as set_node that will form the tree by setting max_val as max(left.max_val, left.total + right.max_val), max_temp as max(right.max_temp, right.total + left.max_temp), total as left.total + right.total and sub_sum as max({left.sub_sum, right.sub_sum, left.max_temp + right.max_val}) then return node." }, { "code": null, "e": 3121, "s": 2792, "text": "Create a method of structure as set_node that will form the tree by setting max_val as max(left.max_val, left.total + right.max_val), max_temp as max(right.max_temp, right.total + left.max_temp), total as left.total + right.total and sub_sum as max({left.sub_sum, right.sub_sum, left.max_temp + right.max_val}) then return node." }, { "code": null, "e": 3487, "s": 3121, "text": "Create a method as build_tree that will be used to construct a tree.Check IF first = last then set total, max_temp, max_val and sub_sum as arr[first] and return.Make a call to the build_tree method as build_tree(node, arr, first, temp, 2 * inx) and build_tree(node, arr, temp + 1, last, 2 * inx + 1) then set node[inx] to set_nodes(node[2 * inx], node[2 * inx + 1])" }, { "code": null, "e": 3556, "s": 3487, "text": "Create a method as build_tree that will be used to construct a tree." }, { "code": null, "e": 3650, "s": 3556, "text": "Check IF first = last then set total, max_temp, max_val and sub_sum as arr[first] and return." }, { "code": null, "e": 3744, "s": 3650, "text": "Check IF first = last then set total, max_temp, max_val and sub_sum as arr[first] and return." }, { "code": null, "e": 3949, "s": 3744, "text": "Make a call to the build_tree method as build_tree(node, arr, first, temp, 2 * inx) and build_tree(node, arr, temp + 1, last, 2 * inx + 1) then set node[inx] to set_nodes(node[2 * inx], node[2 * inx + 1])" }, { "code": null, "e": 4154, "s": 3949, "text": "Make a call to the build_tree method as build_tree(node, arr, first, temp, 2 * inx) and build_tree(node, arr, temp + 1, last, 2 * inx + 1) then set node[inx] to set_nodes(node[2 * inx], node[2 * inx + 1])" }, { "code": null, "e": 4361, "s": 4154, "text": "Create a method as create_tree and set temp as (int)(ceil(log2(size))) then make a call to the build_tree() method by passing node object of tree, arr, value 0, size of an array -1\n, value 1 as an argument." }, { "code": null, "e": 4568, "s": 4361, "text": "Create a method as create_tree and set temp as (int)(ceil(log2(size))) then make a call to the build_tree() method by passing node object of tree, arr, value 0, size of an array -1\n, value 1 as an argument." }, { "code": null, "e": 5093, "s": 4568, "text": "Create a method to find the maximum subarray sum as maximum_sub(Tree* node, int temp, int temp_2, int temp_3, int temp_4, int inx)Check IF temp greater than temp_4 OR temp_2 less than temp_3then return NULLCheck IF temp greater than temp_3 AND temp_2 less than temp_4 then return node[inx]Make a call to the method as left to call the function maximum_sub(node, temp, mid, temp_3, temp_4, 2 * inx) and right to maximum_sub(node, mid + 1, temp_2, temp_3, temp_4, 2 * inx + 1)Set result as set_nodes(left, right)Return result." }, { "code": null, "e": 5224, "s": 5093, "text": "Create a method to find the maximum subarray sum as maximum_sub(Tree* node, int temp, int temp_2, int temp_3, int temp_4, int inx)" }, { "code": null, "e": 5301, "s": 5224, "text": "Check IF temp greater than temp_4 OR temp_2 less than temp_3then return NULL" }, { "code": null, "e": 5378, "s": 5301, "text": "Check IF temp greater than temp_4 OR temp_2 less than temp_3then return NULL" }, { "code": null, "e": 5462, "s": 5378, "text": "Check IF temp greater than temp_3 AND temp_2 less than temp_4 then return node[inx]" }, { "code": null, "e": 5546, "s": 5462, "text": "Check IF temp greater than temp_3 AND temp_2 less than temp_4 then return node[inx]" }, { "code": null, "e": 5732, "s": 5546, "text": "Make a call to the method as left to call the function maximum_sub(node, temp, mid, temp_3, temp_4, 2 * inx) and right to maximum_sub(node, mid + 1, temp_2, temp_3, temp_4, 2 * inx + 1)" }, { "code": null, "e": 5918, "s": 5732, "text": "Make a call to the method as left to call the function maximum_sub(node, temp, mid, temp_3, temp_4, 2 * inx) and right to maximum_sub(node, mid + 1, temp_2, temp_3, temp_4, 2 * inx + 1)" }, { "code": null, "e": 5955, "s": 5918, "text": "Set result as set_nodes(left, right)" }, { "code": null, "e": 5992, "s": 5955, "text": "Set result as set_nodes(left, right)" }, { "code": null, "e": 6007, "s": 5992, "text": "Return result." }, { "code": null, "e": 6022, "s": 6007, "text": "Return result." }, { "code": null, "e": 6197, "s": 6022, "text": "Create a method as maximum_subarray(Tree* node, int first, int last, int size)Create a call to the method as maximum_sub(node, 0, size - 1, first, last, 1)Return temp.sub_sum" }, { "code": null, "e": 6276, "s": 6197, "text": "Create a method as maximum_subarray(Tree* node, int first, int last, int size)" }, { "code": null, "e": 6354, "s": 6276, "text": "Create a call to the method as maximum_sub(node, 0, size - 1, first, last, 1)" }, { "code": null, "e": 6432, "s": 6354, "text": "Create a call to the method as maximum_sub(node, 0, size - 1, first, last, 1)" }, { "code": null, "e": 6452, "s": 6432, "text": "Return temp.sub_sum" }, { "code": null, "e": 6472, "s": 6452, "text": "Return temp.sub_sum" }, { "code": null, "e": 6762, "s": 6472, "text": "In the main() functionDeclare an array of integer types with positive and negative values and calculate the size of an array.Define the range from first index to last index.Call the function maximum_subarray(node, first, last, size) to calculate the maximum subarray sum in the given range" }, { "code": null, "e": 6785, "s": 6762, "text": "In the main() function" }, { "code": null, "e": 6889, "s": 6785, "text": "Declare an array of integer types with positive and negative values and calculate the size of an array." }, { "code": null, "e": 6993, "s": 6889, "text": "Declare an array of integer types with positive and negative values and calculate the size of an array." }, { "code": null, "e": 7042, "s": 6993, "text": "Define the range from first index to last index." }, { "code": null, "e": 7091, "s": 7042, "text": "Define the range from first index to last index." }, { "code": null, "e": 7208, "s": 7091, "text": "Call the function maximum_subarray(node, first, last, size) to calculate the maximum subarray sum in the given range" }, { "code": null, "e": 7325, "s": 7208, "text": "Call the function maximum_subarray(node, first, last, size) to calculate the maximum subarray sum in the given range" }, { "code": null, "e": 9505, "s": 7325, "text": "#include <bits/stdc++.h>\nusing namespace std;\n#define MAX 0x3f3f\nstruct Tree{\n int max_val;\n int max_temp;\n int total;\n int sub_sum;\n Tree(){\n max_val = max_temp = sub_sum = -MAX;\n total = -MAX;\n }\n};\n\nTree set_nodes(Tree left, Tree right){\n Tree node;\n node.max_val = max(left.max_val, left.total + right.max_val);\n node.max_temp = max(right.max_temp, right.total + left.max_temp);\n node.total = left.total + right.total;\n node.sub_sum = max({left.sub_sum, right.sub_sum, left.max_temp + right.max_val});\n return node;\n}\nvoid build_tree(Tree* node, int arr[], int first, int last, int inx){\n if(first == last){\n node[inx].total = arr[first];\n node[inx].max_temp = arr[first];\n node[inx].max_val = arr[first];\n node[inx].sub_sum = arr[first];\n return;\n }\n int temp = (first + last) / 2;\n build_tree(node, arr, first, temp, 2 * inx);\n build_tree(node, arr, temp + 1, last, 2 * inx + 1);\n node[inx] = set_nodes(node[2 * inx], node[2 * inx + 1]);\n}\nTree* create_tree(int arr[], int size){\n int temp = (int)(ceil(log2(size)));\n int n = 2 * (int)pow(2, temp) - 1;\n Tree* node = new Tree[n];\n build_tree(node, arr, 0, size - 1, 1);\n return node;\n}\nTree maximum_sub(Tree* node, int temp, int temp_2, int temp_3, int temp_4, int inx){\n if(temp > temp_4 || temp_2 < temp_3){\n Tree nullNode;\n return nullNode;\n }\n if(temp >= temp_3 && temp_2 <= temp_4){\n return node[inx];\n }\n int mid = (temp + temp_2) / 2;\n Tree left = maximum_sub(node, temp, mid, temp_3, temp_4, 2 * inx);\n Tree right = maximum_sub(node, mid + 1, temp_2, temp_3, temp_4, 2 * inx + 1);\n Tree result = set_nodes(left, right);\n return result;\n}\nint maximum_subarray(Tree* node, int first, int last, int size){\n Tree temp = maximum_sub(node, 0, size - 1, first, last, 1);\n return temp.sub_sum;\n}\nint main(){\n int arr[] = { 3, 2, -1, 6, 7, 2 };\n int size = sizeof(arr) / sizeof(arr[0]);\n Tree* node = create_tree(arr, size);\n int first = 0;\n int last = 5;\n int sub_sum = maximum_subarray(node, first, last, size);\n cout<< \"Maximum Subarray Sum in a given Range is: \"<< sub_sum;\n return 0;\n}" }, { "code": null, "e": 9568, "s": 9505, "text": "If we run the above code it will generate the following Output" }, { "code": null, "e": 9614, "s": 9568, "text": "Maximum Subarray Sum in a given Range is: 19\n" } ]
Difference between Traditional and Reactive Computer System - GeeksforGeeks
04 May, 2020 1. Traditional Computer System :Traditional Computer System takes the input from the user and computes the output as the function of the input. It basically computes function on the input. Output data = f(input data) Example:If x is input and f is some function, y(output) = f(x) 2. Reactive Computer System :Reactive Computer System takes the input from the user but does not produce the output as a function of input but it interacts with the environment. In this interaction, the results computed are used to perform some action on environment. Example:Real-time Systems Difference between Traditional and Reactive System : Difference Between Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Difference between Prim's and Kruskal's algorithm for MST Difference between Internal and External fragmentation Differences and Applications of List, Tuple, Set and Dictionary in Python Banker's Algorithm in Operating System Page Replacement Algorithms in Operating Systems Types of Operating Systems Program for FCFS CPU Scheduling | Set 1 Program for Round Robin scheduling | Set 1
[ { "code": null, "e": 24858, "s": 24830, "text": "\n04 May, 2020" }, { "code": null, "e": 25047, "s": 24858, "text": "1. Traditional Computer System :Traditional Computer System takes the input from the user and computes the output as the function of the input. It basically computes function on the input." }, { "code": null, "e": 25076, "s": 25047, "text": "Output data = f(input data) " }, { "code": null, "e": 25139, "s": 25076, "text": "Example:If x is input and f is some function, y(output) = f(x)" }, { "code": null, "e": 25407, "s": 25139, "text": "2. Reactive Computer System :Reactive Computer System takes the input from the user but does not produce the output as a function of input but it interacts with the environment. In this interaction, the results computed are used to perform some action on environment." }, { "code": null, "e": 25433, "s": 25407, "text": "Example:Real-time Systems" }, { "code": null, "e": 25486, "s": 25433, "text": "Difference between Traditional and Reactive System :" }, { "code": null, "e": 25505, "s": 25486, "text": "Difference Between" }, { "code": null, "e": 25523, "s": 25505, "text": "Operating Systems" }, { "code": null, "e": 25541, "s": 25523, "text": "Operating Systems" }, { "code": null, "e": 25639, "s": 25541, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25700, "s": 25639, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 25768, "s": 25700, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 25826, "s": 25768, "text": "Difference between Prim's and Kruskal's algorithm for MST" }, { "code": null, "e": 25881, "s": 25826, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 25955, "s": 25881, "text": "Differences and Applications of List, Tuple, Set and Dictionary in Python" }, { "code": null, "e": 25994, "s": 25955, "text": "Banker's Algorithm in Operating System" }, { "code": null, "e": 26043, "s": 25994, "text": "Page Replacement Algorithms in Operating Systems" }, { "code": null, "e": 26070, "s": 26043, "text": "Types of Operating Systems" }, { "code": null, "e": 26110, "s": 26070, "text": "Program for FCFS CPU Scheduling | Set 1" } ]
Google Guice - Scopes
Guice returns a new instance every time when it supplies a value as its default behaviour. It is configurable via scopes. Following are the scopes that Guice supports: @Singleton - Single instance for lifetime of the application. @Singleton object needs to be threadsafe. @Singleton - Single instance for lifetime of the application. @Singleton object needs to be threadsafe. @SessionScoped - Single instance for a particular session of the web application. @SessionScoped object needs to be threadsafe. @SessionScoped - Single instance for a particular session of the web application. @SessionScoped object needs to be threadsafe. @RequestScoped - Single instance for a particular request of the web application. @RequestScoped object does not need to be threadsafe. @RequestScoped - Single instance for a particular request of the web application. @RequestScoped object does not need to be threadsafe. Following are the ways to apply scopes. @Singleton class SpellCheckerImpl implements SpellChecker { public SpellCheckerImpl(){} @Override public void checkSpelling() { System.out.println("Inside checkSpelling." ); } } bind(SpellChecker.class).to(SpellCheckerImpl.class).in(Singleton.class); @Provides @Singleton public SpellChecker provideSpellChecker(){ String dbUrl = "jdbc:mysql://localhost:5326/emp"; String user = "user"; int timeout = 100; SpellChecker SpellChecker = new SpellCheckerImpl(dbUrl, user, timeout); return SpellChecker; } Let's see the Scope at class level in action. Create a java class named GuiceTester. GuiceTester.java import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Singleton; public class GuiceTester { public static void main(String[] args) { Injector injector = Guice.createInjector(new TextEditorModule()); SpellChecker spellChecker = new SpellCheckerImpl(); injector.injectMembers(spellChecker); TextEditor editor = injector.getInstance(TextEditor.class); System.out.println(editor.getSpellCheckerId()); TextEditor editor1 = injector.getInstance(TextEditor.class); System.out.println(editor1.getSpellCheckerId()); } } class TextEditor { private SpellChecker spellChecker; @Inject public void setSpellChecker(SpellChecker spellChecker){ this.spellChecker = spellChecker; } public TextEditor() { } public void makeSpellCheck(){ spellChecker.checkSpelling(); } public double getSpellCheckerId(){ return spellChecker.getId(); } } //Binding Module class TextEditorModule extends AbstractModule { @Override protected void configure() { bind(SpellChecker.class).to(SpellCheckerImpl.class); } } interface SpellChecker { public double getId(); public void checkSpelling(); } @Singleton class SpellCheckerImpl implements SpellChecker { double id; public SpellCheckerImpl(){ id = Math.random(); } @Override public void checkSpelling() { System.out.println("Inside checkSpelling." ); } @Override public double getId() { return id; } } Compile and run the file, you may see the following output with same numbers. 0.3055839187063575 0.3055839187063575 Create a java class named GuiceTester. GuiceTester.java import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; public class GuiceTester { public static void main(String[] args) { Injector injector = Guice.createInjector(new TextEditorModule()); SpellChecker spellChecker = new SpellCheckerImpl(); injector.injectMembers(spellChecker); TextEditor editor = injector.getInstance(TextEditor.class); System.out.println(editor.getSpellCheckerId()); TextEditor editor1 = injector.getInstance(TextEditor.class); System.out.println(editor1.getSpellCheckerId()); } } class TextEditor { private SpellChecker spellChecker; @Inject public void setSpellChecker(SpellChecker spellChecker){ this.spellChecker = spellChecker; } public TextEditor() { } public void makeSpellCheck(){ spellChecker.checkSpelling(); } public double getSpellCheckerId(){ return spellChecker.getId(); } } //Binding Module class TextEditorModule extends AbstractModule { @Override protected void configure() { bind(SpellChecker.class).to(SpellCheckerImpl.class); } } interface SpellChecker { public double getId(); public void checkSpelling(); } class SpellCheckerImpl implements SpellChecker { double id; public SpellCheckerImpl(){ id = Math.random(); } @Override public void checkSpelling() { System.out.println("Inside checkSpelling." ); } @Override public double getId() { return id; } } Compile and run the file, you may see the following output with different numbers. 0.556007079571739 0.22095011760351602 27 Lectures 1.5 hours Lemuel Ogbunude Print Add Notes Bookmark this page
[ { "code": null, "e": 2270, "s": 2102, "text": "Guice returns a new instance every time when it supplies a value as its default behaviour. It is configurable via scopes. Following are the scopes that Guice supports:" }, { "code": null, "e": 2375, "s": 2270, "text": "@Singleton - Single instance for lifetime of the application. @Singleton object needs to be threadsafe.\n" }, { "code": null, "e": 2479, "s": 2375, "text": "@Singleton - Single instance for lifetime of the application. @Singleton object needs to be threadsafe." }, { "code": null, "e": 2608, "s": 2479, "text": "@SessionScoped - Single instance for a particular session of the web application. @SessionScoped object needs to be threadsafe.\n" }, { "code": null, "e": 2736, "s": 2608, "text": "@SessionScoped - Single instance for a particular session of the web application. @SessionScoped object needs to be threadsafe." }, { "code": null, "e": 2873, "s": 2736, "text": "@RequestScoped - Single instance for a particular request of the web application. @RequestScoped object does not need to be threadsafe.\n" }, { "code": null, "e": 3009, "s": 2873, "text": "@RequestScoped - Single instance for a particular request of the web application. @RequestScoped object does not need to be threadsafe." }, { "code": null, "e": 3049, "s": 3009, "text": "Following are the ways to apply scopes." }, { "code": null, "e": 3251, "s": 3049, "text": "@Singleton\nclass SpellCheckerImpl implements SpellChecker {\n\n public SpellCheckerImpl(){}\n \n @Override\n public void checkSpelling() { \n System.out.println(\"Inside checkSpelling.\" );\n }\n}" }, { "code": null, "e": 3327, "s": 3251, "text": " bind(SpellChecker.class).to(SpellCheckerImpl.class).in(Singleton.class);" }, { "code": null, "e": 3594, "s": 3327, "text": "@Provides @Singleton\npublic SpellChecker provideSpellChecker(){\n\n String dbUrl = \"jdbc:mysql://localhost:5326/emp\";\n String user = \"user\";\n int timeout = 100;\n\n SpellChecker SpellChecker = new SpellCheckerImpl(dbUrl, user, timeout);\n return SpellChecker;\n}" }, { "code": null, "e": 3640, "s": 3594, "text": "Let's see the Scope at class level in action." }, { "code": null, "e": 3679, "s": 3640, "text": "Create a java class named GuiceTester." }, { "code": null, "e": 3696, "s": 3679, "text": "GuiceTester.java" }, { "code": null, "e": 5320, "s": 3696, "text": "import com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Inject;\nimport com.google.inject.Injector;\nimport com.google.inject.Singleton;\n\npublic class GuiceTester {\n public static void main(String[] args) {\n Injector injector = Guice.createInjector(new TextEditorModule());\n SpellChecker spellChecker = new SpellCheckerImpl();\n injector.injectMembers(spellChecker);\n\n TextEditor editor = injector.getInstance(TextEditor.class); \n System.out.println(editor.getSpellCheckerId());\n\n TextEditor editor1 = injector.getInstance(TextEditor.class); \n System.out.println(editor1.getSpellCheckerId());\n } \n}\n\nclass TextEditor {\n private SpellChecker spellChecker;\n\n @Inject\n public void setSpellChecker(SpellChecker spellChecker){\n this.spellChecker = spellChecker;\n }\n public TextEditor() { }\n\n public void makeSpellCheck(){\n spellChecker.checkSpelling();\n } \n\n public double getSpellCheckerId(){\n return spellChecker.getId();\n }\n}\n\n//Binding Module\nclass TextEditorModule extends AbstractModule {\n\n @Override\n protected void configure() { \n bind(SpellChecker.class).to(SpellCheckerImpl.class);\n } \n}\n\ninterface SpellChecker {\n public double getId();\n public void checkSpelling();\n}\n\n@Singleton\nclass SpellCheckerImpl implements SpellChecker {\n\n double id; \n public SpellCheckerImpl(){\n id = Math.random(); \n }\n\n @Override\n public void checkSpelling() { \n System.out.println(\"Inside checkSpelling.\" );\n }\n\n @Override\n public double getId() { \n return id;\n }\n}" }, { "code": null, "e": 5398, "s": 5320, "text": "Compile and run the file, you may see the following output with same numbers." }, { "code": null, "e": 5437, "s": 5398, "text": "0.3055839187063575\n0.3055839187063575\n" }, { "code": null, "e": 5476, "s": 5437, "text": "Create a java class named GuiceTester." }, { "code": null, "e": 5493, "s": 5476, "text": "GuiceTester.java" }, { "code": null, "e": 7070, "s": 5493, "text": "import com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Inject;\nimport com.google.inject.Injector;\n\npublic class GuiceTester {\n public static void main(String[] args) {\n Injector injector = Guice.createInjector(new TextEditorModule());\n SpellChecker spellChecker = new SpellCheckerImpl();\n injector.injectMembers(spellChecker);\n\n TextEditor editor = injector.getInstance(TextEditor.class); \n System.out.println(editor.getSpellCheckerId());\n\n TextEditor editor1 = injector.getInstance(TextEditor.class); \n System.out.println(editor1.getSpellCheckerId());\n } \n}\n\nclass TextEditor {\n private SpellChecker spellChecker;\n\n @Inject\n public void setSpellChecker(SpellChecker spellChecker){\n this.spellChecker = spellChecker;\n }\n public TextEditor() { }\n\n public void makeSpellCheck(){\n spellChecker.checkSpelling();\n } \n\n public double getSpellCheckerId(){\n return spellChecker.getId();\n }\n}\n\n//Binding Module\nclass TextEditorModule extends AbstractModule {\n\n @Override\n protected void configure() { \n bind(SpellChecker.class).to(SpellCheckerImpl.class);\n } \n}\n\ninterface SpellChecker {\n public double getId();\n public void checkSpelling();\n}\n\nclass SpellCheckerImpl implements SpellChecker {\n\n double id; \n public SpellCheckerImpl(){\n id = Math.random(); \n }\n\n @Override\n public void checkSpelling() { \n System.out.println(\"Inside checkSpelling.\" );\n }\n\n @Override\n public double getId() { \n return id;\n }\n}" }, { "code": null, "e": 7153, "s": 7070, "text": "Compile and run the file, you may see the following output with different numbers." }, { "code": null, "e": 7192, "s": 7153, "text": "0.556007079571739\n0.22095011760351602\n" }, { "code": null, "e": 7227, "s": 7192, "text": "\n 27 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7244, "s": 7227, "text": " Lemuel Ogbunude" }, { "code": null, "e": 7251, "s": 7244, "text": " Print" }, { "code": null, "e": 7262, "s": 7251, "text": " Add Notes" } ]
Natural Language Toolkit - Tokenizing Text
It may be defined as the process of breaking up a piece of text into smaller parts, such as sentences and words. These smaller parts are called tokens. For example, a word is a token in a sentence, and a sentence is a token in a paragraph. As we know that NLP is used to build applications such as sentiment analysis, QA systems, language translation, smart chatbots, voice systems, etc., hence, in order to build them, it becomes vital to understand the pattern in the text. The tokens, mentioned above, are very useful in finding and understanding these patterns. We can consider tokenization as the base step for other recipes such as stemming and lemmatization. nltk.tokenize is the package provided by NLTK module to achieve the process of tokenization. Splitting the sentence into words or creating a list of words from a string is an essential part of every text processing activity. Let us understand it with the help of various functions/modules provided by nltk.tokenize package. word_tokenize module is used for basic word tokenization. Following example will use this module to split a sentence into words. import nltk from nltk.tokenize import word_tokenize word_tokenize('Tutorialspoint.com provides high quality technical tutorials for free.') ['Tutorialspoint.com', 'provides', 'high', 'quality', 'technical', 'tutorials', 'for', 'free', '.'] word_tokenize module, used above is basically a wrapper function that calls tokenize() function as an instance of the TreebankWordTokenizer class. It will give the same output as we get while using word_tokenize() module for splitting the sentences into word. Let us see the same example implemented above − First, we need to import the natural language toolkit(nltk). import nltk Now, import the TreebankWordTokenizer class to implement the word tokenizer algorithm − from nltk.tokenize import TreebankWordTokenizer Next, create an instance of TreebankWordTokenizer class as follows − Tokenizer_wrd = TreebankWordTokenizer() Now, input the sentence you want to convert to tokens − Tokenizer_wrd.tokenize( 'Tutorialspoint.com provides high quality technical tutorials for free.' ) [ 'Tutorialspoint.com', 'provides', 'high', 'quality', 'technical', 'tutorials', 'for', 'free', '.' ] Let us see the complete implementation example below import nltk from nltk.tokenize import TreebankWordTokenizer tokenizer_wrd = TreebankWordTokenizer() tokenizer_wrd.tokenize('Tutorialspoint.com provides high quality technical tutorials for free.') [ 'Tutorialspoint.com', 'provides', 'high', 'quality', 'technical', 'tutorials','for', 'free', '.' ] The most significant convention of a tokenizer is to separate contractions. For example, if we use word_tokenize() module for this purpose, it will give the output as follows − import nltk from nltk.tokenize import word_tokenize word_tokenize('won’t') ['wo', "n't"]] Such kind of convention by TreebankWordTokenizer is unacceptable. That’s why we have two alternative word tokenizers namely PunktWordTokenizer and WordPunctTokenizer. An alternative word tokenizer that splits all punctuation into separate tokens. Let us understand it with the following simple example − from nltk.tokenize import WordPunctTokenizer tokenizer = WordPunctTokenizer() tokenizer.tokenize(" I can't allow you to go home early") ['I', 'can', "'", 't', 'allow', 'you', 'to', 'go', 'home', 'early'] In this section we are going to split text/paragraph into sentences. NLTK provides sent_tokenize module for this purpose. An obvious question that came in our mind is that when we have word tokenizer then why do we need sentence tokenizer or why do we need to tokenize text into sentences. Suppose we need to count average words in sentences, how we can do this? For accomplishing this task, we need both sentence tokenization and word tokenization. Let us understand the difference between sentence and word tokenizer with the help of following simple example − import nltk from nltk.tokenize import sent_tokenize text = "Let us understand the difference between sentence & word tokenizer. It is going to be a simple example." sent_tokenize(text) [ "Let us understand the difference between sentence & word tokenizer.", 'It is going to be a simple example.' ] If you feel that the output of word tokenizer is unacceptable and want complete control over how to tokenize the text, we have regular expression which can be used while doing sentence tokenization. NLTK provide RegexpTokenizer class to achieve this. Let us understand the concept with the help of two examples below. In first example we will be using regular expression for matching alphanumeric tokens plus single quotes so that we don’t split contractions like “won’t”. import nltk from nltk.tokenize import RegexpTokenizer tokenizer = RegexpTokenizer("[\w']+") tokenizer.tokenize("won't is a contraction.") tokenizer.tokenize("can't is a contraction.") ["won't", 'is', 'a', 'contraction'] ["can't", 'is', 'a', 'contraction'] In first example, we will be using regular expression to tokenize on whitespace. import nltk from nltk.tokenize import RegexpTokenizer tokenizer = RegexpTokenizer('/s+' , gaps = True) tokenizer.tokenize("won't is a contraction.") ["won't", 'is', 'a', 'contraction'] From the above output, we can see that the punctuation remains in the tokens. The parameter gaps = True means the pattern is going to identify the gaps to tokenize on. On the other hand, if we will use gaps = False parameter then the pattern would be used to identify the tokens which can be seen in following example − import nltk from nltk.tokenize import RegexpTokenizer tokenizer = RegexpTokenizer('/s+' , gaps = False) tokenizer.tokenize("won't is a contraction.") [ ] It will give us the blank output. 59 Lectures 2.5 hours Mike West 17 Lectures 1 hours Pranjal Srivastava 6 Lectures 1 hours Prabh Kirpa Classes 12 Lectures 1 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2624, "s": 2384, "text": "It may be defined as the process of breaking up a piece of text into smaller parts, such as sentences and words. These smaller parts are called tokens. For example, a word is a token in a sentence, and a sentence is a token in a paragraph." }, { "code": null, "e": 3050, "s": 2624, "text": "As we know that NLP is used to build applications such as sentiment analysis, QA systems, language translation, smart chatbots, voice systems, etc., hence, in order to build them, it becomes vital to understand the pattern in the text. The tokens, mentioned above, are very useful in finding and understanding these patterns. We can consider tokenization as the base step for other recipes such as stemming and lemmatization." }, { "code": null, "e": 3143, "s": 3050, "text": "nltk.tokenize is the package provided by NLTK module to achieve the process of tokenization." }, { "code": null, "e": 3374, "s": 3143, "text": "Splitting the sentence into words or creating a list of words from a string is an essential part of every text processing activity. Let us understand it with the help of various functions/modules provided by nltk.tokenize package." }, { "code": null, "e": 3503, "s": 3374, "text": "word_tokenize module is used for basic word tokenization. Following example will use this module to split a sentence into words." }, { "code": null, "e": 3643, "s": 3503, "text": "import nltk\nfrom nltk.tokenize import word_tokenize\nword_tokenize('Tutorialspoint.com provides high quality technical tutorials for free.')" }, { "code": null, "e": 3744, "s": 3643, "text": "['Tutorialspoint.com', 'provides', 'high', 'quality', 'technical', 'tutorials', 'for', 'free', '.']\n" }, { "code": null, "e": 4052, "s": 3744, "text": "word_tokenize module, used above is basically a wrapper function that calls tokenize() function as an instance of the TreebankWordTokenizer class. It will give the same output as we get while using word_tokenize() module for splitting the sentences into word. Let us see the same example implemented above −" }, { "code": null, "e": 4113, "s": 4052, "text": "First, we need to import the natural language toolkit(nltk)." }, { "code": null, "e": 4126, "s": 4113, "text": "import nltk\n" }, { "code": null, "e": 4214, "s": 4126, "text": "Now, import the TreebankWordTokenizer class to implement the word tokenizer algorithm −" }, { "code": null, "e": 4263, "s": 4214, "text": "from nltk.tokenize import TreebankWordTokenizer\n" }, { "code": null, "e": 4332, "s": 4263, "text": "Next, create an instance of TreebankWordTokenizer class as follows −" }, { "code": null, "e": 4373, "s": 4332, "text": "Tokenizer_wrd = TreebankWordTokenizer()\n" }, { "code": null, "e": 4429, "s": 4373, "text": "Now, input the sentence you want to convert to tokens −" }, { "code": null, "e": 4532, "s": 4429, "text": "Tokenizer_wrd.tokenize(\n 'Tutorialspoint.com provides high quality technical tutorials for free.'\n)\n" }, { "code": null, "e": 4642, "s": 4532, "text": "[\n 'Tutorialspoint.com', 'provides', 'high', 'quality', \n 'technical', 'tutorials', 'for', 'free', '.'\n]\n" }, { "code": null, "e": 4695, "s": 4642, "text": "Let us see the complete implementation example below" }, { "code": null, "e": 4892, "s": 4695, "text": "import nltk\nfrom nltk.tokenize import TreebankWordTokenizer\ntokenizer_wrd = TreebankWordTokenizer()\ntokenizer_wrd.tokenize('Tutorialspoint.com provides high quality technical\ntutorials for free.')" }, { "code": null, "e": 5001, "s": 4892, "text": "[\n 'Tutorialspoint.com', 'provides', 'high', 'quality', \n 'technical', 'tutorials','for', 'free', '.'\n]\n" }, { "code": null, "e": 5178, "s": 5001, "text": "The most significant convention of a tokenizer is to separate contractions. For example, if we use word_tokenize() module for this purpose, it will give the output as follows −" }, { "code": null, "e": 5253, "s": 5178, "text": "import nltk\nfrom nltk.tokenize import word_tokenize\nword_tokenize('won’t')" }, { "code": null, "e": 5269, "s": 5253, "text": "['wo', \"n't\"]]\n" }, { "code": null, "e": 5436, "s": 5269, "text": "Such kind of convention by TreebankWordTokenizer is unacceptable. That’s why we have two alternative word tokenizers namely PunktWordTokenizer and WordPunctTokenizer." }, { "code": null, "e": 5573, "s": 5436, "text": "An alternative word tokenizer that splits all punctuation into separate tokens. Let us understand it with the following simple example −" }, { "code": null, "e": 5709, "s": 5573, "text": "from nltk.tokenize import WordPunctTokenizer\ntokenizer = WordPunctTokenizer()\ntokenizer.tokenize(\" I can't allow you to go home early\")" }, { "code": null, "e": 5778, "s": 5709, "text": "['I', 'can', \"'\", 't', 'allow', 'you', 'to', 'go', 'home', 'early']\n" }, { "code": null, "e": 5900, "s": 5778, "text": "In this section we are going to split text/paragraph into sentences. NLTK provides sent_tokenize module for this purpose." }, { "code": null, "e": 6228, "s": 5900, "text": "An obvious question that came in our mind is that when we have word tokenizer then why do we need sentence tokenizer or why do we need to tokenize text into sentences. Suppose we need to count average words in sentences, how we can do this? For accomplishing this task, we need both sentence tokenization and word tokenization." }, { "code": null, "e": 6341, "s": 6228, "text": "Let us understand the difference between sentence and word tokenizer with the help of following simple example −" }, { "code": null, "e": 6527, "s": 6341, "text": "import nltk\nfrom nltk.tokenize import sent_tokenize\ntext = \"Let us understand the difference between sentence & word tokenizer. \nIt is going to be a simple example.\"\nsent_tokenize(text)" }, { "code": null, "e": 6648, "s": 6527, "text": "[\n \"Let us understand the difference between sentence & word tokenizer.\", \n 'It is going to be a simple example.'\n]\n" }, { "code": null, "e": 6899, "s": 6648, "text": "If you feel that the output of word tokenizer is unacceptable and want complete control over how to tokenize the text, we have regular expression which can be used while doing sentence tokenization. NLTK provide RegexpTokenizer class to achieve this." }, { "code": null, "e": 6966, "s": 6899, "text": "Let us understand the concept with the help of two examples below." }, { "code": null, "e": 7121, "s": 6966, "text": "In first example we will be using regular expression for matching alphanumeric tokens plus single quotes so that we don’t split contractions like “won’t”." }, { "code": null, "e": 7305, "s": 7121, "text": "import nltk\nfrom nltk.tokenize import RegexpTokenizer\ntokenizer = RegexpTokenizer(\"[\\w']+\")\ntokenizer.tokenize(\"won't is a contraction.\")\ntokenizer.tokenize(\"can't is a contraction.\")" }, { "code": null, "e": 7378, "s": 7305, "text": "[\"won't\", 'is', 'a', 'contraction']\n[\"can't\", 'is', 'a', 'contraction']\n" }, { "code": null, "e": 7459, "s": 7378, "text": "In first example, we will be using regular expression to tokenize on whitespace." }, { "code": null, "e": 7608, "s": 7459, "text": "import nltk\nfrom nltk.tokenize import RegexpTokenizer\ntokenizer = RegexpTokenizer('/s+' , gaps = True)\ntokenizer.tokenize(\"won't is a contraction.\")" }, { "code": null, "e": 7645, "s": 7608, "text": "[\"won't\", 'is', 'a', 'contraction']\n" }, { "code": null, "e": 7965, "s": 7645, "text": "From the above output, we can see that the punctuation remains in the tokens. The parameter gaps = True means the pattern is going to identify the gaps to tokenize on. On the other hand, if we will use gaps = False parameter then the pattern would be used to identify the tokens which can be seen in following example −" }, { "code": null, "e": 8115, "s": 7965, "text": "import nltk\nfrom nltk.tokenize import RegexpTokenizer\ntokenizer = RegexpTokenizer('/s+' , gaps = False)\ntokenizer.tokenize(\"won't is a contraction.\")" }, { "code": null, "e": 8120, "s": 8115, "text": "[ ]\n" }, { "code": null, "e": 8154, "s": 8120, "text": "It will give us the blank output." }, { "code": null, "e": 8189, "s": 8154, "text": "\n 59 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8200, "s": 8189, "text": " Mike West" }, { "code": null, "e": 8233, "s": 8200, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 8253, "s": 8233, "text": " Pranjal Srivastava" }, { "code": null, "e": 8285, "s": 8253, "text": "\n 6 Lectures \n 1 hours \n" }, { "code": null, "e": 8306, "s": 8285, "text": " Prabh Kirpa Classes" }, { "code": null, "e": 8339, "s": 8306, "text": "\n 12 Lectures \n 1 hours \n" }, { "code": null, "e": 8362, "s": 8339, "text": " Stone River ELearning" }, { "code": null, "e": 8369, "s": 8362, "text": " Print" }, { "code": null, "e": 8380, "s": 8369, "text": " Add Notes" } ]
Java - Object and Classes
Java is an Object-Oriented Language. As a language that has the Object-Oriented feature, Java supports the following fundamental concepts − Polymorphism Inheritance Encapsulation Abstraction Classes Objects Instance Method Message Passing In this chapter, we will look into the concepts - Classes and Objects. Object − Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors – wagging the tail, barking, eating. An object is an instance of a class. Object − Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors – wagging the tail, barking, eating. An object is an instance of a class. Class − A class can be defined as a template/blueprint that describes the behavior/state that the object of its type support. Class − A class can be defined as a template/blueprint that describes the behavior/state that the object of its type support. Let us now look deep into what are objects. If we consider the real-world, we can find many objects around us, cars, dogs, humans, etc. All these objects have a state and a behavior. If we consider a dog, then its state is - name, breed, color, and the behavior is - barking, wagging the tail, running. If you compare the software object with a real-world object, they have very similar characteristics. Software objects also have a state and a behavior. A software object's state is stored in fields and behavior is shown via methods. So in software development, methods operate on the internal state of an object and the object-to-object communication is done via methods. A class is a blueprint from which individual objects are created. Following is a sample of a class. public class Dog { String breed; int age; String color; void barking() { } void hungry() { } void sleeping() { } } A class can contain any of the following variable types. Local variables − Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed. Local variables − Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed. Instance variables − Instance variables are variables within a class but outside any method. These variables are initialized when the class is instantiated. Instance variables can be accessed from inside any method, constructor or blocks of that particular class. Instance variables − Instance variables are variables within a class but outside any method. These variables are initialized when the class is instantiated. Instance variables can be accessed from inside any method, constructor or blocks of that particular class. Class variables − Class variables are variables declared within a class, outside any method, with the static keyword. Class variables − Class variables are variables declared within a class, outside any method, with the static keyword. A class can have any number of methods to access the value of various kinds of methods. In the above example, barking(), hungry() and sleeping() are methods. Following are some of the important topics that need to be discussed when looking into classes of the Java Language. When discussing about classes, one of the most important sub topic would be constructors. Every class has a constructor. If we do not explicitly write a constructor for a class, the Java compiler builds a default constructor for that class. Each time a new object is created, at least one constructor will be invoked. The main rule of constructors is that they should have the same name as the class. A class can have more than one constructor. Following is an example of a constructor − public class Puppy { public Puppy() { } public Puppy(String name) { // This constructor has one parameter, name. } } Java also supports Singleton Classes where you would be able to create only one instance of a class. Note − We have two different types of constructors. We are going to discuss constructors in detail in the subsequent chapters. As mentioned previously, a class provides the blueprints for objects. So basically, an object is created from a class. In Java, the new keyword is used to create new objects. There are three steps when creating an object from a class − Declaration − A variable declaration with a variable name with an object type. Declaration − A variable declaration with a variable name with an object type. Instantiation − The 'new' keyword is used to create the object. Instantiation − The 'new' keyword is used to create the object. Initialization − The 'new' keyword is followed by a call to a constructor. This call initializes the new object. Initialization − The 'new' keyword is followed by a call to a constructor. This call initializes the new object. Following is an example of creating an object − public class Puppy { public Puppy(String name) { // This constructor has one parameter, name. System.out.println("Passed Name is :" + name ); } public static void main(String []args) { // Following statement would create an object myPuppy Puppy myPuppy = new Puppy( "tommy" ); } } If we compile and run the above program, then it will produce the following result − Passed Name is :tommy Instance variables and methods are accessed via created objects. To access an instance variable, following is the fully qualified path − /* First create an object */ ObjectReference = new Constructor(); /* Now call a variable as follows */ ObjectReference.variableName; /* Now you can call a class method as follows */ ObjectReference.MethodName(); This example explains how to access instance variables and methods of a class. public class Puppy { int puppyAge; public Puppy(String name) { // This constructor has one parameter, name. System.out.println("Name chosen is :" + name ); } public void setAge( int age ) { puppyAge = age; } public int getAge( ) { System.out.println("Puppy's age is :" + puppyAge ); return puppyAge; } public static void main(String []args) { /* Object creation */ Puppy myPuppy = new Puppy( "tommy" ); /* Call class method to set puppy's age */ myPuppy.setAge( 2 ); /* Call another class method to get puppy's age */ myPuppy.getAge( ); /* You can access instance variable as follows as well */ System.out.println("Variable Value :" + myPuppy.puppyAge ); } } If we compile and run the above program, then it will produce the following result − Name chosen is :tommy Puppy's age is :2 Variable Value :2 As the last part of this section, let's now look into the source file declaration rules. These rules are essential when declaring classes, import statements and package statements in a source file. There can be only one public class per source file. There can be only one public class per source file. A source file can have multiple non-public classes. A source file can have multiple non-public classes. The public class name should be the name of the source file as well which should be appended by .java at the end. For example: the class name is public class Employee{} then the source file should be as Employee.java. The public class name should be the name of the source file as well which should be appended by .java at the end. For example: the class name is public class Employee{} then the source file should be as Employee.java. If the class is defined inside a package, then the package statement should be the first statement in the source file. If the class is defined inside a package, then the package statement should be the first statement in the source file. If import statements are present, then they must be written between the package statement and the class declaration. If there are no package statements, then the import statement should be the first line in the source file. If import statements are present, then they must be written between the package statement and the class declaration. If there are no package statements, then the import statement should be the first line in the source file. Import and package statements will imply to all the classes present in the source file. It is not possible to declare different import and/or package statements to different classes in the source file. Import and package statements will imply to all the classes present in the source file. It is not possible to declare different import and/or package statements to different classes in the source file. Classes have several access levels and there are different types of classes; abstract classes, final classes, etc. We will be explaining about all these in the access modifiers chapter. Apart from the above mentioned types of classes, Java also has some special classes called Inner classes and Anonymous classes. In simple words, it is a way of categorizing the classes and interfaces. When developing applications in Java, hundreds of classes and interfaces will be written, therefore categorizing these classes is a must as well as makes life much easier. In Java if a fully qualified name, which includes the package and the class name is given, then the compiler can easily locate the source code or classes. Import statement is a way of giving the proper location for the compiler to find that particular class. For example, the following line would ask the compiler to load all the classes available in directory java_installation/java/io − import java.io.*; For our case study, we will be creating two classes. They are Employee and EmployeeTest. First open notepad and add the following code. Remember this is the Employee class and the class is a public class. Now, save this source file with the name Employee.java. The Employee class has four instance variables - name, age, designation and salary. The class has one explicitly defined constructor, which takes a parameter. import java.io.*; public class Employee { String name; int age; String designation; double salary; // This is the constructor of the class Employee public Employee(String name) { this.name = name; } // Assign the age of the Employee to the variable age. public void empAge(int empAge) { age = empAge; } /* Assign the designation to the variable designation.*/ public void empDesignation(String empDesig) { designation = empDesig; } /* Assign the salary to the variable salary.*/ public void empSalary(double empSalary) { salary = empSalary; } /* Print the Employee details */ public void printEmployee() { System.out.println("Name:"+ name ); System.out.println("Age:" + age ); System.out.println("Designation:" + designation ); System.out.println("Salary:" + salary); } } As mentioned previously in this tutorial, processing starts from the main method. Therefore, in order for us to run this Employee class there should be a main method and objects should be created. We will be creating a separate class for these tasks. Following is the EmployeeTest class, which creates two instances of the class Employee and invokes the methods for each object to assign values for each variable. Save the following code in EmployeeTest.java file. import java.io.*; public class EmployeeTest { public static void main(String args[]) { /* Create two objects using constructor */ Employee empOne = new Employee("James Smith"); Employee empTwo = new Employee("Mary Anne"); // Invoking methods for each object created empOne.empAge(26); empOne.empDesignation("Senior Software Engineer"); empOne.empSalary(1000); empOne.printEmployee(); empTwo.empAge(21); empTwo.empDesignation("Software Engineer"); empTwo.empSalary(500); empTwo.printEmployee(); } } Now, compile both the classes and then run EmployeeTest to see the result as follows − C:\> javac Employee.java C:\> javac EmployeeTest.java C:\> java EmployeeTest Name:James Smith Age:26 Designation:Senior Software Engineer Salary:1000.0 Name:Mary Anne Age:21 Designation:Software Engineer Salary:500.0 In the next session, we will discuss the basic data types in Java and how they can be used when developing Java applications. 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2517, "s": 2377, "text": "Java is an Object-Oriented Language. As a language that has the Object-Oriented feature, Java supports the following fundamental concepts −" }, { "code": null, "e": 2530, "s": 2517, "text": "Polymorphism" }, { "code": null, "e": 2542, "s": 2530, "text": "Inheritance" }, { "code": null, "e": 2556, "s": 2542, "text": "Encapsulation" }, { "code": null, "e": 2568, "s": 2556, "text": "Abstraction" }, { "code": null, "e": 2576, "s": 2568, "text": "Classes" }, { "code": null, "e": 2584, "s": 2576, "text": "Objects" }, { "code": null, "e": 2593, "s": 2584, "text": "Instance" }, { "code": null, "e": 2600, "s": 2593, "text": "Method" }, { "code": null, "e": 2616, "s": 2600, "text": "Message Passing" }, { "code": null, "e": 2687, "s": 2616, "text": "In this chapter, we will look into the concepts - Classes and Objects." }, { "code": null, "e": 2873, "s": 2687, "text": "Object − Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors – wagging the tail, barking, eating. An object is an instance of a class." }, { "code": null, "e": 3059, "s": 2873, "text": "Object − Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors – wagging the tail, barking, eating. An object is an instance of a class." }, { "code": null, "e": 3185, "s": 3059, "text": "Class − A class can be defined as a template/blueprint that describes the behavior/state that the object of its type support." }, { "code": null, "e": 3311, "s": 3185, "text": "Class − A class can be defined as a template/blueprint that describes the behavior/state that the object of its type support." }, { "code": null, "e": 3494, "s": 3311, "text": "Let us now look deep into what are objects. If we consider the real-world, we can find many objects around us, cars, dogs, humans, etc. All these objects have a state and a behavior." }, { "code": null, "e": 3614, "s": 3494, "text": "If we consider a dog, then its state is - name, breed, color, and the behavior is - barking, wagging the tail, running." }, { "code": null, "e": 3715, "s": 3614, "text": "If you compare the software object with a real-world object, they have very similar characteristics." }, { "code": null, "e": 3847, "s": 3715, "text": "Software objects also have a state and a behavior. A software object's state is stored in fields and behavior is shown via methods." }, { "code": null, "e": 3986, "s": 3847, "text": "So in software development, methods operate on the internal state of an object and the object-to-object communication is done via methods." }, { "code": null, "e": 4052, "s": 3986, "text": "A class is a blueprint from which individual objects are created." }, { "code": null, "e": 4086, "s": 4052, "text": "Following is a sample of a class." }, { "code": null, "e": 4231, "s": 4086, "text": "public class Dog {\n String breed;\n int age;\n String color;\n\n void barking() {\n }\n\n void hungry() {\n }\n\n void sleeping() {\n }\n}" }, { "code": null, "e": 4288, "s": 4231, "text": "A class can contain any of the following variable types." }, { "code": null, "e": 4521, "s": 4288, "text": "Local variables − Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed." }, { "code": null, "e": 4754, "s": 4521, "text": "Local variables − Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed." }, { "code": null, "e": 5018, "s": 4754, "text": "Instance variables − Instance variables are variables within a class but outside any method. These variables are initialized when the class is instantiated. Instance variables can be accessed from inside any method, constructor or blocks of that particular class." }, { "code": null, "e": 5282, "s": 5018, "text": "Instance variables − Instance variables are variables within a class but outside any method. These variables are initialized when the class is instantiated. Instance variables can be accessed from inside any method, constructor or blocks of that particular class." }, { "code": null, "e": 5400, "s": 5282, "text": "Class variables − Class variables are variables declared within a class, outside any method, with the static keyword." }, { "code": null, "e": 5518, "s": 5400, "text": "Class variables − Class variables are variables declared within a class, outside any method, with the static keyword." }, { "code": null, "e": 5676, "s": 5518, "text": "A class can have any number of methods to access the value of various kinds of methods. In the above example, barking(), hungry() and sleeping() are methods." }, { "code": null, "e": 5793, "s": 5676, "text": "Following are some of the important topics that need to be discussed when looking into classes of the Java Language." }, { "code": null, "e": 6034, "s": 5793, "text": "When discussing about classes, one of the most important sub topic would be constructors. Every class has a constructor. If we do not explicitly write a constructor for a class, the Java compiler builds a default constructor for that class." }, { "code": null, "e": 6238, "s": 6034, "text": "Each time a new object is created, at least one constructor will be invoked. The main rule of constructors is that they should have the same name as the class. A class can have more than one constructor." }, { "code": null, "e": 6281, "s": 6238, "text": "Following is an example of a constructor −" }, { "code": null, "e": 6417, "s": 6281, "text": "public class Puppy {\n public Puppy() {\n }\n\n public Puppy(String name) {\n // This constructor has one parameter, name.\n }\n}" }, { "code": null, "e": 6518, "s": 6417, "text": "Java also supports Singleton Classes where you would be able to create only one instance of a class." }, { "code": null, "e": 6645, "s": 6518, "text": "Note − We have two different types of constructors. We are going to discuss constructors in detail in the subsequent chapters." }, { "code": null, "e": 6820, "s": 6645, "text": "As mentioned previously, a class provides the blueprints for objects. So basically, an object is created from a class. In Java, the new keyword is used to create new objects." }, { "code": null, "e": 6881, "s": 6820, "text": "There are three steps when creating an object from a class −" }, { "code": null, "e": 6960, "s": 6881, "text": "Declaration − A variable declaration with a variable name with an object type." }, { "code": null, "e": 7039, "s": 6960, "text": "Declaration − A variable declaration with a variable name with an object type." }, { "code": null, "e": 7103, "s": 7039, "text": "Instantiation − The 'new' keyword is used to create the object." }, { "code": null, "e": 7167, "s": 7103, "text": "Instantiation − The 'new' keyword is used to create the object." }, { "code": null, "e": 7280, "s": 7167, "text": "Initialization − The 'new' keyword is followed by a call to a constructor. This call initializes the new object." }, { "code": null, "e": 7393, "s": 7280, "text": "Initialization − The 'new' keyword is followed by a call to a constructor. This call initializes the new object." }, { "code": null, "e": 7441, "s": 7393, "text": "Following is an example of creating an object −" }, { "code": null, "e": 7759, "s": 7441, "text": "public class Puppy {\n public Puppy(String name) {\n // This constructor has one parameter, name.\n System.out.println(\"Passed Name is :\" + name );\n }\n\n public static void main(String []args) {\n // Following statement would create an object myPuppy\n Puppy myPuppy = new Puppy( \"tommy\" );\n }\n}" }, { "code": null, "e": 7844, "s": 7759, "text": "If we compile and run the above program, then it will produce the following result −" }, { "code": null, "e": 7867, "s": 7844, "text": "Passed Name is :tommy\n" }, { "code": null, "e": 8004, "s": 7867, "text": "Instance variables and methods are accessed via created objects. To access an instance variable, following is the fully qualified path −" }, { "code": null, "e": 8219, "s": 8004, "text": "/* First create an object */\nObjectReference = new Constructor();\n\n/* Now call a variable as follows */\nObjectReference.variableName;\n\n/* Now you can call a class method as follows */\nObjectReference.MethodName();\n" }, { "code": null, "e": 8298, "s": 8219, "text": "This example explains how to access instance variables and methods of a class." }, { "code": null, "e": 9069, "s": 8298, "text": "public class Puppy {\n int puppyAge;\n\n public Puppy(String name) {\n // This constructor has one parameter, name.\n System.out.println(\"Name chosen is :\" + name );\n }\n\n public void setAge( int age ) {\n puppyAge = age;\n }\n\n public int getAge( ) {\n System.out.println(\"Puppy's age is :\" + puppyAge );\n return puppyAge;\n }\n\n public static void main(String []args) {\n /* Object creation */\n Puppy myPuppy = new Puppy( \"tommy\" );\n\n /* Call class method to set puppy's age */\n myPuppy.setAge( 2 );\n\n /* Call another class method to get puppy's age */\n myPuppy.getAge( );\n\n /* You can access instance variable as follows as well */\n System.out.println(\"Variable Value :\" + myPuppy.puppyAge );\n }\n}" }, { "code": null, "e": 9154, "s": 9069, "text": "If we compile and run the above program, then it will produce the following result −" }, { "code": null, "e": 9213, "s": 9154, "text": "Name chosen is :tommy\nPuppy's age is :2\nVariable Value :2\n" }, { "code": null, "e": 9411, "s": 9213, "text": "As the last part of this section, let's now look into the source file declaration rules. These rules are essential when declaring classes, import statements and package statements in a source file." }, { "code": null, "e": 9463, "s": 9411, "text": "There can be only one public class per source file." }, { "code": null, "e": 9515, "s": 9463, "text": "There can be only one public class per source file." }, { "code": null, "e": 9567, "s": 9515, "text": "A source file can have multiple non-public classes." }, { "code": null, "e": 9619, "s": 9567, "text": "A source file can have multiple non-public classes." }, { "code": null, "e": 9837, "s": 9619, "text": "The public class name should be the name of the source file as well which should be appended by .java at the end. For example: the class name is public class Employee{} then the source file should be as Employee.java." }, { "code": null, "e": 10055, "s": 9837, "text": "The public class name should be the name of the source file as well which should be appended by .java at the end. For example: the class name is public class Employee{} then the source file should be as Employee.java." }, { "code": null, "e": 10174, "s": 10055, "text": "If the class is defined inside a package, then the package statement should be the first statement in the source file." }, { "code": null, "e": 10293, "s": 10174, "text": "If the class is defined inside a package, then the package statement should be the first statement in the source file." }, { "code": null, "e": 10517, "s": 10293, "text": "If import statements are present, then they must be written between the package statement and the class declaration. If there are no package statements, then the import statement should be the first line in the source file." }, { "code": null, "e": 10741, "s": 10517, "text": "If import statements are present, then they must be written between the package statement and the class declaration. If there are no package statements, then the import statement should be the first line in the source file." }, { "code": null, "e": 10943, "s": 10741, "text": "Import and package statements will imply to all the classes present in the source file. It is not possible to declare different import and/or package statements to different classes in the source file." }, { "code": null, "e": 11145, "s": 10943, "text": "Import and package statements will imply to all the classes present in the source file. It is not possible to declare different import and/or package statements to different classes in the source file." }, { "code": null, "e": 11331, "s": 11145, "text": "Classes have several access levels and there are different types of classes; abstract classes, final classes, etc. We will be explaining about all these in the access modifiers chapter." }, { "code": null, "e": 11459, "s": 11331, "text": "Apart from the above mentioned types of classes, Java also has some special classes called Inner classes and Anonymous classes." }, { "code": null, "e": 11704, "s": 11459, "text": "In simple words, it is a way of categorizing the classes and interfaces. When developing applications in Java, hundreds of classes and interfaces will be written, therefore categorizing these classes is a must as well as makes life much easier." }, { "code": null, "e": 11963, "s": 11704, "text": "In Java if a fully qualified name, which includes the package and the class name is given, then the compiler can easily locate the source code or classes. Import statement is a way of giving the proper location for the compiler to find that particular class." }, { "code": null, "e": 12093, "s": 11963, "text": "For example, the following line would ask the compiler to load all the classes available in directory java_installation/java/io −" }, { "code": null, "e": 12112, "s": 12093, "text": "import java.io.*;\n" }, { "code": null, "e": 12201, "s": 12112, "text": "For our case study, we will be creating two classes. They are Employee and EmployeeTest." }, { "code": null, "e": 12373, "s": 12201, "text": "First open notepad and add the following code. Remember this is the Employee class and the class is a public class. Now, save this source file with the name Employee.java." }, { "code": null, "e": 12532, "s": 12373, "text": "The Employee class has four instance variables - name, age, designation and salary. The class has one explicitly defined constructor, which takes a parameter." }, { "code": null, "e": 13416, "s": 12532, "text": "import java.io.*;\npublic class Employee {\n\n String name;\n int age;\n String designation;\n double salary;\n\n // This is the constructor of the class Employee\n public Employee(String name) {\n this.name = name;\n }\n\n // Assign the age of the Employee to the variable age.\n public void empAge(int empAge) {\n age = empAge;\n }\n\n /* Assign the designation to the variable designation.*/\n public void empDesignation(String empDesig) {\n designation = empDesig;\n }\n\n /* Assign the salary to the variable\tsalary.*/\n public void empSalary(double empSalary) {\n salary = empSalary;\n }\n\n /* Print the Employee details */\n public void printEmployee() {\n System.out.println(\"Name:\"+ name );\n System.out.println(\"Age:\" + age );\n System.out.println(\"Designation:\" + designation );\n System.out.println(\"Salary:\" + salary);\n }\n}" }, { "code": null, "e": 13667, "s": 13416, "text": "As mentioned previously in this tutorial, processing starts from the main method. Therefore, in order for us to run this Employee class there should be a main method and objects should be created. We will be creating a separate class for these tasks." }, { "code": null, "e": 13830, "s": 13667, "text": "Following is the EmployeeTest class, which creates two instances of the class Employee and invokes the methods for each object to assign values for each variable." }, { "code": null, "e": 13881, "s": 13830, "text": "Save the following code in EmployeeTest.java file." }, { "code": null, "e": 14460, "s": 13881, "text": "import java.io.*;\npublic class EmployeeTest {\n\n public static void main(String args[]) {\n /* Create two objects using constructor */\n Employee empOne = new Employee(\"James Smith\");\n Employee empTwo = new Employee(\"Mary Anne\");\n\n // Invoking methods for each object created\n empOne.empAge(26);\n empOne.empDesignation(\"Senior Software Engineer\");\n empOne.empSalary(1000);\n empOne.printEmployee();\n\n empTwo.empAge(21);\n empTwo.empDesignation(\"Software Engineer\");\n empTwo.empSalary(500);\n empTwo.printEmployee();\n }\n}" }, { "code": null, "e": 14547, "s": 14460, "text": "Now, compile both the classes and then run EmployeeTest to see the result as follows −" }, { "code": null, "e": 14765, "s": 14547, "text": "C:\\> javac Employee.java\nC:\\> javac EmployeeTest.java\nC:\\> java EmployeeTest\nName:James Smith\nAge:26\nDesignation:Senior Software Engineer\nSalary:1000.0\nName:Mary Anne\nAge:21\nDesignation:Software Engineer\nSalary:500.0\n" }, { "code": null, "e": 14891, "s": 14765, "text": "In the next session, we will discuss the basic data types in Java and how they can be used when developing Java applications." }, { "code": null, "e": 14924, "s": 14891, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 14940, "s": 14924, "text": " Malhar Lathkar" }, { "code": null, "e": 14973, "s": 14940, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 14989, "s": 14973, "text": " Malhar Lathkar" }, { "code": null, "e": 15024, "s": 14989, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 15038, "s": 15024, "text": " Anadi Sharma" }, { "code": null, "e": 15072, "s": 15038, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 15086, "s": 15072, "text": " Tushar Kale" }, { "code": null, "e": 15123, "s": 15086, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 15138, "s": 15123, "text": " Monica Mittal" }, { "code": null, "e": 15171, "s": 15138, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 15190, "s": 15171, "text": " Arnab Chakraborty" }, { "code": null, "e": 15197, "s": 15190, "text": " Print" }, { "code": null, "e": 15208, "s": 15197, "text": " Add Notes" } ]
Send Chrome Notification Using Python - GeeksforGeeks
29 Jun, 2021 In this article, we are going to see how to send a Chrome notification from your PC to a phone or several devices in this article. We may send messages, links, and other content. For this, we’ll use Python’s notify2 module and its various capabilities, which will help us in delivering messages to many devices. notify2 is a Python module that is used to deliver notifications and may be used for a variety of applications. For example, if we are creating a news notifier and you want to view the changes on your smartphone rather than your local workstation, we can easily use this module. pip install notify2 Step 1: Create a program that takes you to subscribe to the webapps. Python3 from notify_run import Notify notify = Notify()notify.register() Output: You will be given a link and a QR code; click on the link or scan the QR code to proceed. Step 2: When you click on the link, you will be presented with the following interface: Step 3: Simply click on the subscribe on this device button, and if you want alerts on other devices, the link is provided at the bottom; simply go to your device’s chrome, copy this URL, and then click on the subscribe on this device button. Step 4: Now write a Python program to send the notification. For sending alerts, the send function is utilized. Simply write a message within the send function and execute the script; you will be alerted by Chrome as well as any devices to which you have subscribed. Python3 from notify_run import Notify notify = Notify()notify.send("Any Message you want to send") Output: You will notify by Chrome after you run the script After you run the script, the message will also be shown on the web: Other devices, like the phone: python-modules python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe Selecting rows in pandas DataFrame based on conditions How To Convert Python Dictionary To JSON? Check if element exists in list in Python 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": 24292, "s": 24264, "text": "\n29 Jun, 2021" }, { "code": null, "e": 24604, "s": 24292, "text": "In this article, we are going to see how to send a Chrome notification from your PC to a phone or several devices in this article. We may send messages, links, and other content. For this, we’ll use Python’s notify2 module and its various capabilities, which will help us in delivering messages to many devices." }, { "code": null, "e": 24883, "s": 24604, "text": "notify2 is a Python module that is used to deliver notifications and may be used for a variety of applications. For example, if we are creating a news notifier and you want to view the changes on your smartphone rather than your local workstation, we can easily use this module." }, { "code": null, "e": 24903, "s": 24883, "text": "pip install notify2" }, { "code": null, "e": 24972, "s": 24903, "text": "Step 1: Create a program that takes you to subscribe to the webapps." }, { "code": null, "e": 24980, "s": 24972, "text": "Python3" }, { "code": "from notify_run import Notify notify = Notify()notify.register()", "e": 25046, "s": 24980, "text": null }, { "code": null, "e": 25054, "s": 25046, "text": "Output:" }, { "code": null, "e": 25144, "s": 25054, "text": "You will be given a link and a QR code; click on the link or scan the QR code to proceed." }, { "code": null, "e": 25232, "s": 25144, "text": "Step 2: When you click on the link, you will be presented with the following interface:" }, { "code": null, "e": 25475, "s": 25232, "text": "Step 3: Simply click on the subscribe on this device button, and if you want alerts on other devices, the link is provided at the bottom; simply go to your device’s chrome, copy this URL, and then click on the subscribe on this device button." }, { "code": null, "e": 25536, "s": 25475, "text": "Step 4: Now write a Python program to send the notification." }, { "code": null, "e": 25742, "s": 25536, "text": "For sending alerts, the send function is utilized. Simply write a message within the send function and execute the script; you will be alerted by Chrome as well as any devices to which you have subscribed." }, { "code": null, "e": 25750, "s": 25742, "text": "Python3" }, { "code": "from notify_run import Notify notify = Notify()notify.send(\"Any Message you want to send\")", "e": 25842, "s": 25750, "text": null }, { "code": null, "e": 25851, "s": 25842, "text": "Output: " }, { "code": null, "e": 25902, "s": 25851, "text": "You will notify by Chrome after you run the script" }, { "code": null, "e": 25971, "s": 25902, "text": "After you run the script, the message will also be shown on the web:" }, { "code": null, "e": 26002, "s": 25971, "text": "Other devices, like the phone:" }, { "code": null, "e": 26017, "s": 26002, "text": "python-modules" }, { "code": null, "e": 26032, "s": 26017, "text": "python-utility" }, { "code": null, "e": 26039, "s": 26032, "text": "Python" }, { "code": null, "e": 26137, "s": 26039, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26146, "s": 26137, "text": "Comments" }, { "code": null, "e": 26159, "s": 26146, "text": "Old Comments" }, { "code": null, "e": 26191, "s": 26159, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26247, "s": 26191, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26302, "s": 26247, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26344, "s": 26302, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26386, "s": 26344, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26417, "s": 26386, "text": "Python | os.path.join() method" }, { "code": null, "e": 26456, "s": 26417, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26485, "s": 26456, "text": "Create a directory in Python" }, { "code": null, "e": 26507, "s": 26485, "text": "Defaultdict in Python" } ]
5 Ways to Merge Dictionaries in Python | by Jimit Dholakia | Towards Data Science
In Python, a dictionary is a data structure which contains elements in the form of a key-value pair where keys are used to access the values of the dictionary. Python dictionaries are unordered and mutable i.e. the elements of the dictionaries can be changed. In this article, we will explore five different ways to merge two or more dictionaries, along with a crude way. For this article, let us create two dictionaries d1 and d2 which we want to concatenate into a single dictionary: d1 = {'India': 'Delhi', 'Canada': 'Ottawa', 'United States': 'Washington D. C.'}d2 = {'France': 'Paris', 'Malaysia': 'Kuala Lumpur'} You can merge two dictionaries by iterating over the key-value pairs of the second dictionary with the first one. d3 = d1.copy()for key, value in d2.items(): d3[key] = value print(d3)Output:{'India': 'Delhi', 'Canada': 'Ottawa', 'United States': 'Washington D. C.', 'France': 'Paris', 'Malaysia': 'Kuala Lumpur'} Now, let us see cleaner and better ways of merging the dictionaries: Dictionary has a method update() which merges the dictionary with the items from the other dictionary in-place and overwrites existing keys. d4 = d1.copy()d4.update(d2)print(d4)Output:{'India': 'Delhi', 'Canada': 'Ottawa', 'United States': 'Washington D. C.', 'France': 'Paris', 'Malaysia': 'Kuala Lumpur'} The update method modifies the current dictionary. So you might want to create a copy of the dictionary before operating on the dictionary. We can merge dictionaries in one line by simply using the unpacking operator (**). d5 = {**d1, **d2}print(d5)Output:{'India': 'Delhi', 'Canada': 'Ottawa', 'United States': 'Washington D. C.', 'France': 'Paris', 'Malaysia': 'Kuala Lumpur'} We can also merge multiple dictionaries using this method. {**dict1, **dict2, **dict3} This is, perhaps, the least known method to merge dictionaries. ChainMap class from the Collections module groups multiple dictionaries in a single view. from collections import ChainMapd6 = ChainMap(d1, d2)print(d6)Output:ChainMap({'Canada': 'Ottawa', 'India': 'Delhi', 'United States': 'Washington D. C.'}, {'France': 'Paris', 'Malaysia': 'Kuala Lumpur'}) This method returns an object of the ChainMap class. We can, still, use this object as we would use any other dictionary. e.g. d6[’India’] will return 'Delhi’. However, in case of the same keys in two dictionaries, this method will return the value of the first dictionary, unlike the other methods which return the value from the second dictionary. x = {'A': 1, 'B': 2}y = {'B': 10, 'C': 20}z = ChainMap(x, y)z['B']# outputs 2 We can merge the dictionaries by unpacking the second dictionary. d7 = dict(d1, **d2)print(d7)Output:{'India': 'Delhi', 'Canada': 'Ottawa', 'United States': 'Washington D. C.', 'France': 'Paris', 'Malaysia': 'Kuala Lumpur'} However, this method only works if the keys of the second dictionary are strings. x = {1: 'A', 2: 'B'}y = {3: 'C', 4: 'D'}z = dict(x, **y)Output:TypeError: keyword arguments must be strings Python 3.9 has introduced the merge operator (|) in the dict class. Using the merge operator, we can combine dictionaries in a single line of code. d8 = d1 | d2print(d8)Output:{'India': 'Delhi', 'Canada': 'Ottawa', 'United States': 'Washington D. C.', 'France': 'Paris', 'Malaysia': 'Kuala Lumpur'} We can also merge the dictionaries in-place by using the update operator (|=). d1 |= d2 The code snippets used in this article can be found on my GitHub page. LinkedIn: https://www.linkedin.com/in/jimit105/GitHub: https://github.com/jimit105Twitter: https://twitter.com/jimit105
[ { "code": null, "e": 432, "s": 172, "text": "In Python, a dictionary is a data structure which contains elements in the form of a key-value pair where keys are used to access the values of the dictionary. Python dictionaries are unordered and mutable i.e. the elements of the dictionaries can be changed." }, { "code": null, "e": 544, "s": 432, "text": "In this article, we will explore five different ways to merge two or more dictionaries, along with a crude way." }, { "code": null, "e": 658, "s": 544, "text": "For this article, let us create two dictionaries d1 and d2 which we want to concatenate into a single dictionary:" }, { "code": null, "e": 806, "s": 658, "text": "d1 = {'India': 'Delhi', 'Canada': 'Ottawa', 'United States': 'Washington D. C.'}d2 = {'France': 'Paris', 'Malaysia': 'Kuala Lumpur'}" }, { "code": null, "e": 920, "s": 806, "text": "You can merge two dictionaries by iterating over the key-value pairs of the second dictionary with the first one." }, { "code": null, "e": 1125, "s": 920, "text": "d3 = d1.copy()for key, value in d2.items(): d3[key] = value print(d3)Output:{'India': 'Delhi', 'Canada': 'Ottawa', 'United States': 'Washington D. C.', 'France': 'Paris', 'Malaysia': 'Kuala Lumpur'}" }, { "code": null, "e": 1194, "s": 1125, "text": "Now, let us see cleaner and better ways of merging the dictionaries:" }, { "code": null, "e": 1335, "s": 1194, "text": "Dictionary has a method update() which merges the dictionary with the items from the other dictionary in-place and overwrites existing keys." }, { "code": null, "e": 1501, "s": 1335, "text": "d4 = d1.copy()d4.update(d2)print(d4)Output:{'India': 'Delhi', 'Canada': 'Ottawa', 'United States': 'Washington D. C.', 'France': 'Paris', 'Malaysia': 'Kuala Lumpur'}" }, { "code": null, "e": 1641, "s": 1501, "text": "The update method modifies the current dictionary. So you might want to create a copy of the dictionary before operating on the dictionary." }, { "code": null, "e": 1724, "s": 1641, "text": "We can merge dictionaries in one line by simply using the unpacking operator (**)." }, { "code": null, "e": 1880, "s": 1724, "text": "d5 = {**d1, **d2}print(d5)Output:{'India': 'Delhi', 'Canada': 'Ottawa', 'United States': 'Washington D. C.', 'France': 'Paris', 'Malaysia': 'Kuala Lumpur'}" }, { "code": null, "e": 1939, "s": 1880, "text": "We can also merge multiple dictionaries using this method." }, { "code": null, "e": 1967, "s": 1939, "text": "{**dict1, **dict2, **dict3}" }, { "code": null, "e": 2121, "s": 1967, "text": "This is, perhaps, the least known method to merge dictionaries. ChainMap class from the Collections module groups multiple dictionaries in a single view." }, { "code": null, "e": 2360, "s": 2121, "text": "from collections import ChainMapd6 = ChainMap(d1, d2)print(d6)Output:ChainMap({'Canada': 'Ottawa', 'India': 'Delhi', 'United States': 'Washington D. C.'}, {'France': 'Paris', 'Malaysia': 'Kuala Lumpur'})" }, { "code": null, "e": 2520, "s": 2360, "text": "This method returns an object of the ChainMap class. We can, still, use this object as we would use any other dictionary. e.g. d6[’India’] will return 'Delhi’." }, { "code": null, "e": 2710, "s": 2520, "text": "However, in case of the same keys in two dictionaries, this method will return the value of the first dictionary, unlike the other methods which return the value from the second dictionary." }, { "code": null, "e": 2788, "s": 2710, "text": "x = {'A': 1, 'B': 2}y = {'B': 10, 'C': 20}z = ChainMap(x, y)z['B']# outputs 2" }, { "code": null, "e": 2854, "s": 2788, "text": "We can merge the dictionaries by unpacking the second dictionary." }, { "code": null, "e": 3012, "s": 2854, "text": "d7 = dict(d1, **d2)print(d7)Output:{'India': 'Delhi', 'Canada': 'Ottawa', 'United States': 'Washington D. C.', 'France': 'Paris', 'Malaysia': 'Kuala Lumpur'}" }, { "code": null, "e": 3094, "s": 3012, "text": "However, this method only works if the keys of the second dictionary are strings." }, { "code": null, "e": 3202, "s": 3094, "text": "x = {1: 'A', 2: 'B'}y = {3: 'C', 4: 'D'}z = dict(x, **y)Output:TypeError: keyword arguments must be strings" }, { "code": null, "e": 3350, "s": 3202, "text": "Python 3.9 has introduced the merge operator (|) in the dict class. Using the merge operator, we can combine dictionaries in a single line of code." }, { "code": null, "e": 3501, "s": 3350, "text": "d8 = d1 | d2print(d8)Output:{'India': 'Delhi', 'Canada': 'Ottawa', 'United States': 'Washington D. C.', 'France': 'Paris', 'Malaysia': 'Kuala Lumpur'}" }, { "code": null, "e": 3580, "s": 3501, "text": "We can also merge the dictionaries in-place by using the update operator (|=)." }, { "code": null, "e": 3589, "s": 3580, "text": "d1 |= d2" }, { "code": null, "e": 3660, "s": 3589, "text": "The code snippets used in this article can be found on my GitHub page." } ]
What are the most important tags for an HTML Document?
HTML has various tags to format content, heading, align content, add sections, etc to a website. The most important tags for an HTML document is doctype, <html>, <head> and <body>. doctypedoctype is the doctype declaration type. It is used for specifying which version of HTML the document is using. <!DOCTYPE html> <html> The HTML <html> tag is the container for all other HTML elements except for the <!DOCTYPE html> tag, which is located before the opening <html> tag. All other HTML elements are nested between the <html> and </html> tags.<head>The HTML <head> tag is used for indicating the head section of the HTML document. Tags included inside head tags are not displayed on browser window. The <title>...</title> tag goes inside the <html>...</html> <head> <title>HTML Document</title> </head> <body> The HTML <body> tag shows the main content section of the HTML document.
[ { "code": null, "e": 1243, "s": 1062, "text": "HTML has various tags to format content, heading, align content, add sections, etc to a website. The most important tags for an HTML document is doctype, <html>, <head> and <body>." }, { "code": null, "e": 1362, "s": 1243, "text": "doctypedoctype is the doctype declaration type. It is used for specifying which version of HTML the document is using." }, { "code": null, "e": 1378, "s": 1362, "text": "<!DOCTYPE html>" }, { "code": null, "e": 1385, "s": 1378, "text": "<html>" }, { "code": null, "e": 1465, "s": 1385, "text": "The HTML <html> tag is the container for all other HTML elements except for the" }, { "code": null, "e": 1821, "s": 1465, "text": "<!DOCTYPE html> tag, which is located before the opening <html> tag. All other HTML elements are nested between the <html> and </html> tags.<head>The HTML <head> tag is used for indicating the head section of the HTML document. Tags included inside head tags are not displayed on browser window. The <title>...</title> tag goes inside the <html>...</html>" }, { "code": null, "e": 1868, "s": 1821, "text": "<head>\n <title>HTML Document</title>\n</head>" }, { "code": null, "e": 1876, "s": 1868, "text": "<body> " }, { "code": null, "e": 1949, "s": 1876, "text": "The HTML <body> tag shows the main content section of the HTML document." } ]
Data Scientist vs Machine Learning Scientist Difference | Towards Data Science
IntroductionData ScientistsMachine Learning ScientistsSummaryReferences Introduction Data Scientists Machine Learning Scientists Summary References These two roles can sometimes be interchangeable amongst recruiters, however, if you are specialized in either of these roles, you know there is a difference. Both roles share a focus on machine learning algorithms, yet their day-to-day can be very different. Data scientists tend to focus more on use cases like credit card fraud detection, product classification, or customer segmentation, whereas machine learning scientists focus on use cases like signal processing, object detection, automobile/self-driving, and robotics. Below, I will be describing more specific differences between data scientists and machine learning scientists in terms of job goals, dedication, and skills. Data scientists may see more consistent job descriptions along with their respective education and skills required. A typical data scientist will usually work with a stakeholder to define a problem, build a dataset, compare various machine learning algorithms, output results, and interpret and present those results. Data scientist roles have a focus on business and collaboration between stakeholders. The models they build tend to not take as long as a machine learning scientist, say around a few months or even a few weeks, depending on the project. Here are some of the education and skills you can expect as a data scientist: Education BS or MS degree oriented Data Science Statistics Business Analytics Skills Python or R Data Analysis Tableau or another visualization software Jupyter Notebook SQL Regression Model Building Tend to be more simple use cases like ad-hoc classification, time series analysis, etc. Data scientists usually will have a foundation in business or data analytics, and then they will be able to use code, usually in Python or R to automate predictions using machine learning libraries in those programming languages. The road to a data scientist or machine learning scientist position may be different as well. For example, perhaps a data scientist started off as a statistician, business analyst, data analyst, or business intelligence analyst, and then became a data scientist. For a machine learning scientist, it may be a path where you start off as a computer scientist, software engineer, physicist, robotics engineer, or engineer in general, and then become a machine learning scientist. Of course, the typical path is not required, and you can land one of these positions in your own way, keeping in mind your own personal goals of what you want to do with machine learning. While data scientists can focus more on building a model and presenting results to stakeholders, machine learning scientists often are more focused on the algorithms themselves, as well as the software engineering around implementing the model. Machine learning scientists often have the word ‘Research’ in their title as well. This means that you may focus more on researching algorithms in general before implementing a more simple approach. Overall, these roles can indeed be the same at different companies, so it is ultimately up to you to realize the difference whenever you look at a job description. The biggest takeaway is that data science roles seem to be more popular and more consistent, meaning they do not vary as much in their job description as much as machine learning scientists do, so take these skills with a grain of salt. Some of the differences are in the education and skills required of which I will note below: Education Ph.D. degree oriented Machine Learning Computer Science Robotics Physics Mathematics Skills Research-heavy Signals & Distributed Systems OpenCV C++ or C Quality Assurance Automation Model Deployment Unix Artificial Intellgence Tend to be more complex use cases like self-driving cars, automatic robotics, etc. The skills required for machine learning scientists tend to include more software engineering focus, like C++ for example, as well as more automation and deployment focused. Also, in some job descriptions, we will see that there might be a specialization like Physics or Robotics. This article has outlined some of the differences and similarities between these two roles. There is a bit of overlap, as well as some clearer differences. I wanted to post this article as well in hopes that people will comment on their experiences in either role, as I know these two roles to some companies and employees may be exactly the same or vastly different. I have personally seen these differences myself, however, that does not mean that the same will be true for you. With that being said, I encourage you to explore both positions — in not just articles, but also in job descriptions themselves as that is where you will get the most accurate and applicable information, especially per company. To summarize, here are the main differences between data scientists and machine learning scientists: * Data scientists: Python, R, statistics, visualization tools, perhaps faster paced, simpler use cases* Machine learning scientists: software engineering, research-focused, perhaps slower paced, more involved use cases I have also attached some real job descriptions [4, 5, 6] if you would like to see machine learning scientist examples, as I know those positions tend to be rarer. It will also allow you to see the differences yourself. I hope you found my article both interesting and useful. Please feel free to comment down below what you see as similarities or differences between these two positions. Comment down below if you disagree or agree with these differences between data scientists and machine learning scientists. Please feel free to check out my profile and other articles, as well as reach out to me on LinkedIn. I am not affiliated with any of the mentioned companies. [1] Photo by Fitore F on Unsplash, (2019) [2] Photo by Stephen Dawson on Unsplash, (2018) [3] Photo by Bram Van Oost on Unsplash, (2019) [4] Indeed, Machine Learning Scientist / Engineer (MLSys 2021) Job Description, (2021) [5] Indeed, Machine Learning Research Scientist Job Description, (2021) [6] Indeed, Machine Learning Scientist Job Description, (2021)
[ { "code": null, "e": 243, "s": 171, "text": "IntroductionData ScientistsMachine Learning ScientistsSummaryReferences" }, { "code": null, "e": 256, "s": 243, "text": "Introduction" }, { "code": null, "e": 272, "s": 256, "text": "Data Scientists" }, { "code": null, "e": 300, "s": 272, "text": "Machine Learning Scientists" }, { "code": null, "e": 308, "s": 300, "text": "Summary" }, { "code": null, "e": 319, "s": 308, "text": "References" }, { "code": null, "e": 1004, "s": 319, "text": "These two roles can sometimes be interchangeable amongst recruiters, however, if you are specialized in either of these roles, you know there is a difference. Both roles share a focus on machine learning algorithms, yet their day-to-day can be very different. Data scientists tend to focus more on use cases like credit card fraud detection, product classification, or customer segmentation, whereas machine learning scientists focus on use cases like signal processing, object detection, automobile/self-driving, and robotics. Below, I will be describing more specific differences between data scientists and machine learning scientists in terms of job goals, dedication, and skills." }, { "code": null, "e": 1559, "s": 1004, "text": "Data scientists may see more consistent job descriptions along with their respective education and skills required. A typical data scientist will usually work with a stakeholder to define a problem, build a dataset, compare various machine learning algorithms, output results, and interpret and present those results. Data scientist roles have a focus on business and collaboration between stakeholders. The models they build tend to not take as long as a machine learning scientist, say around a few months or even a few weeks, depending on the project." }, { "code": null, "e": 1637, "s": 1559, "text": "Here are some of the education and skills you can expect as a data scientist:" }, { "code": null, "e": 1647, "s": 1637, "text": "Education" }, { "code": null, "e": 1672, "s": 1647, "text": "BS or MS degree oriented" }, { "code": null, "e": 1685, "s": 1672, "text": "Data Science" }, { "code": null, "e": 1696, "s": 1685, "text": "Statistics" }, { "code": null, "e": 1715, "s": 1696, "text": "Business Analytics" }, { "code": null, "e": 1722, "s": 1715, "text": "Skills" }, { "code": null, "e": 1734, "s": 1722, "text": "Python or R" }, { "code": null, "e": 1748, "s": 1734, "text": "Data Analysis" }, { "code": null, "e": 1790, "s": 1748, "text": "Tableau or another visualization software" }, { "code": null, "e": 1807, "s": 1790, "text": "Jupyter Notebook" }, { "code": null, "e": 1811, "s": 1807, "text": "SQL" }, { "code": null, "e": 1822, "s": 1811, "text": "Regression" }, { "code": null, "e": 1837, "s": 1822, "text": "Model Building" }, { "code": null, "e": 1925, "s": 1837, "text": "Tend to be more simple use cases like ad-hoc classification, time series analysis, etc." }, { "code": null, "e": 2155, "s": 1925, "text": "Data scientists usually will have a foundation in business or data analytics, and then they will be able to use code, usually in Python or R to automate predictions using machine learning libraries in those programming languages." }, { "code": null, "e": 2821, "s": 2155, "text": "The road to a data scientist or machine learning scientist position may be different as well. For example, perhaps a data scientist started off as a statistician, business analyst, data analyst, or business intelligence analyst, and then became a data scientist. For a machine learning scientist, it may be a path where you start off as a computer scientist, software engineer, physicist, robotics engineer, or engineer in general, and then become a machine learning scientist. Of course, the typical path is not required, and you can land one of these positions in your own way, keeping in mind your own personal goals of what you want to do with machine learning." }, { "code": null, "e": 3666, "s": 2821, "text": "While data scientists can focus more on building a model and presenting results to stakeholders, machine learning scientists often are more focused on the algorithms themselves, as well as the software engineering around implementing the model. Machine learning scientists often have the word ‘Research’ in their title as well. This means that you may focus more on researching algorithms in general before implementing a more simple approach. Overall, these roles can indeed be the same at different companies, so it is ultimately up to you to realize the difference whenever you look at a job description. The biggest takeaway is that data science roles seem to be more popular and more consistent, meaning they do not vary as much in their job description as much as machine learning scientists do, so take these skills with a grain of salt." }, { "code": null, "e": 3759, "s": 3666, "text": "Some of the differences are in the education and skills required of which I will note below:" }, { "code": null, "e": 3769, "s": 3759, "text": "Education" }, { "code": null, "e": 3791, "s": 3769, "text": "Ph.D. degree oriented" }, { "code": null, "e": 3808, "s": 3791, "text": "Machine Learning" }, { "code": null, "e": 3825, "s": 3808, "text": "Computer Science" }, { "code": null, "e": 3834, "s": 3825, "text": "Robotics" }, { "code": null, "e": 3842, "s": 3834, "text": "Physics" }, { "code": null, "e": 3854, "s": 3842, "text": "Mathematics" }, { "code": null, "e": 3861, "s": 3854, "text": "Skills" }, { "code": null, "e": 3876, "s": 3861, "text": "Research-heavy" }, { "code": null, "e": 3906, "s": 3876, "text": "Signals & Distributed Systems" }, { "code": null, "e": 3913, "s": 3906, "text": "OpenCV" }, { "code": null, "e": 3922, "s": 3913, "text": "C++ or C" }, { "code": null, "e": 3940, "s": 3922, "text": "Quality Assurance" }, { "code": null, "e": 3951, "s": 3940, "text": "Automation" }, { "code": null, "e": 3968, "s": 3951, "text": "Model Deployment" }, { "code": null, "e": 3973, "s": 3968, "text": "Unix" }, { "code": null, "e": 3996, "s": 3973, "text": "Artificial Intellgence" }, { "code": null, "e": 4079, "s": 3996, "text": "Tend to be more complex use cases like self-driving cars, automatic robotics, etc." }, { "code": null, "e": 4360, "s": 4079, "text": "The skills required for machine learning scientists tend to include more software engineering focus, like C++ for example, as well as more automation and deployment focused. Also, in some job descriptions, we will see that there might be a specialization like Physics or Robotics." }, { "code": null, "e": 5069, "s": 4360, "text": "This article has outlined some of the differences and similarities between these two roles. There is a bit of overlap, as well as some clearer differences. I wanted to post this article as well in hopes that people will comment on their experiences in either role, as I know these two roles to some companies and employees may be exactly the same or vastly different. I have personally seen these differences myself, however, that does not mean that the same will be true for you. With that being said, I encourage you to explore both positions — in not just articles, but also in job descriptions themselves as that is where you will get the most accurate and applicable information, especially per company." }, { "code": null, "e": 5170, "s": 5069, "text": "To summarize, here are the main differences between data scientists and machine learning scientists:" }, { "code": null, "e": 5389, "s": 5170, "text": "* Data scientists: Python, R, statistics, visualization tools, perhaps faster paced, simpler use cases* Machine learning scientists: software engineering, research-focused, perhaps slower paced, more involved use cases" }, { "code": null, "e": 5609, "s": 5389, "text": "I have also attached some real job descriptions [4, 5, 6] if you would like to see machine learning scientist examples, as I know those positions tend to be rarer. It will also allow you to see the differences yourself." }, { "code": null, "e": 5902, "s": 5609, "text": "I hope you found my article both interesting and useful. Please feel free to comment down below what you see as similarities or differences between these two positions. Comment down below if you disagree or agree with these differences between data scientists and machine learning scientists." }, { "code": null, "e": 6060, "s": 5902, "text": "Please feel free to check out my profile and other articles, as well as reach out to me on LinkedIn. I am not affiliated with any of the mentioned companies." }, { "code": null, "e": 6102, "s": 6060, "text": "[1] Photo by Fitore F on Unsplash, (2019)" }, { "code": null, "e": 6150, "s": 6102, "text": "[2] Photo by Stephen Dawson on Unsplash, (2018)" }, { "code": null, "e": 6197, "s": 6150, "text": "[3] Photo by Bram Van Oost on Unsplash, (2019)" }, { "code": null, "e": 6284, "s": 6197, "text": "[4] Indeed, Machine Learning Scientist / Engineer (MLSys 2021) Job Description, (2021)" }, { "code": null, "e": 6356, "s": 6284, "text": "[5] Indeed, Machine Learning Research Scientist Job Description, (2021)" } ]
PHP ob_get_clean() Function - GeeksforGeeks
17 Mar, 2021 The ob_get_clean() function is an in-built PHP function that is used to clean or delete the current output buffer. It’s also used to get the output buffering again after cleaning the buffer. The ob_get_clean() function is the combination of both ob_get_contents() and ob_end_clean(). Syntax: string|false ob_get_clean(); Parameters: It does not accept any parameter. Return value: This function returns the contents of the output buffer and end output buffering. If output buffering is not active, then it returns false. Example 1: Below is a simple example of ob_get_clean() functionality. PHP <?php // Create an output bufferob_start(); echo "Welcome to GeeksforGeeks"; $out = ob_get_clean();$out = strtolower($out); var_dump($out);?> Output: string(24) "Welcome to GeeksforGeeks" Example 2: PHP <?php // Declare a class class GFG { public function GFG_Funcion() { $variable = array( "A" => "Welcome", "B" => "GeeksforGeeks", "C" => "Geeks" ); foreach ($variable as $key => $value) { echo $key . " => " . $value; echo "<br/>"; } }} ob_start(); // Creating an object of class GFG$object = new GFG(); // Calling function$object -> GFG_Funcion(); $saved_ob_level = ob_get_level(); $start_ob_level=""; while (ob_get_level() > $start_ob_level) { ob_end_flush();} // Now, it is the final output buffer$content = ob_get_clean(); ?> Output: A => Welcome B => GeeksforGeeks C => Geeks Reference: https://www.php.net/manual/en/function.ob-get-clean.php PHP-function PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to fetch data from localserver database and display on HTML table using PHP ? How to create admin login page using PHP? Different ways for passing data to view in Laravel How to generate PDF file using PHP ? Create a drop-down list that options fetched from a MySQL database in PHP Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24972, "s": 24944, "text": "\n17 Mar, 2021" }, { "code": null, "e": 25256, "s": 24972, "text": "The ob_get_clean() function is an in-built PHP function that is used to clean or delete the current output buffer. It’s also used to get the output buffering again after cleaning the buffer. The ob_get_clean() function is the combination of both ob_get_contents() and ob_end_clean()." }, { "code": null, "e": 25264, "s": 25256, "text": "Syntax:" }, { "code": null, "e": 25293, "s": 25264, "text": "string|false ob_get_clean();" }, { "code": null, "e": 25339, "s": 25293, "text": "Parameters: It does not accept any parameter." }, { "code": null, "e": 25493, "s": 25339, "text": "Return value: This function returns the contents of the output buffer and end output buffering. If output buffering is not active, then it returns false." }, { "code": null, "e": 25563, "s": 25493, "text": "Example 1: Below is a simple example of ob_get_clean() functionality." }, { "code": null, "e": 25567, "s": 25563, "text": "PHP" }, { "code": "<?php // Create an output bufferob_start(); echo \"Welcome to GeeksforGeeks\"; $out = ob_get_clean();$out = strtolower($out); var_dump($out);?>", "e": 25714, "s": 25567, "text": null }, { "code": null, "e": 25722, "s": 25714, "text": "Output:" }, { "code": null, "e": 25760, "s": 25722, "text": "string(24) \"Welcome to GeeksforGeeks\"" }, { "code": null, "e": 25771, "s": 25760, "text": "Example 2:" }, { "code": null, "e": 25775, "s": 25771, "text": "PHP" }, { "code": "<?php // Declare a class class GFG { public function GFG_Funcion() { $variable = array( \"A\" => \"Welcome\", \"B\" => \"GeeksforGeeks\", \"C\" => \"Geeks\" ); foreach ($variable as $key => $value) { echo $key . \" => \" . $value; echo \"<br/>\"; } }} ob_start(); // Creating an object of class GFG$object = new GFG(); // Calling function$object -> GFG_Funcion(); $saved_ob_level = ob_get_level(); $start_ob_level=\"\"; while (ob_get_level() > $start_ob_level) { ob_end_flush();} // Now, it is the final output buffer$content = ob_get_clean(); ?>", "e": 26407, "s": 25775, "text": null }, { "code": null, "e": 26415, "s": 26407, "text": "Output:" }, { "code": null, "e": 26458, "s": 26415, "text": "A => Welcome\nB => GeeksforGeeks\nC => Geeks" }, { "code": null, "e": 26525, "s": 26458, "text": "Reference: https://www.php.net/manual/en/function.ob-get-clean.php" }, { "code": null, "e": 26538, "s": 26525, "text": "PHP-function" }, { "code": null, "e": 26542, "s": 26538, "text": "PHP" }, { "code": null, "e": 26559, "s": 26542, "text": "Web Technologies" }, { "code": null, "e": 26563, "s": 26559, "text": "PHP" }, { "code": null, "e": 26661, "s": 26563, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26670, "s": 26661, "text": "Comments" }, { "code": null, "e": 26683, "s": 26670, "text": "Old Comments" }, { "code": null, "e": 26765, "s": 26683, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 26807, "s": 26765, "text": "How to create admin login page using PHP?" }, { "code": null, "e": 26858, "s": 26807, "text": "Different ways for passing data to view in Laravel" }, { "code": null, "e": 26895, "s": 26858, "text": "How to generate PDF file using PHP ?" }, { "code": null, "e": 26969, "s": 26895, "text": "Create a drop-down list that options fetched from a MySQL database in PHP" }, { "code": null, "e": 27011, "s": 26969, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27044, "s": 27011, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27087, "s": 27044, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27149, "s": 27087, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Java Program for Recursive Bubble Sort
Following is the Java Program for Recursice Bubble Sort − Live Demo import java.util.Arrays; public class Demo{ static void bubble_sort(int my_arr[], int len_arr){ if (len_arr == 1) return; for (int i=0; i<len_arr-1; i++) if (my_arr[i] > my_arr[i+1]){ int temp = my_arr[i]; my_arr[i] = my_arr[i+1]; my_arr[i+1] = temp; } bubble_sort(my_arr, len_arr-1); } public static void main(String[] args){ int my_arr[] = {45, 67, 89, 31, 63, 0, 21, 12}; bubble_sort(my_arr, my_arr.length); System.out.println("The array after implementing bubble sort is "); System.out.println(Arrays.toString(my_arr)); } } The array after implementing bubble sort is [0, 12, 21, 31, 45, 63, 67, 89] A function named 'Demo' contains the function to perform bubble sort. If the length of the array is 1, then the array is returned. Otherwise, the array is iterated over and if the element at the first place is greater than the element at the next position, the elements are swapped. After the first pass, the largest element would have been fixed, and the bubble sort is called on all elements except the largest once. In the main function, the array is defined and it is passed as a parameter to the bubble sort function.
[ { "code": null, "e": 1120, "s": 1062, "text": "Following is the Java Program for Recursice Bubble Sort −" }, { "code": null, "e": 1131, "s": 1120, "text": " Live Demo" }, { "code": null, "e": 1758, "s": 1131, "text": "import java.util.Arrays;\npublic class Demo{\n static void bubble_sort(int my_arr[], int len_arr){\n if (len_arr == 1)\n return;\n for (int i=0; i<len_arr-1; i++)\n if (my_arr[i] > my_arr[i+1]){\n int temp = my_arr[i];\n my_arr[i] = my_arr[i+1];\n my_arr[i+1] = temp;\n }\n bubble_sort(my_arr, len_arr-1);\n }\n public static void main(String[] args){\n int my_arr[] = {45, 67, 89, 31, 63, 0, 21, 12};\n bubble_sort(my_arr, my_arr.length);\n System.out.println(\"The array after implementing bubble sort is \");\n System.out.println(Arrays.toString(my_arr));\n }\n}" }, { "code": null, "e": 1834, "s": 1758, "text": "The array after implementing bubble sort is\n[0, 12, 21, 31, 45, 63, 67, 89]" }, { "code": null, "e": 2117, "s": 1834, "text": "A function named 'Demo' contains the function to perform bubble sort. If the length of the array is 1, then the array is returned. Otherwise, the array is iterated over and if the element at the first place is greater than the element at the next position, the elements are swapped." }, { "code": null, "e": 2357, "s": 2117, "text": "After the first pass, the largest element would have been fixed, and the bubble sort is called on all elements except the largest once. In the main function, the array is defined and it is passed as a parameter to the bubble sort function." } ]
How to image copy the entire DB2 table TAB1 into a dataset?
The image copy allows us to download or copy the DB2 table into a mainframe dataset. There are two types of Image copy i.e. Full image copy and Incremental image copy. The full image copy is used to take the backup of the entire table. The incremental image copy refers to the differential backup. In order to take the full image copy of the DB2 table we can use the below JCL step. //STEP1 EXEC DSNUPROC //SYSCOPY DD DSN=TEST.TAB1.COPY,UNIT=SYSDA,VOL=SER=CPY01I, // SPACE=(CYL,(15,1)),DISP=(NEW,CATLG,CATLG) //SYSOUT DD SYSOUT=* //SYSIN DD * COPY TABLESPACE TAB1SPAC /* We can use the utility DSNUPROC for this purpose. The SYSCOPY will have the dataset in which we want to take the backup of the table. The SYSIN is populated with the parameter COPY TABLESPACE which is followed by the name of tablespace where the table TAB1 resides.
[ { "code": null, "e": 1445, "s": 1062, "text": "The image copy allows us to download or copy the DB2 table into a mainframe dataset. There are two types of Image copy i.e. Full image copy and Incremental image copy. The full image copy is used to take the backup of the entire table. The incremental image copy refers to the differential backup. In order to take the full image copy of the DB2 table we can use the below JCL step." }, { "code": null, "e": 1633, "s": 1445, "text": "//STEP1 EXEC DSNUPROC\n//SYSCOPY DD DSN=TEST.TAB1.COPY,UNIT=SYSDA,VOL=SER=CPY01I,\n// SPACE=(CYL,(15,1)),DISP=(NEW,CATLG,CATLG)\n//SYSOUT DD SYSOUT=*\n//SYSIN DD *\nCOPY TABLESPACE TAB1SPAC\n/*" }, { "code": null, "e": 1899, "s": 1633, "text": "We can use the utility DSNUPROC for this purpose. The SYSCOPY will have the dataset in which we want to take the backup of the table. The SYSIN is populated with the parameter COPY TABLESPACE which is followed by the name of tablespace where the table TAB1 resides." } ]
How to implement Dictionary with Python3
Dictionaries in python are a type of data structure that map keys to values as a key-value pair. They are one of the frequently used data structures and have many interesting properties. They are presented by enclosing them in a pair of curly brace like below. dict = {'day1':'Mon' ,'day2':'Tue','day3':'Wed'} The elements or key-value pairs in the dictionary are represented within single quotes and separated by a colon. We create a dictionary by assigning values written in the form of a key. Dict1 = {'day1':'Mon' ,'day2':'Tue','day3':'Wed'} print(type(dict1)) print(dict1) # Using the dict() method dict2 =dict({('day1','Mon'),('day2','Tue'),('day3','Wed')}) print(type(dict2)) print(dict2) Running the above code gives us the following result − {'day1': 'Mon', 'day2': 'Tue', 'day3': 'Wed'} Dictionaries can also be nested. Means, we have a dictionary as a value for one of the keys inside another dictionary. In the below example we have Saturday and Sunday marked as elements of an inner dictionary which is nested inside an outer dictionary. dict = {'day1': 'Mon', 'day2': 'Tue', 'day3': 'Wed','weekend':{'d1':'Saturday','d2':'Sunday'}} print(dict) Running the above code gives us the following result: {'day1': 'Mon', 'day2': 'Tue', 'day3': 'Wed', 'weekend': {'d1': 'Saturday', 'd2': 'Sunday'}} To access the elements of a dictionary, we can use the square brackets along with the key to obtain its value. We can also use the get() method to get the values for the dictionary elements. dict = {'day1': 'Mon', 'day2': 'Tue', 'day3': 'Wed','weekend':{'d1':'Saturday','d2':'Sunday'}} print(dict['day2']) print(dict['weekend']) print(dict.get('day3')) Running the above code gives us the following result: Tue {'d1': 'Saturday', 'd2': 'Sunday'} Wed We add new elements to a dictionary by adding a new key value pair. We can also add another dictionary as an element to create a nested dictionary. dict = {'day1': 'Mon', 'day2': 'Tue', 'day3': 'Wed'} dict['day4']='Thu' dict['day5']='Fri' print(dict) Running the above code gives us the following result: {'day1': 'Mon', 'day2': 'Tue', 'day3': 'Wed', 'day4': 'Thu', 'day5': 'Fri'} We can update a dictionary by adding a new entry or a key-value pair and modifying an existing entry. We have already seen the addition of new elements to the dictionary above. Now we will see the modification of existing entry.Here we simply take the key and assign the new value to the element. dict = {'day1': 'Mon', 'day2': 'Tue', 'day3': 'Wed'} dict['day1']='Monday' dict['day2']='Tuesday' print(dict) Running the above code gives us the following result: {'day1': 'Monday', 'day2': 'Tuesday', 'day3': 'Wed'} The specific elements of a dictionary can be deleted by using the del keyword. It can also be used to delete the entire dictionary. There is also the clear() method which can be used to remove elements from the entire dictionary. dict = {'day1': 'Mon', 'day2': 'Tue', 'day3': 'Wed'} print(dict) del dict['day3'] print(dict) dict.clear() print(dict) Running the above code gives us the following result: {'day1': 'Mon', 'day2': 'Tue', 'day3': 'Wed'} {'day1': 'Mon', 'day2': 'Tue'} {}
[ { "code": null, "e": 1323, "s": 1062, "text": "Dictionaries in python are a type of data structure that map keys to values as a key-value pair. They are one of the frequently used data structures and have many interesting properties. They are presented by enclosing them in a pair of curly brace like below." }, { "code": null, "e": 1372, "s": 1323, "text": "dict = {'day1':'Mon' ,'day2':'Tue','day3':'Wed'}" }, { "code": null, "e": 1485, "s": 1372, "text": "The elements or key-value pairs in the dictionary are represented within single quotes and separated by a colon." }, { "code": null, "e": 1558, "s": 1485, "text": "We create a dictionary by assigning values written in the form of a key." }, { "code": null, "e": 1759, "s": 1558, "text": "Dict1 = {'day1':'Mon' ,'day2':'Tue','day3':'Wed'}\nprint(type(dict1))\nprint(dict1)\n\n# Using the dict() method\ndict2 =dict({('day1','Mon'),('day2','Tue'),('day3','Wed')})\nprint(type(dict2))\nprint(dict2)" }, { "code": null, "e": 1814, "s": 1759, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1860, "s": 1814, "text": "{'day1': 'Mon', 'day2': 'Tue', 'day3': 'Wed'}" }, { "code": null, "e": 2114, "s": 1860, "text": "Dictionaries can also be nested. Means, we have a dictionary as a value for one of the keys inside another dictionary. In the below example we have Saturday and Sunday marked as elements of an inner dictionary which is nested inside an outer dictionary." }, { "code": null, "e": 2221, "s": 2114, "text": "dict = {'day1': 'Mon', 'day2': 'Tue', 'day3': 'Wed','weekend':{'d1':'Saturday','d2':'Sunday'}}\nprint(dict)" }, { "code": null, "e": 2275, "s": 2221, "text": "Running the above code gives us the following result:" }, { "code": null, "e": 2368, "s": 2275, "text": "{'day1': 'Mon', 'day2': 'Tue', 'day3': 'Wed', 'weekend': {'d1': 'Saturday', 'd2': 'Sunday'}}" }, { "code": null, "e": 2559, "s": 2368, "text": "To access the elements of a dictionary, we can use the square brackets along with the key to obtain its value. We can also use the get() method to get the values for the dictionary elements." }, { "code": null, "e": 2721, "s": 2559, "text": "dict = {'day1': 'Mon', 'day2': 'Tue', 'day3': 'Wed','weekend':{'d1':'Saturday','d2':'Sunday'}}\nprint(dict['day2'])\nprint(dict['weekend'])\nprint(dict.get('day3'))" }, { "code": null, "e": 2775, "s": 2721, "text": "Running the above code gives us the following result:" }, { "code": null, "e": 2818, "s": 2775, "text": "Tue\n{'d1': 'Saturday', 'd2': 'Sunday'}\nWed" }, { "code": null, "e": 2966, "s": 2818, "text": "We add new elements to a dictionary by adding a new key value pair. We can also add another dictionary as an element to create a nested dictionary." }, { "code": null, "e": 3069, "s": 2966, "text": "dict = {'day1': 'Mon', 'day2': 'Tue', 'day3': 'Wed'}\ndict['day4']='Thu'\ndict['day5']='Fri'\nprint(dict)" }, { "code": null, "e": 3123, "s": 3069, "text": "Running the above code gives us the following result:" }, { "code": null, "e": 3199, "s": 3123, "text": "{'day1': 'Mon', 'day2': 'Tue', 'day3': 'Wed', 'day4': 'Thu', 'day5': 'Fri'}" }, { "code": null, "e": 3496, "s": 3199, "text": "We can update a dictionary by adding a new entry or a key-value pair and modifying an existing entry. We have already seen the addition of new elements to the dictionary above. Now we will see the modification of existing entry.Here we simply take the key and assign the new value to the element." }, { "code": null, "e": 3606, "s": 3496, "text": "dict = {'day1': 'Mon', 'day2': 'Tue', 'day3': 'Wed'}\ndict['day1']='Monday'\ndict['day2']='Tuesday'\nprint(dict)" }, { "code": null, "e": 3660, "s": 3606, "text": "Running the above code gives us the following result:" }, { "code": null, "e": 3713, "s": 3660, "text": "{'day1': 'Monday', 'day2': 'Tuesday', 'day3': 'Wed'}" }, { "code": null, "e": 3943, "s": 3713, "text": "The specific elements of a dictionary can be deleted by using the del keyword. It can also be used to delete the entire dictionary. There is also the clear() method which can be used to remove elements from the entire dictionary." }, { "code": null, "e": 4062, "s": 3943, "text": "dict = {'day1': 'Mon', 'day2': 'Tue', 'day3': 'Wed'}\nprint(dict)\ndel dict['day3']\nprint(dict)\ndict.clear()\nprint(dict)" }, { "code": null, "e": 4116, "s": 4062, "text": "Running the above code gives us the following result:" }, { "code": null, "e": 4196, "s": 4116, "text": "{'day1': 'Mon', 'day2': 'Tue', 'day3': 'Wed'}\n{'day1': 'Mon', 'day2': 'Tue'}\n{}" } ]
Python - Create progress bar using tqdm module - GeeksforGeeks
22 Apr, 2020 In this article we will see how to make progress bar with the help of tqdm module. A progress bar is a graphical control element used to visualize the progression of an extended computer operation, such as a download, file transfer, or installation. Sometimes, the graphic is accompanied by a textual representation of the progress in a percent format. Required Modules : Tqdm : Tqdm package is one of the more comprehensive packages for progress bars with python and is handy for those instances you want to build scripts that keep the users informed on the status of your application. pip install tqdm Time : This module provides various time-related functions, it is part of python’s standard library. # importing modulesfrom tqdm import trangefrom time import sleep # creating loopfor i in trange(10, desc ="loop "): # slowing the for loop sleep(0.1) Output : Example 2: # importing modulesfrom tqdm import tnrangefrom time import sleep # creating loopfor i in tnrange(2, desc ="loop 1"): # creating nested loop for j in tnrange(5, desc ="loop 2"): # slowing the for loop sleep(0.2) Output : Example 3: # importing modulesimport timeimport sysfrom tqdm import trange # random functiondef random_task(): time.sleep(0.5) # another random functiondef another_random_task(): time.sleep(0.2) # Outer loopfor i in trange(3, file=sys.stdout, desc='Outer loop'): random_task() # inner loop for j in trange(5,file=sys.stdout, desc='Inner loop'): another_random_task() Output : python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Reading and Writing to text files in Python sum() function in Python *args and **kwargs in Python
[ { "code": null, "e": 24320, "s": 24292, "text": "\n22 Apr, 2020" }, { "code": null, "e": 24673, "s": 24320, "text": "In this article we will see how to make progress bar with the help of tqdm module. A progress bar is a graphical control element used to visualize the progression of an extended computer operation, such as a download, file transfer, or installation. Sometimes, the graphic is accompanied by a textual representation of the progress in a percent format." }, { "code": null, "e": 24692, "s": 24673, "text": "Required Modules :" }, { "code": null, "e": 24907, "s": 24692, "text": "Tqdm : Tqdm package is one of the more comprehensive packages for progress bars with python and is handy for those instances you want to build scripts that keep the users informed on the status of your application." }, { "code": null, "e": 24924, "s": 24907, "text": "pip install tqdm" }, { "code": null, "e": 25025, "s": 24924, "text": "Time : This module provides various time-related functions, it is part of python’s standard library." }, { "code": "# importing modulesfrom tqdm import trangefrom time import sleep # creating loopfor i in trange(10, desc =\"loop \"): # slowing the for loop sleep(0.1)", "e": 25202, "s": 25025, "text": null }, { "code": null, "e": 25211, "s": 25202, "text": "Output :" }, { "code": null, "e": 25222, "s": 25211, "text": "Example 2:" }, { "code": "# importing modulesfrom tqdm import tnrangefrom time import sleep # creating loopfor i in tnrange(2, desc =\"loop 1\"): # creating nested loop for j in tnrange(5, desc =\"loop 2\"): # slowing the for loop sleep(0.2)", "e": 25471, "s": 25222, "text": null }, { "code": null, "e": 25480, "s": 25471, "text": "Output :" }, { "code": null, "e": 25491, "s": 25480, "text": "Example 3:" }, { "code": "# importing modulesimport timeimport sysfrom tqdm import trange # random functiondef random_task(): time.sleep(0.5) # another random functiondef another_random_task(): time.sleep(0.2) # Outer loopfor i in trange(3, file=sys.stdout, desc='Outer loop'): random_task() # inner loop for j in trange(5,file=sys.stdout, desc='Inner loop'): another_random_task()", "e": 25882, "s": 25491, "text": null }, { "code": null, "e": 25891, "s": 25882, "text": "Output :" }, { "code": null, "e": 25906, "s": 25891, "text": "python-utility" }, { "code": null, "e": 25913, "s": 25906, "text": "Python" }, { "code": null, "e": 26011, "s": 25913, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26020, "s": 26011, "text": "Comments" }, { "code": null, "e": 26033, "s": 26020, "text": "Old Comments" }, { "code": null, "e": 26051, "s": 26033, "text": "Python Dictionary" }, { "code": null, "e": 26086, "s": 26051, "text": "Read a file line by line in Python" }, { "code": null, "e": 26108, "s": 26086, "text": "Enumerate() in Python" }, { "code": null, "e": 26140, "s": 26108, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26182, "s": 26140, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26208, "s": 26182, "text": "Python String | replace()" }, { "code": null, "e": 26245, "s": 26208, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 26289, "s": 26245, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 26314, "s": 26289, "text": "sum() function in Python" } ]
Jupyter + IDE: how to make it work | by Denis Kazakov | Towards Data Science
If you work with data in Python, you probably know of Jupyter notebooks. The format just makes sense for simultaneously writing code and exploring data ..or does it?! Most of critique about relying on notebooks can be found in this excellent talk: I don’t like notebooks, Joel Grus. To summarize, notebooks are not a great environment for a large project: git versioning doesn’t really work, tests are not supported, ultimately notebooks become a mess of code scattered across cells. Of course, all of that falls flat against a simple argument: “But.. notebooks are so convenient” (me a year ago probably) When working with data, you almost never know if your approach works or not just because your code runs. You always do analysis during and after developing a model, track results of different hypothesis, record observations, etc. Notebook format really does align with that process. But that doesn’t mean it can’t be improved. Let’s summarize exactly why we love and hate Jupyter notebooks and IDEs (Integrated Development Environment). Finally, let’s see how to marry the best of both worlds in one simple workflow. (Optional) Use pyenv for isolating your python for each project space. Installation guide. Virtual environments are a different topic, but I think they’re also super helpful. Editable pip install We use pip to essentially point python to a ‘package’ that will be our code. It’s not a real package though, rather just a link to our code. This allows us to import our code as if it was a python package, while also being able to edit our code and updating the ‘package’ for it on the fly. cd YOUR_PROJECT_ROOTmkdir lib Define the package by creating asetup.pyfile in your project root: from setuptools import setupsetup( name='lib', version='0.1.0', packages=['lib'],) Install the package with pip’s editable flag: pip install -e . Package structure We still need our code to have a package structure. Every folder in lib directory needs to have an empty __init__.py file. |-- setup.py|-- lib| |-- __init__.py| |-- tools| |-- __init__.py| |-- tool.py As an example, in lib/tools/tool.py define a function: def yo(): print("Hello World") You can now import it in a python shell with: >>> from lib.tools.tool import yo>>> yo()Hello World Autoreload Jupyter can dynamically reload any package changes with autoreload. In your Jupyter notebook, run autoreload import once: %load_ext autoreload%autoreload 2 Now when we edit code inlib using our favourite IDE, we will have: python automatically put the edits into a lib package,Jupyter notebook automatically propagate the changes whenever we use that package. python automatically put the edits into a lib package, Jupyter notebook automatically propagate the changes whenever we use that package. The changes propagate from an IDE to notebook immediately, as soon as you save the file you’re working on! Note, I did not need to rerun the function import to see the changes. It allows me to keep my notebooks to the point, documenting the results I want to keep, while keeping good quality code in a proper repository that can be reused later, without a need to copy paste chunks of code from notebook to notebook. It also allows me to use a powerful IDE to develop quality code, making me waste less time on documenting code, syntax errors, etc.
[ { "code": null, "e": 339, "s": 172, "text": "If you work with data in Python, you probably know of Jupyter notebooks. The format just makes sense for simultaneously writing code and exploring data ..or does it?!" }, { "code": null, "e": 717, "s": 339, "text": "Most of critique about relying on notebooks can be found in this excellent talk: I don’t like notebooks, Joel Grus. To summarize, notebooks are not a great environment for a large project: git versioning doesn’t really work, tests are not supported, ultimately notebooks become a mess of code scattered across cells. Of course, all of that falls flat against a simple argument:" }, { "code": null, "e": 778, "s": 717, "text": "“But.. notebooks are so convenient” (me a year ago probably)" }, { "code": null, "e": 1105, "s": 778, "text": "When working with data, you almost never know if your approach works or not just because your code runs. You always do analysis during and after developing a model, track results of different hypothesis, record observations, etc. Notebook format really does align with that process. But that doesn’t mean it can’t be improved." }, { "code": null, "e": 1215, "s": 1105, "text": "Let’s summarize exactly why we love and hate Jupyter notebooks and IDEs (Integrated Development Environment)." }, { "code": null, "e": 1295, "s": 1215, "text": "Finally, let’s see how to marry the best of both worlds in one simple workflow." }, { "code": null, "e": 1386, "s": 1295, "text": "(Optional) Use pyenv for isolating your python for each project space. Installation guide." }, { "code": null, "e": 1470, "s": 1386, "text": "Virtual environments are a different topic, but I think they’re also super helpful." }, { "code": null, "e": 1491, "s": 1470, "text": "Editable pip install" }, { "code": null, "e": 1782, "s": 1491, "text": "We use pip to essentially point python to a ‘package’ that will be our code. It’s not a real package though, rather just a link to our code. This allows us to import our code as if it was a python package, while also being able to edit our code and updating the ‘package’ for it on the fly." }, { "code": null, "e": 1812, "s": 1782, "text": "cd YOUR_PROJECT_ROOTmkdir lib" }, { "code": null, "e": 1879, "s": 1812, "text": "Define the package by creating asetup.pyfile in your project root:" }, { "code": null, "e": 1965, "s": 1879, "text": "from setuptools import setupsetup( name='lib', version='0.1.0', packages=['lib'],)" }, { "code": null, "e": 2011, "s": 1965, "text": "Install the package with pip’s editable flag:" }, { "code": null, "e": 2028, "s": 2011, "text": "pip install -e ." }, { "code": null, "e": 2046, "s": 2028, "text": "Package structure" }, { "code": null, "e": 2169, "s": 2046, "text": "We still need our code to have a package structure. Every folder in lib directory needs to have an empty __init__.py file." }, { "code": null, "e": 2263, "s": 2169, "text": "|-- setup.py|-- lib| |-- __init__.py| |-- tools| |-- __init__.py| |-- tool.py" }, { "code": null, "e": 2318, "s": 2263, "text": "As an example, in lib/tools/tool.py define a function:" }, { "code": null, "e": 2352, "s": 2318, "text": "def yo(): print(\"Hello World\")" }, { "code": null, "e": 2398, "s": 2352, "text": "You can now import it in a python shell with:" }, { "code": null, "e": 2451, "s": 2398, "text": ">>> from lib.tools.tool import yo>>> yo()Hello World" }, { "code": null, "e": 2462, "s": 2451, "text": "Autoreload" }, { "code": null, "e": 2584, "s": 2462, "text": "Jupyter can dynamically reload any package changes with autoreload. In your Jupyter notebook, run autoreload import once:" }, { "code": null, "e": 2618, "s": 2584, "text": "%load_ext autoreload%autoreload 2" }, { "code": null, "e": 2685, "s": 2618, "text": "Now when we edit code inlib using our favourite IDE, we will have:" }, { "code": null, "e": 2822, "s": 2685, "text": "python automatically put the edits into a lib package,Jupyter notebook automatically propagate the changes whenever we use that package." }, { "code": null, "e": 2877, "s": 2822, "text": "python automatically put the edits into a lib package," }, { "code": null, "e": 2960, "s": 2877, "text": "Jupyter notebook automatically propagate the changes whenever we use that package." }, { "code": null, "e": 3137, "s": 2960, "text": "The changes propagate from an IDE to notebook immediately, as soon as you save the file you’re working on! Note, I did not need to rerun the function import to see the changes." }, { "code": null, "e": 3377, "s": 3137, "text": "It allows me to keep my notebooks to the point, documenting the results I want to keep, while keeping good quality code in a proper repository that can be reused later, without a need to copy paste chunks of code from notebook to notebook." } ]
C# | Boolean.Equals(Boolean) Method - GeeksforGeeks
28 Jun, 2021 This method is used to return a value indicating whether this instance is equal to a specified Boolean object.Syntax: public bool Equals (bool obj); Here, obj is a boolean value to compare to this instance.Return Value: This method returns true if obj has the same value as this instance otherwise it returns false.Below programs illustrate the use of Boolean.Equals(bool obj) Method:Example 1: CSHARP // C# program to demonstrate// Boolean.Parse(String)// Methodusing System; class GFG { // Main Method public static void Main() { // passing different values // to the method to check check(true, true); check(true, false); check(false, true); check(false, false); } // Defining check method public static void check(bool input1, bool input2) { // declaring bool variable bool val; // getting parsed value val = input1.Equals(input2); // checking the equivalency if (val == true) Console.WriteLine("{0} is equal to {1}", input1, input2); else Console.WriteLine("{0} is not equal to {1}", input1, input2); }} True is equal to True True is not equal to False False is not equal to True False is equal to False Example 2: CSHARP // C# program to demonstrate// Boolean.Parse(String)// Methodusing System; class GFG { // Main Method public static void Main() { // Declaring the variable // input1 and input2 bool input1, input2; // initializing the variables input1 = true; input2 = false; // checking the equality bool val = input1.Equals(input2); // checking the equivalency if (val == true) Console.WriteLine("input1 is equal to input2"); else Console.WriteLine("input1 is not equal to input2"); }} input1 is not equal to input2 Note: This method implements the System.IEquatable<T> interface, and performs slightly better than Equals because it does not have to convert the obj parameter to an object.Reference: https://docs.microsoft.com/en-us/dotnet/api/system.boolean.equals?view=netframework-4.7.2#System_Boolean_Equals_System_Boolean_ sweetyty CSharp Boolean Struct CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Delegates C# | Method Overriding C# | Abstract Classes Difference between Ref and Out keywords in C# Extension Method in C# C# | Replace() Method C# | String.IndexOf( ) Method | Set - 1 C# | Class and Object C# | Constructors
[ { "code": null, "e": 25593, "s": 25565, "text": "\n28 Jun, 2021" }, { "code": null, "e": 25713, "s": 25593, "text": "This method is used to return a value indicating whether this instance is equal to a specified Boolean object.Syntax: " }, { "code": null, "e": 25744, "s": 25713, "text": "public bool Equals (bool obj);" }, { "code": null, "e": 25991, "s": 25744, "text": "Here, obj is a boolean value to compare to this instance.Return Value: This method returns true if obj has the same value as this instance otherwise it returns false.Below programs illustrate the use of Boolean.Equals(bool obj) Method:Example 1: " }, { "code": null, "e": 25998, "s": 25991, "text": "CSHARP" }, { "code": "// C# program to demonstrate// Boolean.Parse(String)// Methodusing System; class GFG { // Main Method public static void Main() { // passing different values // to the method to check check(true, true); check(true, false); check(false, true); check(false, false); } // Defining check method public static void check(bool input1, bool input2) { // declaring bool variable bool val; // getting parsed value val = input1.Equals(input2); // checking the equivalency if (val == true) Console.WriteLine(\"{0} is equal to {1}\", input1, input2); else Console.WriteLine(\"{0} is not equal to {1}\", input1, input2); }}", "e": 26823, "s": 25998, "text": null }, { "code": null, "e": 26923, "s": 26823, "text": "True is equal to True\nTrue is not equal to False\nFalse is not equal to True\nFalse is equal to False" }, { "code": null, "e": 26937, "s": 26925, "text": "Example 2: " }, { "code": null, "e": 26944, "s": 26937, "text": "CSHARP" }, { "code": "// C# program to demonstrate// Boolean.Parse(String)// Methodusing System; class GFG { // Main Method public static void Main() { // Declaring the variable // input1 and input2 bool input1, input2; // initializing the variables input1 = true; input2 = false; // checking the equality bool val = input1.Equals(input2); // checking the equivalency if (val == true) Console.WriteLine(\"input1 is equal to input2\"); else Console.WriteLine(\"input1 is not equal to input2\"); }}", "e": 27532, "s": 26944, "text": null }, { "code": null, "e": 27562, "s": 27532, "text": "input1 is not equal to input2" }, { "code": null, "e": 27750, "s": 27564, "text": "Note: This method implements the System.IEquatable<T> interface, and performs slightly better than Equals because it does not have to convert the obj parameter to an object.Reference: " }, { "code": null, "e": 27878, "s": 27750, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.boolean.equals?view=netframework-4.7.2#System_Boolean_Equals_System_Boolean_" }, { "code": null, "e": 27889, "s": 27880, "text": "sweetyty" }, { "code": null, "e": 27911, "s": 27889, "text": "CSharp Boolean Struct" }, { "code": null, "e": 27925, "s": 27911, "text": "CSharp-method" }, { "code": null, "e": 27928, "s": 27925, "text": "C#" }, { "code": null, "e": 28026, "s": 27928, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28054, "s": 28026, "text": "C# Dictionary with examples" }, { "code": null, "e": 28069, "s": 28054, "text": "C# | Delegates" }, { "code": null, "e": 28092, "s": 28069, "text": "C# | Method Overriding" }, { "code": null, "e": 28114, "s": 28092, "text": "C# | Abstract Classes" }, { "code": null, "e": 28160, "s": 28114, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 28183, "s": 28160, "text": "Extension Method in C#" }, { "code": null, "e": 28205, "s": 28183, "text": "C# | Replace() Method" }, { "code": null, "e": 28245, "s": 28205, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 28267, "s": 28245, "text": "C# | Class and Object" } ]
Get MySQL maximum value from 3 different columns?
To get the maximum value from three different columns, use the GREATEST() function. The syntax is as follows SELECT GREATEST(yourColumnName1,yourColumnName2,yourColumnName3) AS anyAliasName FROM yourTableName; To understand the above syntax, let us create a table. The query to create a table is as follows mysql> create table MaxOfThreeColumnsDemo -> ( -> First int, -> Second int, -> Third int -> ); Query OK, 0 rows affected (0.73 sec) Insert some records in the table using insert command. The query is as follows mysql> insert into MaxOfThreeColumnsDemo values(30,90,60); Query OK, 1 row affected (0.16 sec) mysql> insert into MaxOfThreeColumnsDemo values(100,40,50); Query OK, 1 row affected (0.20 sec) mysql> insert into MaxOfThreeColumnsDemo values(101,290,150); Query OK, 1 row affected (0.22 sec) Display all records from the table using select statement. The query is as follows mysql> select *from MaxOfThreeColumnsDemo; The following is the output +-------+--------+-------+ | First | Second | Third | +-------+--------+-------+ | 30 | 90 | 60 | | 100 | 40 | 50 | | 101 | 290 | 150 | +-------+--------+-------+ 3 rows in set (0.00 sec) Here is the query to find the greatest of three columns mysql> select greatest(First,Second,Third) AS MAXValueOfThreeColumns from MaxOfThreeColumnsDemo; The following is the output +------------------------+ | MAXValueOfThreeColumns | +------------------------+ | 90 | | 100 | | 290 | +------------------------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1146, "s": 1062, "text": "To get the maximum value from three different columns, use the GREATEST() function." }, { "code": null, "e": 1171, "s": 1146, "text": "The syntax is as follows" }, { "code": null, "e": 1272, "s": 1171, "text": "SELECT GREATEST(yourColumnName1,yourColumnName2,yourColumnName3) AS anyAliasName FROM yourTableName;" }, { "code": null, "e": 1369, "s": 1272, "text": "To understand the above syntax, let us create a table. The query to create a table is as follows" }, { "code": null, "e": 1516, "s": 1369, "text": "mysql> create table MaxOfThreeColumnsDemo\n -> (\n -> First int,\n -> Second int,\n -> Third int\n -> );\nQuery OK, 0 rows affected (0.73 sec)" }, { "code": null, "e": 1571, "s": 1516, "text": "Insert some records in the table using insert command." }, { "code": null, "e": 1595, "s": 1571, "text": "The query is as follows" }, { "code": null, "e": 1884, "s": 1595, "text": "mysql> insert into MaxOfThreeColumnsDemo values(30,90,60);\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into MaxOfThreeColumnsDemo values(100,40,50);\nQuery OK, 1 row affected (0.20 sec)\nmysql> insert into MaxOfThreeColumnsDemo values(101,290,150);\nQuery OK, 1 row affected (0.22 sec)" }, { "code": null, "e": 1943, "s": 1884, "text": "Display all records from the table using select statement." }, { "code": null, "e": 1967, "s": 1943, "text": "The query is as follows" }, { "code": null, "e": 2010, "s": 1967, "text": "mysql> select *from MaxOfThreeColumnsDemo;" }, { "code": null, "e": 2038, "s": 2010, "text": "The following is the output" }, { "code": null, "e": 2252, "s": 2038, "text": "+-------+--------+-------+\n| First | Second | Third |\n+-------+--------+-------+\n| 30 | 90 | 60 |\n| 100 | 40 | 50 |\n| 101 | 290 | 150 |\n+-------+--------+-------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 2308, "s": 2252, "text": "Here is the query to find the greatest of three columns" }, { "code": null, "e": 2405, "s": 2308, "text": "mysql> select greatest(First,Second,Third) AS MAXValueOfThreeColumns from MaxOfThreeColumnsDemo;" }, { "code": null, "e": 2433, "s": 2405, "text": "The following is the output" }, { "code": null, "e": 2647, "s": 2433, "text": "+------------------------+\n| MAXValueOfThreeColumns |\n+------------------------+\n| 90 |\n| 100 |\n| 290 |\n+------------------------+\n3 rows in set (0.00 sec)" } ]
Data Types in C
Variables in C are associated with data type. Each data type requires an amount of memory and performs specific operations. There are some common data types in C − int − Used to store an integer value. int − Used to store an integer value. char − Used to store a single character. char − Used to store a single character. float − Used to store decimal numbers with single precision. float − Used to store decimal numbers with single precision. double − Used to store decimal numbers with double precision. double − Used to store decimal numbers with double precision. The following table displays data types in C language − Here is the syntax of datatypes in C language, data_type variable_name; Here is an example of datatypes in C language, Live Demo #include >stdio.h> int main() { // datatypes int a = 10; char b = 'S'; float c = 2.88; double d = 28.888; printf("Integer datatype : %d\n",a); printf("Character datatype : %c\n",b); printf("Float datatype : %f\n",c); printf("Double Float datatype : %lf\n",d); return 0; } Here is the output, Integer datatype : 10 Character datatype : S Float datatype : 2.880000 Double Float datatype : 28.888000
[ { "code": null, "e": 1186, "s": 1062, "text": "Variables in C are associated with data type. Each data type requires an amount of memory and performs specific operations." }, { "code": null, "e": 1226, "s": 1186, "text": "There are some common data types in C −" }, { "code": null, "e": 1264, "s": 1226, "text": "int − Used to store an integer value." }, { "code": null, "e": 1302, "s": 1264, "text": "int − Used to store an integer value." }, { "code": null, "e": 1343, "s": 1302, "text": "char − Used to store a single character." }, { "code": null, "e": 1384, "s": 1343, "text": "char − Used to store a single character." }, { "code": null, "e": 1445, "s": 1384, "text": "float − Used to store decimal numbers with single precision." }, { "code": null, "e": 1506, "s": 1445, "text": "float − Used to store decimal numbers with single precision." }, { "code": null, "e": 1568, "s": 1506, "text": "double − Used to store decimal numbers with double precision." }, { "code": null, "e": 1630, "s": 1568, "text": "double − Used to store decimal numbers with double precision." }, { "code": null, "e": 1686, "s": 1630, "text": "The following table displays data types in C language −" }, { "code": null, "e": 1733, "s": 1686, "text": "Here is the syntax of datatypes in C language," }, { "code": null, "e": 1758, "s": 1733, "text": "data_type variable_name;" }, { "code": null, "e": 1805, "s": 1758, "text": "Here is an example of datatypes in C language," }, { "code": null, "e": 1816, "s": 1805, "text": " Live Demo" }, { "code": null, "e": 2118, "s": 1816, "text": "#include >stdio.h>\nint main() {\n // datatypes\n int a = 10;\n char b = 'S';\n float c = 2.88;\n double d = 28.888;\n printf(\"Integer datatype : %d\\n\",a);\n printf(\"Character datatype : %c\\n\",b);\n printf(\"Float datatype : %f\\n\",c);\n printf(\"Double Float datatype : %lf\\n\",d);\n return 0;\n}" }, { "code": null, "e": 2138, "s": 2118, "text": "Here is the output," }, { "code": null, "e": 2243, "s": 2138, "text": "Integer datatype : 10\nCharacter datatype : S\nFloat datatype : 2.880000\nDouble Float datatype : 28.888000" } ]
Batch Script - String length
In DOS scripting, there is no length function defined for finding the length of a string. There are custom-defined functions which can be used for the same. Following is an example of a custom-defined function for seeing the length of a string. @echo off set str = Hello World call :strLen str strlen echo String is %strlen% characters long exit /b :strLen setlocal enabledelayedexpansion :strLen_Loop if not "!%1:~%len%!"=="" set /A len+=1 & goto :strLen_Loop (endlocal & set %2=%len%) goto :eof A few key things to keep in mind about the above program are − The actual code which finds the length of string is defined in the :strLen block. The actual code which finds the length of string is defined in the :strLen block. The length of the string is maintained in the variable len. The length of the string is maintained in the variable len. The above command produces the following output. 11 Print Add Notes Bookmark this page
[ { "code": null, "e": 2414, "s": 2169, "text": "In DOS scripting, there is no length function defined for finding the length of a string. There are custom-defined functions which can be used for the same. Following is an example of a custom-defined function for seeing the length of a string." }, { "code": null, "e": 2671, "s": 2414, "text": "@echo off\nset str = Hello World\ncall :strLen str strlen\necho String is %strlen% characters long\nexit /b\n\n:strLen\nsetlocal enabledelayedexpansion\n\n:strLen_Loop\n if not \"!%1:~%len%!\"==\"\" set /A len+=1 & goto :strLen_Loop\n(endlocal & set %2=%len%)\ngoto :eof" }, { "code": null, "e": 2734, "s": 2671, "text": "A few key things to keep in mind about the above program are −" }, { "code": null, "e": 2816, "s": 2734, "text": "The actual code which finds the length of string is defined in the :strLen block." }, { "code": null, "e": 2898, "s": 2816, "text": "The actual code which finds the length of string is defined in the :strLen block." }, { "code": null, "e": 2958, "s": 2898, "text": "The length of the string is maintained in the variable len." }, { "code": null, "e": 3018, "s": 2958, "text": "The length of the string is maintained in the variable len." }, { "code": null, "e": 3067, "s": 3018, "text": "The above command produces the following output." }, { "code": null, "e": 3071, "s": 3067, "text": "11\n" }, { "code": null, "e": 3078, "s": 3071, "text": " Print" }, { "code": null, "e": 3089, "s": 3078, "text": " Add Notes" } ]
Microsoft Interview Experience | On-Campus (Virtual) - GeeksforGeeks
05 Apr, 2021 Microsoft conducted entire process virtually due to COVID. Round 1: (Date 29.11.20) Online test:(90 min) CGPA criteria is 7.50 and open for CSE/MnC/EEE/ECE There were different sets with varied difficulties. Some sets were easy and some were difficult. There are 3 coding questions. My set consisted of following questions Longest Common Prefix of all given strings Input:{"geeksforgeeks", "geeks", "geek", "geezer"} Output:"gee" Input:{"apple", "ape", "april"} Output:"ap" Given an array and a number x. Find minimum length subarray whose sum is x. Input: A={1,2,3,4,5},x=3 Output: 1 There are 2 subarrays with sum 3 out of which {3} is the smallest one.So output is 1 Given an array of strings and a string x. Find no of strings in array which have prefix as x. Input: A={"Cisco","Citrix","Cipla"} ,x="Cit" Output: 1 There is only 1 string "Citrix" which contains "Cit" as prefix. Longest Common Prefix of all given strings Input:{"geeksforgeeks", "geeks", "geek", "geezer"} Output:"gee" Input:{"apple", "ape", "april"} Output:"ap" Input:{"geeksforgeeks", "geeks", "geek", "geezer"} Output:"gee" Input:{"apple", "ape", "april"} Output:"ap" Given an array and a number x. Find minimum length subarray whose sum is x. Input: A={1,2,3,4,5},x=3 Output: 1 There are 2 subarrays with sum 3 out of which {3} is the smallest one.So output is 1 Input: A={1,2,3,4,5},x=3 Output: 1 There are 2 subarrays with sum 3 out of which {3} is the smallest one.So output is 1 Given an array of strings and a string x. Find no of strings in array which have prefix as x. Input: A={"Cisco","Citrix","Cipla"} ,x="Cit" Output: 1 There is only 1 string "Citrix" which contains "Cit" as prefix. Input: A={"Cisco","Citrix","Cipla"} ,x="Cit" Output: 1 There is only 1 string "Citrix" which contains "Cit" as prefix. Few more questions which my friends got are Find LIS in given string of lowercase english letters Find LIS in given string of lowercase english letters Around 40 were shortlisted out of 170 students for interviews. Interviews were scheduled on Dec 1st 2020. Interview Round 1: (74 min ) There was only 1 interviewer which is held on MS teams . After a quick introduction of both of us he straightaway gave me a coding question There are N days. Given the dates and temperatures on all the N days in form of a tuple sorted based on temperature. Find k closest dates to a given temperature from the tuple. There are N days. Given the dates and temperatures on all the N days in form of a tuple sorted based on temperature. Find k closest dates to a given temperature from the tuple. I started solving and explained him a O(n) solution. After he seemed satisfied I told him the optimization involved and told him O(log n) solution using Binary Search. He asked me of several corner cases and verified code on all of them. Finally he seemed satisfied and he asked me for some questions. I asked him about the work culture and profile he is currently in. I was shortlisted for Round 2 within 5 min Interview Round 2: (64 min ) There was only 1 interviewer which is held on MS teams.He asked me the famous problem of LRU Cache in a different way but finally it means the same. I explained him all the approaches that I remember and the interviewer is also giving me tips in between when he feels I am stuck. There is No HR Round. Finally the official results were declared by our Placement cell after 9 hours and to my surprise I was one of the 20 candidates shortlisted for Microsoft SDE. Marketing Microsoft On-Campus Interview Experiences Microsoft Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Amazon Interview Experience for SDE-1 (Off-Campus) Amazon AWS Interview Experience for SDE-1 Zoho Interview | Set 3 (Off-Campus) Difference between ANN, CNN and RNN Amazon Interview Experience Amazon Interview Experience for SDE-1 JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021 Infosys Interview Experience for DSE 2022 Amazon Interview Experience (Off-Campus) 2022 Amazon Interview Experience for SDE-1 (On-Campus)
[ { "code": null, "e": 26465, "s": 26437, "text": "\n05 Apr, 2021" }, { "code": null, "e": 26524, "s": 26465, "text": "Microsoft conducted entire process virtually due to COVID." }, { "code": null, "e": 26549, "s": 26524, "text": "Round 1: (Date 29.11.20)" }, { "code": null, "e": 26570, "s": 26549, "text": "Online test:(90 min)" }, { "code": null, "e": 26624, "s": 26570, "text": " CGPA criteria is 7.50 and open for CSE/MnC/EEE/ECE" }, { "code": null, "e": 26751, "s": 26624, "text": "There were different sets with varied difficulties. Some sets were easy and some were difficult. There are 3 coding questions." }, { "code": null, "e": 26791, "s": 26751, "text": "My set consisted of following questions" }, { "code": null, "e": 27428, "s": 26791, "text": "Longest Common Prefix of all given strings Input:{\"geeksforgeeks\", \"geeks\", \"geek\", \"geezer\"}\n Output:\"gee\"\n \n Input:{\"apple\", \"ape\", \"april\"}\n Output:\"ap\" Given an array and a number x. Find minimum length subarray whose sum is x. Input: A={1,2,3,4,5},x=3\n Output: 1\n There are 2 subarrays with sum 3 out of \n which {3} is the smallest one.So output is 1 Given an array of strings and a string x. Find no of strings in array which have prefix as x. Input: A={\"Cisco\",\"Citrix\",\"Cipla\"} ,x=\"Cit\"\n Output: 1\n There is only 1 string \"Citrix\" \n which contains \"Cit\" as prefix." }, { "code": null, "e": 27614, "s": 27428, "text": "Longest Common Prefix of all given strings Input:{\"geeksforgeeks\", \"geeks\", \"geek\", \"geezer\"}\n Output:\"gee\"\n \n Input:{\"apple\", \"ape\", \"april\"}\n Output:\"ap\"" }, { "code": null, "e": 27758, "s": 27614, "text": " Input:{\"geeksforgeeks\", \"geeks\", \"geek\", \"geezer\"}\n Output:\"gee\"\n \n Input:{\"apple\", \"ape\", \"april\"}\n Output:\"ap\"" }, { "code": null, "e": 27974, "s": 27758, "text": " Given an array and a number x. Find minimum length subarray whose sum is x. Input: A={1,2,3,4,5},x=3\n Output: 1\n There are 2 subarrays with sum 3 out of \n which {3} is the smallest one.So output is 1" }, { "code": null, "e": 28114, "s": 27974, "text": " Input: A={1,2,3,4,5},x=3\n Output: 1\n There are 2 subarrays with sum 3 out of \n which {3} is the smallest one.So output is 1" }, { "code": null, "e": 28351, "s": 28114, "text": " Given an array of strings and a string x. Find no of strings in array which have prefix as x. Input: A={\"Cisco\",\"Citrix\",\"Cipla\"} ,x=\"Cit\"\n Output: 1\n There is only 1 string \"Citrix\" \n which contains \"Cit\" as prefix." }, { "code": null, "e": 28493, "s": 28351, "text": " Input: A={\"Cisco\",\"Citrix\",\"Cipla\"} ,x=\"Cit\"\n Output: 1\n There is only 1 string \"Citrix\" \n which contains \"Cit\" as prefix." }, { "code": null, "e": 28537, "s": 28493, "text": "Few more questions which my friends got are" }, { "code": null, "e": 28591, "s": 28537, "text": "Find LIS in given string of lowercase english letters" }, { "code": null, "e": 28645, "s": 28591, "text": "Find LIS in given string of lowercase english letters" }, { "code": null, "e": 28751, "s": 28645, "text": "Around 40 were shortlisted out of 170 students for interviews. Interviews were scheduled on Dec 1st 2020." }, { "code": null, "e": 28781, "s": 28751, "text": "Interview Round 1: (74 min )" }, { "code": null, "e": 28921, "s": 28781, "text": "There was only 1 interviewer which is held on MS teams . After a quick introduction of both of us he straightaway gave me a coding question" }, { "code": null, "e": 29098, "s": 28921, "text": "There are N days. Given the dates and temperatures on all the N days in form of a tuple sorted based on temperature. Find k closest dates to a given temperature from the tuple." }, { "code": null, "e": 29275, "s": 29098, "text": "There are N days. Given the dates and temperatures on all the N days in form of a tuple sorted based on temperature. Find k closest dates to a given temperature from the tuple." }, { "code": null, "e": 29653, "s": 29275, "text": "I started solving and explained him a O(n) solution. After he seemed satisfied I told him the optimization involved and told him O(log n) solution using Binary Search. He asked me of several corner cases and verified code on all of them. Finally he seemed satisfied and he asked me for some questions. I asked him about the work culture and profile he is currently in." }, { "code": null, "e": 29696, "s": 29653, "text": "I was shortlisted for Round 2 within 5 min" }, { "code": null, "e": 29727, "s": 29696, "text": " Interview Round 2: (64 min )" }, { "code": null, "e": 30011, "s": 29727, "text": "There was only 1 interviewer which is held on MS teams.He asked me the famous problem of LRU Cache in a different way but finally it means the same. I explained him all the approaches that I remember and the interviewer is also giving me tips in between when he feels I am stuck." }, { "code": null, "e": 30033, "s": 30011, "text": "There is No HR Round." }, { "code": null, "e": 30195, "s": 30033, "text": "Finally the official results were declared by our Placement cell after 9 hours and to my surprise I was one of the 20 candidates shortlisted for Microsoft SDE." }, { "code": null, "e": 30211, "s": 30201, "text": "Marketing" }, { "code": null, "e": 30221, "s": 30211, "text": "Microsoft" }, { "code": null, "e": 30231, "s": 30221, "text": "On-Campus" }, { "code": null, "e": 30253, "s": 30231, "text": "Interview Experiences" }, { "code": null, "e": 30263, "s": 30253, "text": "Microsoft" }, { "code": null, "e": 30361, "s": 30263, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30412, "s": 30361, "text": "Amazon Interview Experience for SDE-1 (Off-Campus)" }, { "code": null, "e": 30454, "s": 30412, "text": "Amazon AWS Interview Experience for SDE-1" }, { "code": null, "e": 30490, "s": 30454, "text": "Zoho Interview | Set 3 (Off-Campus)" }, { "code": null, "e": 30526, "s": 30490, "text": "Difference between ANN, CNN and RNN" }, { "code": null, "e": 30554, "s": 30526, "text": "Amazon Interview Experience" }, { "code": null, "e": 30592, "s": 30554, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 30664, "s": 30592, "text": "JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021" }, { "code": null, "e": 30706, "s": 30664, "text": "Infosys Interview Experience for DSE 2022" }, { "code": null, "e": 30752, "s": 30706, "text": "Amazon Interview Experience (Off-Campus) 2022" } ]
Convert singly linked list into circular linked list - GeeksforGeeks
16 Mar, 2022 Given a singly linked list, we have to convert it into circular linked list. For example, we have been given a singly linked list with four nodes and we want to convert this singly linked list into circular linked list. The above singly linked list is converted into circular linked list. Approach: The idea is to traverse the singly linked list and check if the node is the last node or not. If the node is the last node i.e pointing to NULL then make it point to the starting node i.e head node. Below is the implementation of this approach. C++ Java Python3 C# Javascript // Program for converting singly linked list// into circular linked list.#include <bits/stdc++.h> /* Linked list node */struct Node { int data; struct Node* next;}; // Function that convert singly linked list// into circular linked list.struct Node* circular(struct Node* head){ // declare a node variable start and // assign head node into start node. struct Node* start = head; // check that while head->next not equal // to NULL then head points to next node. while (head->next != NULL) head = head->next; // if head->next points to NULL then // start assign to the head->next node. head->next = start; return start;} void push(struct Node** head, int data){ // Allocate dynamic memory for newNode. struct Node* newNode = (struct Node*)malloc (sizeof(struct Node)); // Assign the data into newNode. newNode->data = data; // newNode->next assign the address of // head node. newNode->next = (*head); // newNode become the headNode. (*head) = newNode;} // Function that display the elements of// circular linked list.void displayList(struct Node* node){ struct Node* start = node; while (node->next != start) { printf("%d ", node->data); node = node->next; } // Display the last node of circular // linked list. printf("%d ", node->data);} // Driver program to test the functionsint main(){ // Start with empty list struct Node* head = NULL; // Using push() function to construct // singly linked list // 17->22->13->14->15 push(&head, 15); push(&head, 14); push(&head, 13); push(&head, 22); push(&head, 17); // Call the circular_list function that // convert singly linked list to circular // linked list. circular(head); printf("Display list: \n"); displayList(head); return 0;} // Program for converting// singly linked list into// circular linked list.class GFG{ /*Linked list node */static class Node{ int data; Node next;}; // Function that convert// singly linked list into// circular linked list.static Node circular(Node head){ // declare a node variable // start and assign head // node into start node. Node start = head; // check that while head.next // not equal to null then head // points to next node. while (head.next != null) head = head.next; // if head.next points to null // then start assign to the // head.next node. head.next = start; return start;} static Node push(Node head, int data){ // Allocate dynamic memory // for newNode. Node newNode = new Node(); // Assign the data into newNode. newNode.data = data; // newNode.next assign the // address of head node. newNode.next = (head); // newNode become the headNode. (head) = newNode; return head;} // Function that display the elements// of circular linked list.static void displayList( Node node){ Node start = node; while (node.next != start) { System.out.print(" "+ node.data); node = node.next; } // Display the last node of // circular linked list. System.out.print(" " + node.data);} // Driver Codepublic static void main(String args[]){ // Start with empty list Node head = null; // Using push() function to // convert singly linked list // 17.22.13.14.15 head = push(head, 15); head = push(head, 14); head = push(head, 13); head = push(head, 22); head = push(head, 17); // Call the circular_list function // that convert singly linked // list to circular linked list. circular(head); System.out.print("Display list: \n"); displayList(head);}} // This code is contributed// by Arnab Kundu # Python3 program for converting# singly linked list into# circular linked list.import sys # Linked list nodeclass Node: def __init__(self,data): self.data = data self.next = None def push(head, data): if not head: return Node(data) # Allocate dynamic memory # for newNode. # Assign the data into newNode. newNode = Node(data) # newNode.next assign the # address of head node. newNode.next = head # newNode become the headNode. head = newNode return head # Function that convert# singly linked list into# circular linked list.def circular(head): # declare a node variable # start and assign head # node into start node. start = head # check that while head.next # not equal to null then head # points to next node. while(head.next is not None): head = head.next # if head.next points to null # then start assign to the # head.next node. head.next = start return start # Function that display the elements# of circular linked list.def displayList(node): start = node while(node.next is not start): print("{} ".format(node.data),end="") node=node.next # Display the last node of # circular linked list. print("{} ".format(node.data),end="") # Driver Codeif __name__=='__main__': # Start with empty list head=None # Using push() function to # convert singly linked list # 17.22.13.14.15 head=push(head,15) head=push(head,14) head=push(head,13) head=push(head,22) head=push(head,17) # Call the circular_list function # that convert singly linked # list to circular linked list. circular(head) print("Display List:") displayList(head) # This Code is Contributed By Vikash Kumar 37 // C# Program for converting// singly linked list into// circular linked list.using System; class GFG{ /*Linked list node */ public class Node { public int data; public Node next; }; // Function that convert // singly linked list into // circular linked list. static Node circular(Node head) { // declare a node variable // start and assign head // node into start node. Node start = head; // check that while head.next // not equal to null then head // points to next node. while (head.next != null) head = head.next; // if head.next points to null // then start assign to the // head.next node. head.next = start; return start; } static Node push(Node head, int data) { // Allocate dynamic memory // for newNode. Node newNode = new Node(); // Assign the data into newNode. newNode.data = data; // newNode.next assign the // address of head node. newNode.next = (head); // newNode become the headNode. (head) = newNode; return head; } // Function that display the elements // of circular linked list. static void displayList( Node node) { Node start = node; while (node.next != start) { Console.Write(" " + node.data); node = node.next; } // Display the last node of // circular linked list. Console.Write(" " + node.data); } // Driver Code public static void Main(String []args) { // Start with empty list Node head = null; // Using push() function to // convert singly linked list // 17.22.13.14.15 head = push(head, 15); head = push(head, 14); head = push(head, 13); head = push(head, 22); head = push(head, 17); // Call the circular_list function // that convert singly linked // list to circular linked list. circular(head); Console.Write("Display list: \n"); displayList(head); }} // This code is contributed 29AjayKumar <script>// Javascript Program for converting// singly linked list into// circular linked list. /* Linked list node */class Node{ constructor(val) { this.data = val; this.next = null; } } // Function that convert // singly linked list into // circular linked list. function circular( head) { // declare a node variable // start and assign head // node into start node. start = head; // check that while head.next // not equal to null then head // points to next node. while (head.next != null) head = head.next; // if head.next points to null // then start assign to the // head.next node. head.next = start; return start; } function push( head , data) { // Allocate dynamic memory // for newNode. newNode = new Node(); // Assign the data into newNode. newNode.data = data; // newNode.next assign the // address of head node. newNode.next = (head); // newNode become the headNode. (head) = newNode; return head; } // Function that display the elements // of circular linked list. function displayList( node) { start = node; while (node.next != start) { document.write(" " + node.data); node = node.next; } // Display the last node of // circular linked list. document.write(" " + node.data); } // Driver Code // Start with empty list head = null; // Using push() function to // convert singly linked list // 17.22.13.14.15 head = push(head, 15); head = push(head, 14); head = push(head, 13); head = push(head, 22); head = push(head, 17); // Call the circular_list function // that convert singly linked // list to circular linked list. circular(head); document.write("Display list: <br/>"); displayList(head); // This code is contributed by gauravrajput1</script> Output: Display list: 17 22 13 14 15 YouTubeGeeksforGeeks507K subscribersConvert singly linked list into circular linked list | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:43•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=hLz1HXsuyvw" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Dharmendra kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. andrew1234 29AjayKumar Vikash Kumar 37 nidhi_biet GauravRajput1 simmytarika5 circular linked list Linked List Linked List circular linked list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Linked List | Set 1 (Introduction) Linked List | Set 2 (Inserting a node) Stack Data Structure (Introduction and Program) Linked List | Set 3 (Deleting a node) LinkedList in Java Linked List vs Array Detect loop in a linked list Merge two sorted linked lists Find the middle of a given linked list Delete a Linked List node at a given position
[ { "code": null, "e": 32366, "s": 32338, "text": "\n16 Mar, 2022" }, { "code": null, "e": 32587, "s": 32366, "text": "Given a singly linked list, we have to convert it into circular linked list. For example, we have been given a singly linked list with four nodes and we want to convert this singly linked list into circular linked list. " }, { "code": null, "e": 32658, "s": 32587, "text": "The above singly linked list is converted into circular linked list. " }, { "code": null, "e": 32916, "s": 32660, "text": "Approach: The idea is to traverse the singly linked list and check if the node is the last node or not. If the node is the last node i.e pointing to NULL then make it point to the starting node i.e head node. Below is the implementation of this approach. " }, { "code": null, "e": 32920, "s": 32916, "text": "C++" }, { "code": null, "e": 32925, "s": 32920, "text": "Java" }, { "code": null, "e": 32933, "s": 32925, "text": "Python3" }, { "code": null, "e": 32936, "s": 32933, "text": "C#" }, { "code": null, "e": 32947, "s": 32936, "text": "Javascript" }, { "code": "// Program for converting singly linked list// into circular linked list.#include <bits/stdc++.h> /* Linked list node */struct Node { int data; struct Node* next;}; // Function that convert singly linked list// into circular linked list.struct Node* circular(struct Node* head){ // declare a node variable start and // assign head node into start node. struct Node* start = head; // check that while head->next not equal // to NULL then head points to next node. while (head->next != NULL) head = head->next; // if head->next points to NULL then // start assign to the head->next node. head->next = start; return start;} void push(struct Node** head, int data){ // Allocate dynamic memory for newNode. struct Node* newNode = (struct Node*)malloc (sizeof(struct Node)); // Assign the data into newNode. newNode->data = data; // newNode->next assign the address of // head node. newNode->next = (*head); // newNode become the headNode. (*head) = newNode;} // Function that display the elements of// circular linked list.void displayList(struct Node* node){ struct Node* start = node; while (node->next != start) { printf(\"%d \", node->data); node = node->next; } // Display the last node of circular // linked list. printf(\"%d \", node->data);} // Driver program to test the functionsint main(){ // Start with empty list struct Node* head = NULL; // Using push() function to construct // singly linked list // 17->22->13->14->15 push(&head, 15); push(&head, 14); push(&head, 13); push(&head, 22); push(&head, 17); // Call the circular_list function that // convert singly linked list to circular // linked list. circular(head); printf(\"Display list: \\n\"); displayList(head); return 0;}", "e": 34830, "s": 32947, "text": null }, { "code": "// Program for converting// singly linked list into// circular linked list.class GFG{ /*Linked list node */static class Node{ int data; Node next;}; // Function that convert// singly linked list into// circular linked list.static Node circular(Node head){ // declare a node variable // start and assign head // node into start node. Node start = head; // check that while head.next // not equal to null then head // points to next node. while (head.next != null) head = head.next; // if head.next points to null // then start assign to the // head.next node. head.next = start; return start;} static Node push(Node head, int data){ // Allocate dynamic memory // for newNode. Node newNode = new Node(); // Assign the data into newNode. newNode.data = data; // newNode.next assign the // address of head node. newNode.next = (head); // newNode become the headNode. (head) = newNode; return head;} // Function that display the elements// of circular linked list.static void displayList( Node node){ Node start = node; while (node.next != start) { System.out.print(\" \"+ node.data); node = node.next; } // Display the last node of // circular linked list. System.out.print(\" \" + node.data);} // Driver Codepublic static void main(String args[]){ // Start with empty list Node head = null; // Using push() function to // convert singly linked list // 17.22.13.14.15 head = push(head, 15); head = push(head, 14); head = push(head, 13); head = push(head, 22); head = push(head, 17); // Call the circular_list function // that convert singly linked // list to circular linked list. circular(head); System.out.print(\"Display list: \\n\"); displayList(head);}} // This code is contributed// by Arnab Kundu", "e": 36719, "s": 34830, "text": null }, { "code": "# Python3 program for converting# singly linked list into# circular linked list.import sys # Linked list nodeclass Node: def __init__(self,data): self.data = data self.next = None def push(head, data): if not head: return Node(data) # Allocate dynamic memory # for newNode. # Assign the data into newNode. newNode = Node(data) # newNode.next assign the # address of head node. newNode.next = head # newNode become the headNode. head = newNode return head # Function that convert# singly linked list into# circular linked list.def circular(head): # declare a node variable # start and assign head # node into start node. start = head # check that while head.next # not equal to null then head # points to next node. while(head.next is not None): head = head.next # if head.next points to null # then start assign to the # head.next node. head.next = start return start # Function that display the elements# of circular linked list.def displayList(node): start = node while(node.next is not start): print(\"{} \".format(node.data),end=\"\") node=node.next # Display the last node of # circular linked list. print(\"{} \".format(node.data),end=\"\") # Driver Codeif __name__=='__main__': # Start with empty list head=None # Using push() function to # convert singly linked list # 17.22.13.14.15 head=push(head,15) head=push(head,14) head=push(head,13) head=push(head,22) head=push(head,17) # Call the circular_list function # that convert singly linked # list to circular linked list. circular(head) print(\"Display List:\") displayList(head) # This Code is Contributed By Vikash Kumar 37", "e": 38493, "s": 36719, "text": null }, { "code": "// C# Program for converting// singly linked list into// circular linked list.using System; class GFG{ /*Linked list node */ public class Node { public int data; public Node next; }; // Function that convert // singly linked list into // circular linked list. static Node circular(Node head) { // declare a node variable // start and assign head // node into start node. Node start = head; // check that while head.next // not equal to null then head // points to next node. while (head.next != null) head = head.next; // if head.next points to null // then start assign to the // head.next node. head.next = start; return start; } static Node push(Node head, int data) { // Allocate dynamic memory // for newNode. Node newNode = new Node(); // Assign the data into newNode. newNode.data = data; // newNode.next assign the // address of head node. newNode.next = (head); // newNode become the headNode. (head) = newNode; return head; } // Function that display the elements // of circular linked list. static void displayList( Node node) { Node start = node; while (node.next != start) { Console.Write(\" \" + node.data); node = node.next; } // Display the last node of // circular linked list. Console.Write(\" \" + node.data); } // Driver Code public static void Main(String []args) { // Start with empty list Node head = null; // Using push() function to // convert singly linked list // 17.22.13.14.15 head = push(head, 15); head = push(head, 14); head = push(head, 13); head = push(head, 22); head = push(head, 17); // Call the circular_list function // that convert singly linked // list to circular linked list. circular(head); Console.Write(\"Display list: \\n\"); displayList(head); }} // This code is contributed 29AjayKumar", "e": 40679, "s": 38493, "text": null }, { "code": "<script>// Javascript Program for converting// singly linked list into// circular linked list. /* Linked list node */class Node{ constructor(val) { this.data = val; this.next = null; } } // Function that convert // singly linked list into // circular linked list. function circular( head) { // declare a node variable // start and assign head // node into start node. start = head; // check that while head.next // not equal to null then head // points to next node. while (head.next != null) head = head.next; // if head.next points to null // then start assign to the // head.next node. head.next = start; return start; } function push( head , data) { // Allocate dynamic memory // for newNode. newNode = new Node(); // Assign the data into newNode. newNode.data = data; // newNode.next assign the // address of head node. newNode.next = (head); // newNode become the headNode. (head) = newNode; return head; } // Function that display the elements // of circular linked list. function displayList( node) { start = node; while (node.next != start) { document.write(\" \" + node.data); node = node.next; } // Display the last node of // circular linked list. document.write(\" \" + node.data); } // Driver Code // Start with empty list head = null; // Using push() function to // convert singly linked list // 17.22.13.14.15 head = push(head, 15); head = push(head, 14); head = push(head, 13); head = push(head, 22); head = push(head, 17); // Call the circular_list function // that convert singly linked // list to circular linked list. circular(head); document.write(\"Display list: <br/>\"); displayList(head); // This code is contributed by gauravrajput1</script>", "e": 42832, "s": 40679, "text": null }, { "code": null, "e": 42842, "s": 42832, "text": "Output: " }, { "code": null, "e": 42871, "s": 42842, "text": "Display list:\n17 22 13 14 15" }, { "code": null, "e": 43724, "s": 42873, "text": "YouTubeGeeksforGeeks507K subscribersConvert singly linked list into circular linked list | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:43•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=hLz1HXsuyvw\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 44149, "s": 43724, "text": "This article is contributed by Dharmendra kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 44160, "s": 44149, "text": "andrew1234" }, { "code": null, "e": 44172, "s": 44160, "text": "29AjayKumar" }, { "code": null, "e": 44188, "s": 44172, "text": "Vikash Kumar 37" }, { "code": null, "e": 44199, "s": 44188, "text": "nidhi_biet" }, { "code": null, "e": 44213, "s": 44199, "text": "GauravRajput1" }, { "code": null, "e": 44226, "s": 44213, "text": "simmytarika5" }, { "code": null, "e": 44247, "s": 44226, "text": "circular linked list" }, { "code": null, "e": 44259, "s": 44247, "text": "Linked List" }, { "code": null, "e": 44271, "s": 44259, "text": "Linked List" }, { "code": null, "e": 44292, "s": 44271, "text": "circular linked list" }, { "code": null, "e": 44390, "s": 44292, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 44425, "s": 44390, "text": "Linked List | Set 1 (Introduction)" }, { "code": null, "e": 44464, "s": 44425, "text": "Linked List | Set 2 (Inserting a node)" }, { "code": null, "e": 44512, "s": 44464, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 44550, "s": 44512, "text": "Linked List | Set 3 (Deleting a node)" }, { "code": null, "e": 44569, "s": 44550, "text": "LinkedList in Java" }, { "code": null, "e": 44590, "s": 44569, "text": "Linked List vs Array" }, { "code": null, "e": 44619, "s": 44590, "text": "Detect loop in a linked list" }, { "code": null, "e": 44649, "s": 44619, "text": "Merge two sorted linked lists" }, { "code": null, "e": 44688, "s": 44649, "text": "Find the middle of a given linked list" } ]